From 82c6f7726eb2a1697cf165ec86402fe7d05268f2 Mon Sep 17 00:00:00 2001 From: anor Date: Fri, 3 Jul 2026 11:00:20 +1000 Subject: [PATCH] =?UTF-8?q?fix:=20=D0=B0=D0=B4=D0=BC=D0=B8=D0=BD=20=D0=B2?= =?UTF-8?q?=20=D1=87=D1=83=D0=B6=D0=BE=D0=BC=20=D0=B4=D0=B8=D0=B0=D0=BB?= =?UTF-8?q?=D0=BE=D0=B3=D0=B5=20=D0=BF=D0=BE=D0=BB=D1=83=D1=87=D0=B0=D0=BB?= =?UTF-8?q?=20404=20=D0=BD=D0=B0=20=D1=81=D0=BA=D0=B0=D1=87=D0=B8=D0=B2?= =?UTF-8?q?=D0=B0=D0=BD=D0=B8=D0=B8=20=D1=84=D0=B0=D0=B9=D0=BB=D0=BE=D0=B2?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit /api/history для админа умеет показывать чужой диалог, а /api/files и /api/files/{filename} резолвили work_dir только по логину запрашивающего — кнопки скачивания в просматриваемом диалоге давали 404 (инцидент 2026-07-03, yuri111@inbox.ru в диалоге smeta/b1f47437). Теперь оба эндпоинта зеркалят паттерн истории: пусто/нет файла + role=admin → файлы владельца вкладки (db.get_tab_owner). Не-админам чужое по-прежнему 404/пусто (тесты-гарды). Сообщение об ошибке скачивания больше не врёт «файл не существует» — показывает реальный статус. Версия 2026-07-03b. Co-Authored-By: Claude Fable 5 --- db.py | 10 ++++ main.py | 30 +++++++++-- static/chat.html | 2 +- tests/test_admin_foreign_files.py | 85 +++++++++++++++++++++++++++++++ 4 files changed, 123 insertions(+), 4 deletions(-) create mode 100644 tests/test_admin_foreign_files.py diff --git a/db.py b/db.py index ec75212..61437b4 100644 --- a/db.py +++ b/db.py @@ -271,6 +271,16 @@ def get_history_any_user(tab_id: str, limit: int = 100) -> list[dict]: return [dict(r) for r in reversed(rows)] +def get_tab_owner(tab_id: str) -> str | None: + """Username who owns a dialog tab (author of its first message).""" + with _conn() as conn: + row = conn.execute( + "SELECT username FROM messages WHERE tab_id = ? ORDER BY id LIMIT 1", + (tab_id,), + ).fetchone() + return row["username"] if row else None + + # === Audit Log === def log_action(username: str | None, action: str, method: str, path: str, diff --git a/main.py b/main.py index 6bfaa53..b568437 100644 --- a/main.py +++ b/main.py @@ -136,7 +136,7 @@ MAX_MESSAGE_LEN = 10_000 # ⚠️ Версия UI — единый источник. БАМПАТЬ ПРИ КАЖДОМ ДЕПЛОЕ (формат: YYYY-MM-DD + буква). # Фронт берёт её через GET /api/version (chat.html + admin.html, элемент .app-version). -APP_VERSION = "2026-07-03" +APP_VERSION = "2026-07-03b" # Audit: path → action name mapping _AUDIT_MAP = [ @@ -578,11 +578,31 @@ async def upload(request: Request, file: UploadFile): return {"filename": safe_name, "size": total} +def _admin_tab_owner(request: Request, user: str, tab_id: str) -> str | None: + """Владелец вкладки, если её смотрит админ (зеркало фолбэка /api/history). + + Не-админам и для собственных вкладок возвращает None.""" + from auth import get_token_role + token = request.headers.get("authorization", "").removeprefix("Bearer ").strip() + if get_token_role(token) != "admin": + return None + from db import get_tab_owner + owner = get_tab_owner(tab_id) + if not owner or owner == user: + return None + return owner + + @app.get("/api/files") async def files(request: Request): user = _get_user(request) tab_id = request.headers.get("x-tab-id", "default") - return list_user_files(user, tab_id) + result = list_user_files(user, tab_id) + if not result: + owner = _admin_tab_owner(request, user, tab_id) + if owner: + result = list_user_files(owner, tab_id) + return result @app.get("/api/files/{filename}") @@ -592,7 +612,11 @@ async def download_file(filename: str, request: Request): safe_name = Path(filename).name fpath = get_work_dir(user, tab_id) / safe_name if not fpath.exists() or not fpath.is_file(): - raise HTTPException(404, "File not found") + owner = _admin_tab_owner(request, user, tab_id) + if owner: + fpath = get_work_dir(owner, tab_id) / safe_name + if not fpath.exists() or not fpath.is_file(): + raise HTTPException(404, "File not found") return FileResponse(fpath, filename=filename) diff --git a/static/chat.html b/static/chat.html index 7abfade..82a31ad 100644 --- a/static/chat.html +++ b/static/chat.html @@ -1034,7 +1034,7 @@ function downloadWorkFile(name) { // Немедленный revoke в Firefox может оборвать ещё не начавшееся скачивание setTimeout(() => URL.revokeObjectURL(u), 30000); }) - .catch(() => addMsg('error', 'Не удалось скачать «' + name + '» — файл больше не существует.')); + .catch(err => addMsg('error', 'Не удалось скачать «' + name + '» (ошибка ' + err.message + '). Обновите страницу и попробуйте ещё раз.')); } function fmtSize(size) { diff --git a/tests/test_admin_foreign_files.py b/tests/test_admin_foreign_files.py new file mode 100644 index 0000000..ad31da2 --- /dev/null +++ b/tests/test_admin_foreign_files.py @@ -0,0 +1,85 @@ +"""Admin viewing a foreign dialog must be able to download its files. + +/api/history already falls back to any-user history for admins; /api/files and +/api/files/{filename} resolved work_dir by the REQUESTER's username only → +admin opening a user's dialog got 404 on every download button (prod incident +2026-07-03, dialog smeta/b1f47437, admin yuri111@inbox.ru). +""" + +import importlib +import os +import sys + +import pytest + +ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) +if ROOT not in sys.path: + sys.path.insert(0, ROOT) + +TAB = "tab-foreign" +OWNER = "smeta" + + +@pytest.fixture() +def env(tmp_path, monkeypatch): + """main.app + TestClient on isolated DB/DATA_DIR with a known JWT secret.""" + monkeypatch.setenv("DB_PATH", str(tmp_path / "t.db")) + monkeypatch.setenv("DATA_DIR", str(tmp_path / "data")) + monkeypatch.setenv("AI_BACKEND", "claude") + monkeypatch.setenv("SESSION_SECRET", "test-secret") + monkeypatch.chdir(ROOT) + import db, auth, claude_bridge, main + importlib.reload(db) + importlib.reload(auth) + importlib.reload(claude_bridge) + importlib.reload(main) + db.init_db() + # Owner's dialog: a message row (makes them the tab owner) + a work file + db.save_message(OWNER, TAB, "user", "составь смету") + wd = main.get_work_dir(OWNER, TAB) + (wd / "смета.xlsx").write_bytes(b"x" * 42) + + from fastapi.testclient import TestClient + client = TestClient(main.app) + return auth, client + + +def _headers(auth, username, role): + return { + "Authorization": "Bearer " + auth._make_token(username, role), + "X-Tab-Id": TAB, + } + + +def test_admin_downloads_file_from_foreign_dialog(env): + auth, client = env + r = client.get("/api/files/смета.xlsx", headers=_headers(auth, "boss@x", "admin")) + assert r.status_code == 200 + assert r.content == b"x" * 42 + + +def test_admin_lists_files_of_foreign_dialog(env): + auth, client = env + r = client.get("/api/files", headers=_headers(auth, "boss@x", "admin")) + assert r.status_code == 200 + assert [f["name"] for f in r.json()] == ["смета.xlsx"] + + +def test_regular_user_cannot_download_foreign_file(env): + auth, client = env + r = client.get("/api/files/смета.xlsx", headers=_headers(auth, "mallory@x", "user")) + assert r.status_code == 404 + + +def test_regular_user_foreign_list_is_empty(env): + auth, client = env + r = client.get("/api/files", headers=_headers(auth, "mallory@x", "user")) + assert r.status_code == 200 + assert r.json() == [] + + +def test_owner_still_downloads_own_file(env): + auth, client = env + r = client.get("/api/files/смета.xlsx", headers=_headers(auth, OWNER, "user")) + assert r.status_code == 200 + assert r.content == b"x" * 42