Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 7 additions & 2 deletions app/schemas/ai_settings.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,14 +9,19 @@
MODEL_PATTERN = r"^[A-Za-z0-9][A-Za-z0-9._:/-]{0,79}$"


def is_header_safe_key(value: str) -> bool:
"""Ключ уходит в заголовок ``Authorization``: только печатные ASCII-символы без пробелов."""
return value.isascii() and value.isprintable() and not any(ch.isspace() for ch in value)


def _clean_key(value: str | None) -> str | None:
if value is None:
return None
value = value.strip()
if not value:
return None
if any(ch.isspace() for ch in value) or not value.isprintable():
raise ValueError("Ключ не должен содержать пробелов и переводов строки")
if not is_header_safe_key(value):
raise ValueError("Ключ может содержать только латинские буквы, цифры и знаки, без пробелов")
return value


Expand Down
5 changes: 5 additions & 0 deletions app/services/ai_review.py
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@
from app.db.models.auth import User
from app.repositories.question import QuestionRepository
from app.schemas.ai_review import AIReviewResponse, AIReviewStatus
from app.schemas.ai_settings import is_header_safe_key
from app.services.ai_settings import AIConfig, load_ai_config

QUESTION_TEXT_LIMIT = 3000
Expand Down Expand Up @@ -284,6 +285,10 @@ async def review_answer(
ai = await load_ai_config(session)
if not ai.enabled:
raise AIDisabledError("ИИ-проверка ответов не настроена или выключена администратором")
if not is_header_safe_key(ai.api_key):
# httpx не закодирует такой ключ в заголовок: отказываем до резерва, лимит не тратим
log.error("AI review: API key has non-ASCII or non-printable characters")
raise AIProviderError("ИИ-проверка временно недоступна. Попробуйте позже.")

question = await QuestionRepository(session).get_by_id(question_id, user)
if question is None:
Expand Down
8 changes: 8 additions & 0 deletions app/services/ai_settings.py
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@
AIModelOption,
AITestResult,
AIUsage,
is_header_safe_key,
)

KeySource = Literal["admin", "env"]
Expand Down Expand Up @@ -221,6 +222,13 @@ async def check_connection(
use_model = model or cfg.model
if not key:
return AITestResult(ok=False, model=use_model, message="Ключ не задан")
if not is_header_safe_key(key):
# Схема запроса такой ключ не пропустит; сюда попадает ключ из окружения или старой строки БД
return AITestResult(
ok=False,
model=use_model,
message="Ключ содержит недопустимые символы: введите его заново",
)
try:
response = await client.post(
f"{cfg.base_url.rstrip('/')}/chat/completions",
Expand Down
9 changes: 9 additions & 0 deletions tests/test_ai_review.py
Original file line number Diff line number Diff line change
Expand Up @@ -147,6 +147,15 @@ async def test_disabled_returns_503_without_calling_provider(
assert provider.calls == []


async def test_non_ascii_key_is_502_without_reserving_limit(ai_on, provider, user_client, session):
ai_on(AI_API_KEY="sk-ключ-0123456789")
q = await question_with_answer(session)
r = await user_client.post(f"/api/v1/questions/{q.id}/ai-review", json={"answer": "x"})
assert r.status_code == 502 and r.json()["code"] == "ai_unavailable"
assert provider.calls == []
assert await rows(session) == []


async def test_daily_limit_counts_failed_calls_too(ai_on, provider, user_client, session):
ai_on(AI_DAILY_LIMIT_PER_USER=2)
q = await question_with_answer(session)
Expand Down
20 changes: 20 additions & 0 deletions tests/test_ai_settings.py
Original file line number Diff line number Diff line change
Expand Up @@ -111,6 +111,9 @@ async def test_key_encrypted_with_another_secret_is_reported(no_env_key, admin_c
"payload",
[
{"api_key": "two words"},
{"api_key": "sk-ключ-0123456789"},
{"api_key": "sk-caf\u00e9-0123456789"},
{"api_key": "sk-\x7f-0123456789"},
{"model": "bad model!"},
{"daily_limit_per_user": -1},
{"daily_limit_per_user": 100000},
Expand Down Expand Up @@ -146,3 +149,20 @@ async def test_connection_check_without_key_does_not_call_provider(
body = (await admin_client.post(f"{URL}/test", json={})).json()
assert body == {"ok": False, "model": "openai/gpt-5.6-luna", "message": "Ключ не задан"}
assert provider.calls == []


@pytest.mark.parametrize("bad_key", ["sk-ключ-0123456789", "sk-caf\u00e9", "sk-\u2028x"])
async def test_connection_check_rejects_non_ascii_key(no_env_key, admin_client, provider, bad_key):
"""Не-ASCII ключ не кодируется в заголовок Authorization: 422 вместо 500 от httpx."""
r = await admin_client.post(f"{URL}/test", json={"api_key": bad_key})
assert r.status_code == 422, r.text
assert provider.calls == []


async def test_connection_check_reports_non_ascii_env_key(monkeypatch, admin_client, provider):
monkeypatch.setattr(settings, "ai", AISettings(AI_API_KEY="sk-ключ-0123456789"))
r = await admin_client.post(f"{URL}/test", json={})
assert r.status_code == 200, r.text
body = r.json()
assert body["ok"] is False and "недопустимые символы" in body["message"]
assert provider.calls == []
Loading