Files
smeta-web/tests/test_admin_foreign_files.py
T
anor fd6479b365 fix(security): роль админа из БД во ВСЕХ путях + refresh-токен ≠ access (Фабл-пентест)
#1 [MEDIUM]: /api/history и _admin_tab_owner (питает /api/files) брали роль из
JWT (get_token_role), а не из БД → разжалованный (не заблокированный) экс-админ
по живому токену читал чужие сметы/переписку. Единый _is_admin из БД во всех
админ-путях (гейт + читающие фолбэки).
#2 [LOW, усиливал #1]: verify_token/get_token_role не проверяли type → refresh
(7д) работал как access, растягивая окно #1 до 7 дней. Теперь refresh на
access-путях отклоняется.
Red-green: demoted-admin→404/пусто, refresh→401; мутация ловит.
2026-07-24 02:42:58 +10:00

126 lines
4.7 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"""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):
# Юзер должен быть в БД: _get_user проверяет существование на каждом запросе (инцидент 07-22).
import db
try:
db.create_user(username, "h", role=role)
except Exception:
pass
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
# --- Пентест-фикс (Фабл 2026-07-24): роль админа из БД, refresh ≠ access ---
def test_demoted_admin_cannot_access_foreign_data(env):
"""Токен несёт role=admin, но в БД роль user (разжалован, не заблокирован) →
доступа к чужим файлам/истории НЕТ (роль берётся из БД, не из токена)."""
auth, client = env
import db
db.create_user("exadmin@x", "h", role="user") # в БД — обычный юзер
stale = auth._make_token("exadmin@x", "admin") # старый токен с role=admin
h = {"Authorization": "Bearer " + stale, "X-Tab-Id": TAB}
assert client.get("/api/files/смета.xlsx", headers=h).status_code == 404
assert client.get("/api/files", headers=h).json() == []
assert client.get("/api/history", headers=h).json() == []
def test_refresh_token_rejected_as_access(env):
"""refresh-токен (7 дней) не принимается на access-путях даже с role=admin."""
auth, client = env
import db
db.create_user("radmin@x", "h", role="admin") # реальный админ в БД
refresh = auth._make_refresh_token("radmin@x", "admin")
h = {"Authorization": "Bearer " + refresh, "X-Tab-Id": TAB}
assert client.get("/api/files", headers=h).status_code == 401
def test_verify_token_type_guard(env):
"""verify_token/get_token_role различают access и refresh."""
auth, _ = env
acc = auth._make_token("u@x", "admin")
ref = auth._make_refresh_token("u@x", "admin")
assert auth.verify_token(acc) == "u@x" and auth.verify_token(ref) is None
assert auth.get_token_role(acc) == "admin" and auth.get_token_role(ref) == "user"