feat: маскировка сырых ошибок провайдера в чате (не утекают юзеру)

Инцидент 2026-07-15: истёкший OAuth слал юзеру сырой 'API Error: 401 {...}'.
Теперь _stream_and_save детектит ошибку провайдера (401/rate/overloaded) в стриме,
подменяет на человеческое сообщение и НЕ сохраняет сырое в историю; log_action(502).
error_mask.py — чистый модуль детекции, покрыт юнитом (mutation-safe) + интеграционным
тестом на реальном _stream_and_save (сырой 401 не проходит; нормальный ответ цел).
APP_VERSION → 2026-07-15.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
This commit is contained in:
anor
2026-07-15 19:39:42 +10:00
co-authored by Claude Opus 4.8
parent f1c9bcf51d
commit 304c13a3da
5 changed files with 224 additions and 3 deletions
+31 -3
View File
@@ -15,6 +15,7 @@ from fastapi.staticfiles import StaticFiles
from auth import authenticate, verify_token, make_download_ticket, verify_download_ticket
from db import clear_history, get_audit_log, get_feedback, get_history, get_history_any_user, init_db, list_sessions, log_action, ping as db_ping, save_feedback, save_message
from tus_upload import register_tus
from error_mask import looks_like_provider_error, PROVIDER_ERROR_MESSAGE
# Backend: "claude" (Docker sandbox), "glm" (GLM-5 + CAG), "auto" (route by task)
AI_BACKEND = os.environ.get("AI_BACKEND", "claude")
@@ -136,7 +137,7 @@ MAX_MESSAGE_LEN = 10_000
# ⚠️ Версия UI — единый источник. БАМПАТЬ ПРИ КАЖДОМ ДЕПЛОЕ (формат: YYYY-MM-DD + буква).
# Фронт берёт её через GET /api/version (chat.html + admin.html, элемент .app-version).
APP_VERSION = "2026-07-03b"
APP_VERSION = "2026-07-15"
# Audit: path → action name mapping
_AUDIT_MAP = [
@@ -434,6 +435,19 @@ def _work_dir_snapshot(work_dir: Path) -> dict:
return snap
def _sse_payload_text(chunk: str) -> str:
"""Собрать text/result из data-строк SSE-чанка (для детекции ошибок)."""
parts = []
for line in chunk.split("\n"):
if line.startswith("data: "):
try:
d = json.loads(line[6:])
parts.append(d.get("text") or d.get("result") or "")
except Exception:
pass
return "".join(parts)
async def _stream_and_save(message: str, user: str, tab_id: str):
"""Wrap stream_claude to save messages to DB."""
save_message(user, tab_id, "user", message)
@@ -442,11 +456,23 @@ async def _stream_and_save(message: str, user: str, tab_id: str):
work_dir = get_work_dir(user, tab_id)
before = _work_dir_snapshot(work_dir)
full_response = ""
errored = False
async for chunk in stream_claude(message, user, tab_id):
# Guard: сырая ошибка провайдера (401/rate/overloaded) не должна утечь
# юзеру ни в стрим, ни в историю (инцидент 2026-07-15). Маскируем и
# обрываем — после ошибки провайдера полезного ответа уже не будет.
if "event: text" in chunk or "event: done" in chunk:
payload = _sse_payload_text(chunk)
if payload and looks_like_provider_error(payload):
errored = True
log_action(user, "agent_error", "STREAM", "/api/chat",
payload[:200], None, 502)
yield f"event: text\ndata: {json.dumps({'text': PROVIDER_ERROR_MESSAGE}, ensure_ascii=False)}\n\n"
yield f"event: done\ndata: {json.dumps({'result': ''}, ensure_ascii=False)}\n\n"
break
yield chunk
# Collect text for saving
if "event: text" in chunk:
import json
for line in chunk.split("\n"):
if line.startswith("data: "):
try:
@@ -455,7 +481,6 @@ async def _stream_and_save(message: str, user: str, tab_id: str):
except Exception:
pass
elif "event: done" in chunk:
import json
for line in chunk.split("\n"):
if line.startswith("data: "):
try:
@@ -464,6 +489,9 @@ async def _stream_and_save(message: str, user: str, tab_id: str):
full_response = d["result"]
except Exception:
pass
if errored:
save_message(user, tab_id, "assistant", PROVIDER_ERROR_MESSAGE)
return
if full_response:
save_message(user, tab_id, "assistant", full_response)
# Новые/изменённые файлы за время ответа → кнопки скачивания в чате.