From 60d27403fc49dcc8b32d8e26c6c4f54ab5b3870c Mon Sep 17 00:00:00 2001 From: Grisha Lavrov Date: Fri, 4 Dec 2026 18:47:43 +0100 Subject: [PATCH] admin: AI key must be printable ASCII, no 500 on non-ASCII key The key goes into the Authorization header; httpx cannot encode non-ASCII there and raised UnicodeEncodeError, so POST /admin/ai-settings/test answered 500 when Schemathesis fuzzed such a key. The schema now rejects it with 422 (test and save), and the services guard keys from env or old DB rows. --- app/schemas/ai_settings.py | 9 +++++++-- app/services/ai_review.py | 5 +++++ app/services/ai_settings.py | 8 ++++++++ tests/test_ai_review.py | 9 +++++++++ tests/test_ai_settings.py | 20 ++++++++++++++++++++ 5 files changed, 49 insertions(+), 2 deletions(-) diff --git a/app/schemas/ai_settings.py b/app/schemas/ai_settings.py index 1519f6c..08041f0 100644 --- a/app/schemas/ai_settings.py +++ b/app/schemas/ai_settings.py @@ -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 diff --git a/app/services/ai_review.py b/app/services/ai_review.py index d08baf7..20868e1 100644 --- a/app/services/ai_review.py +++ b/app/services/ai_review.py @@ -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 @@ -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: diff --git a/app/services/ai_settings.py b/app/services/ai_settings.py index 1d7e4b6..768f169 100644 --- a/app/services/ai_settings.py +++ b/app/services/ai_settings.py @@ -33,6 +33,7 @@ AIModelOption, AITestResult, AIUsage, + is_header_safe_key, ) KeySource = Literal["admin", "env"] @@ -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", diff --git a/tests/test_ai_review.py b/tests/test_ai_review.py index dfa91fb..988d53d 100644 --- a/tests/test_ai_review.py +++ b/tests/test_ai_review.py @@ -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) diff --git a/tests/test_ai_settings.py b/tests/test_ai_settings.py index 20aa486..73b6a12 100644 --- a/tests/test_ai_settings.py +++ b/tests/test_ai_settings.py @@ -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}, @@ -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 == []