- scripts/predeploy-tests.sh: ворота перед рестартом — копия дерева, полный круг проверок, зелёный след .predeploy-stamp с hash HEAD - тест возврата в карточке ждёт Toast (мгновенное чтение ловило DOM до рендера) - окно теста бейджа — до следующей function, не фиксированные 1800 символов - строки лимитов/баланса не переносятся: на шрифтах сервера строка росла до 82px - changelog: запись 2026-11-24b (версия уехала на прод без записи — рассинхрон, который ловит test_changelog_valid_and_matches_app_version) Co-Authored-By: Claude Code <noreply@anthropic.com>
290 lines
12 KiB
Python
290 lines
12 KiB
Python
"""Пределы загрузки для обычных людей и режим «только просмотр» (30.09.2026).
|
|
|
|
Повод: обычный человек залил в один диалог 99 МБ (книга на 82 МБ в распаковке), агент на
|
|
зайке перестал успевать с первым ответом, и шесть прогонов подряд кончились маской сбоя.
|
|
Распоряжение Хозяина: обычным людям — предел на файл и на сумму в диалоге; этого человека —
|
|
в «только просмотр» по исчерпанию баланса.
|
|
"""
|
|
|
|
import base64
|
|
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-limits"
|
|
MB = 1024 * 1024
|
|
|
|
|
|
@pytest.fixture()
|
|
def env(tmp_path, monkeypatch):
|
|
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.setenv("USER_MAX_FILE_MB", "1")
|
|
monkeypatch.setenv("USER_MAX_DIALOG_MB", "2")
|
|
monkeypatch.delenv("AGENT_OWNER_EMAILS", raising=False)
|
|
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()
|
|
from fastapi.testclient import TestClient
|
|
return db, auth, main, TestClient(main.app)
|
|
|
|
|
|
def _hdr(auth, db, username, role="user"):
|
|
try:
|
|
db.create_user(username, "h", role=role)
|
|
except Exception:
|
|
pass
|
|
return {"Authorization": "Bearer " + auth._make_token(username, role), "X-Tab-Id": TAB}
|
|
|
|
|
|
def _up(client, h, name, size):
|
|
return client.post("/api/upload", headers=h,
|
|
files={"file": (name, b"x" * size, "application/octet-stream")})
|
|
|
|
|
|
def _tus_create(client, h, name, size, tab=TAB):
|
|
meta = "filename {},tab_id {}".format(base64.b64encode(name.encode()).decode(),
|
|
base64.b64encode(tab.encode()).decode())
|
|
return client.post("/api/tus", headers={**h, "Tus-Resumable": "1.0.0",
|
|
"Upload-Length": str(size),
|
|
"Upload-Metadata": meta})
|
|
|
|
|
|
# --- Шаг 1: пределы загрузки ---
|
|
|
|
def test_user_file_over_limit_refused_with_russian_text(env):
|
|
db, auth, main, client = env
|
|
r = _up(client, _hdr(auth, db, "u@x"), "смета.xlsx", MB + 1)
|
|
assert r.status_code == 413
|
|
assert "1 МБ" in r.json()["detail"]
|
|
|
|
|
|
def test_user_file_under_limit_accepted(env):
|
|
db, auth, main, client = env
|
|
r = _up(client, _hdr(auth, db, "u@x"), "смета.xlsx", MB - 10)
|
|
assert r.status_code == 200
|
|
|
|
|
|
def test_user_dialog_total_over_limit_refused(env):
|
|
db, auth, main, client = env
|
|
h = _hdr(auth, db, "u@x")
|
|
assert _up(client, h, "a.xlsx", MB - 10).status_code == 200
|
|
assert _up(client, h, "b.xlsx", MB - 10).status_code == 200
|
|
r = _up(client, h, "c.xlsx", 100) # сумма 2 МБ - 20 + 100 > 2 МБ
|
|
assert r.status_code == 413
|
|
assert "уже загружено 2 МБ из 2 МБ" in r.json()["detail"] # по-русски, без «2.0»
|
|
|
|
|
|
def test_dialog_total_is_per_dialog(env):
|
|
db, auth, main, client = env
|
|
h = _hdr(auth, db, "u@x")
|
|
assert _up(client, h, "a.xlsx", MB - 10).status_code == 200
|
|
assert _up(client, h, "b.xlsx", MB - 10).status_code == 200
|
|
other = {**h, "X-Tab-Id": "tab-other"}
|
|
assert _up(client, other, "c.xlsx", 100).status_code == 200
|
|
|
|
|
|
def test_dialog_total_not_mixed_by_wildcard_tab(env):
|
|
# «_» в имени диалога — подстановочный знак для LIKE: без точной сверки загрузки
|
|
# диалога «tXb» засчитались бы диалогу «t_b».
|
|
db, auth, main, client = env
|
|
h = _hdr(auth, db, "u@x")
|
|
assert _up(client, {**h, "X-Tab-Id": "tXb"}, "a.xlsx", MB - 10).status_code == 200
|
|
assert _up(client, {**h, "X-Tab-Id": "tXb"}, "b.xlsx", MB - 10).status_code == 200
|
|
assert db.uploaded_bytes("u@x", "t_b") == 0
|
|
assert _up(client, {**h, "X-Tab-Id": "t_b"}, "c.xlsx", 100).status_code == 200
|
|
|
|
|
|
def test_admin_not_limited(env):
|
|
db, auth, main, client = env
|
|
r = _up(client, _hdr(auth, db, "boss@x", "admin"), "big.xlsx", 3 * MB)
|
|
assert r.status_code == 200
|
|
|
|
|
|
def test_owner_not_limited(env, monkeypatch):
|
|
db, auth, main, client = env
|
|
monkeypatch.setenv("AGENT_OWNER_EMAILS", "own@x")
|
|
r = _up(client, _hdr(auth, db, "own@x"), "big.xlsx", 3 * MB)
|
|
assert r.status_code == 200
|
|
|
|
|
|
def test_tus_create_refuses_big_file_before_bytes(env):
|
|
db, auth, main, client = env
|
|
r = _tus_create(client, _hdr(auth, db, "u@x"), "смета.pdf", MB + 1)
|
|
assert r.status_code == 413
|
|
assert "1 МБ" in r.json()["detail"]
|
|
|
|
|
|
def test_tus_create_counts_dialog_total(env):
|
|
db, auth, main, client = env
|
|
h = _hdr(auth, db, "u@x")
|
|
assert _up(client, h, "a.xlsx", MB - 10).status_code == 200
|
|
assert _up(client, h, "b.xlsx", MB - 10).status_code == 200
|
|
assert _tus_create(client, h, "c.pdf", 100).status_code == 413
|
|
assert _tus_create(client, h, "c.pdf", 100, tab="tab-other").status_code == 201
|
|
|
|
|
|
def test_tus_parallel_creates_count_pending(env):
|
|
# Несколько загрузок, созданных разом, не должны пройти проверку порознь.
|
|
db, auth, main, client = env
|
|
h = _hdr(auth, db, "u@x")
|
|
assert _tus_create(client, h, "a.pdf", MB - 10).status_code == 201
|
|
assert _tus_create(client, h, "b.pdf", MB - 10).status_code == 201
|
|
assert _tus_create(client, h, "c.pdf", 100).status_code == 413
|
|
|
|
|
|
def test_tus_abandoned_upload_not_counted(env, tmp_path):
|
|
db, auth, main, client = env
|
|
h = _hdr(auth, db, "u@x")
|
|
assert _tus_create(client, h, "a.pdf", MB - 10).status_code == 201
|
|
assert _tus_create(client, h, "b.pdf", MB - 10).status_code == 201
|
|
old = 1_000_000_000
|
|
for p in (tmp_path / "data" / "_tus").iterdir():
|
|
if not p.name.endswith(".json"):
|
|
os.utime(p, (old, old))
|
|
assert _tus_create(client, h, "c.pdf", 100).status_code == 201
|
|
|
|
|
|
def test_tus_finished_upload_counts_toward_dialog(env):
|
|
# Формат строки журнала у tus должен совпадать с разбором суммы, иначе tus-загрузки
|
|
# не учитывались бы вовсе.
|
|
db, auth, main, client = env
|
|
h = _hdr(auth, db, "u@x")
|
|
r = _tus_create(client, h, "a.pdf", 1000)
|
|
loc = r.headers["Location"]
|
|
r = client.patch(loc, headers={**h, "Tus-Resumable": "1.0.0", "Upload-Offset": "0",
|
|
"Content-Type": "application/offset+octet-stream"},
|
|
content=b"x" * 1000)
|
|
assert r.status_code == 204
|
|
assert db.uploaded_bytes("u@x", TAB) == 1000
|
|
|
|
|
|
def test_filename_cannot_spoof_size(env):
|
|
db, auth, main, client = env
|
|
h = _hdr(auth, db, "u@x")
|
|
assert _up(client, h, "смета (1B) tab=q.xlsx", 5000).status_code == 200
|
|
assert db.uploaded_bytes("u@x", TAB) == 5000
|
|
|
|
|
|
def test_admin_read_only_rejects_string_flag(env):
|
|
db, auth, main, client = env
|
|
_hdr(auth, db, "ro@x")
|
|
ah = _hdr(auth, db, "boss@x", "admin")
|
|
r = client.post("/api/admin/users/read-only", headers=ah,
|
|
json={"email": "ro@x", "read_only": "false"})
|
|
assert r.status_code == 400
|
|
assert not db.get_user_by_email("ro@x")["read_only"]
|
|
|
|
|
|
def test_demo_button_shows_server_reason():
|
|
html = open(os.path.join(ROOT, "static", "chat.html"), encoding="utf-8").read()
|
|
assert "if (r.status === 402) { addMsg('error', await reasonOrText(r)); return; }" in html
|
|
|
|
|
|
def test_tus_admin_keeps_big_limit(env):
|
|
db, auth, main, client = env
|
|
r = _tus_create(client, _hdr(auth, db, "boss@x", "admin"), "big.zip", 50 * MB)
|
|
assert r.status_code == 201
|
|
|
|
|
|
def test_page_shows_server_reason_for_413():
|
|
# Страница прежде писала «максимум 3 ГБ на файл» при любом 413 — неправда для человека
|
|
# с пределом в 5 МБ. Текст отказа сервера обязан доходить до человека.
|
|
html = open(os.path.join(ROOT, "static", "chat.html"), encoding="utf-8").read()
|
|
assert "getBody" in html
|
|
assert "function uploadErrText(s, detail) {\n if (detail) return detail;" in html
|
|
|
|
|
|
# --- Шаг 2: только просмотр ---
|
|
|
|
def test_read_only_blocks_chat_upload_tus_demo(env):
|
|
db, auth, main, client = env
|
|
h = _hdr(auth, db, "ro@x")
|
|
assert db.set_read_only("ro@x", True) is True
|
|
r = client.post("/api/chat", headers=h, json={"message": "привет", "tab_id": TAB})
|
|
assert r.status_code == 402
|
|
assert "просмотр" in r.json()["detail"]
|
|
assert _up(client, h, "a.xlsx", 10).status_code == 402
|
|
assert _tus_create(client, h, "a.xlsx", 10).status_code == 402
|
|
assert client.post("/api/demo-file", headers=h, json={"tab_id": TAB}).status_code == 402
|
|
|
|
|
|
def test_read_only_still_reads_history_and_sessions(env):
|
|
db, auth, main, client = env
|
|
h = _hdr(auth, db, "ro@x")
|
|
db.save_message("ro@x", TAB, "user", "вопрос")
|
|
db.set_read_only("ro@x", True)
|
|
assert client.get("/api/sessions", headers=h).status_code == 200
|
|
r = client.get(f"/api/history?tab_id={TAB}", headers=h)
|
|
assert r.status_code == 200
|
|
assert "вопрос" in r.text
|
|
|
|
|
|
def test_read_only_off_restores_work(env):
|
|
db, auth, main, client = env
|
|
h = _hdr(auth, db, "ro@x")
|
|
db.set_read_only("ro@x", True)
|
|
db.set_read_only("ro@x", False)
|
|
assert _up(client, h, "a.xlsx", 10).status_code == 200
|
|
|
|
|
|
def test_set_read_only_unknown_user_reports_false(env):
|
|
db, auth, main, client = env
|
|
assert db.set_read_only("nobody@x", True) is False
|
|
|
|
|
|
def test_admin_endpoint_toggles_read_only_and_lists_it(env):
|
|
db, auth, main, client = env
|
|
_hdr(auth, db, "ro@x")
|
|
ah = _hdr(auth, db, "boss@x", "admin")
|
|
r = client.post("/api/admin/users/read-only", headers=ah,
|
|
json={"email": "ro@x", "read_only": True})
|
|
assert r.status_code == 200
|
|
users = client.get("/api/admin/users", headers=ah).json()
|
|
rows = users["users"] if isinstance(users, dict) else users
|
|
assert [u for u in rows if u["email"] == "ro@x"][0]["read_only"] == 1
|
|
r = client.post("/api/admin/users/read-only", headers=ah,
|
|
json={"email": "nobody@x", "read_only": True})
|
|
assert r.status_code == 404
|
|
|
|
|
|
def test_admin_endpoint_requires_admin(env):
|
|
db, auth, main, client = env
|
|
h = _hdr(auth, db, "u@x")
|
|
r = client.post("/api/admin/users/read-only", headers=h,
|
|
json={"email": "u@x", "read_only": False})
|
|
assert r.status_code == 403
|
|
|
|
|
|
def test_limits_report_read_only(env):
|
|
# Значок остатка не должен показывать «Осталось: 169 ₽» рядом с отказом «баланс
|
|
# исчерпан» (снимок 30.09.2026).
|
|
db, auth, main, client = env
|
|
h = _hdr(auth, db, "ro@x")
|
|
assert client.get("/api/limits", headers=h).json().get("read_only") in (None, False)
|
|
db.set_read_only("ro@x", True)
|
|
assert client.get("/api/limits", headers=h).json()["read_only"] is True
|
|
|
|
|
|
def test_badge_says_balance_exhausted_in_read_only():
|
|
html = open(os.path.join(ROOT, "static", "chat.html"), encoding="utf-8").read()
|
|
i = html.index("function renderBalance(b) {")
|
|
block = html[i:i + 700]
|
|
assert "if (b.read_only) {" in block and "'Баланс исчерпан'" in block
|
|
j = html.index("function openBalancePopover() {")
|
|
# окно — до следующей function, не фиксированные 1800 символов: константы цены
|
|
# (24.11) отодвинули ветку read_only за прежнюю границу, сама проверка в силе
|
|
assert "if (b.read_only) {" in html[j:html.index("function ", j + 10)]
|