"""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