- Смонтированные роутеры /api/gen|ref|wizard/* были полностью анонимны (нет глобального auth-middleware) → аноним жёг LLM/RAG-бюджет, грузил файлы, ловил сырые ошибки. Гейт на include_router через Depends(_auth_dep) — без правки чужого пакета smeta_railway. Живой чат их не использует (только депрекированные страницы). - safe_work_dir: username вида 'zzz/../victim@x.com' резолвился в чужую папку (parent==root проходил) → добавлена проверка user_dir.name==username (один компонент). - null-byte в tab_id из JSON-body давал ValueError→500 → теперь UnsafePath→чистый 400. - /api/gen/calculate был аноним (безопасен лишь из-за раннего return) → добавлен _get_user. Тесты: +collision, +null-byte, +anon-гейт всех смонтированных маршрутов. 300 passed. Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
118 lines
4.8 KiB
Python
118 lines
4.8 KiB
Python
"""Block ① безопасности (Fable audit 2026-07-18): path-traversal через x-tab-id,
|
||
анонимные compute/download-эндпоинты, владелец job'а.
|
||
|
||
Mutation-честность:
|
||
- убери guard в get_work_dir → traversal-тесты пройдут МИМО (файл-часовой удалён / прочитан).
|
||
- верни `_get_user` без ownership → foreign-job тест перестанет давать 404.
|
||
"""
|
||
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)
|
||
|
||
|
||
@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.chdir(ROOT)
|
||
import auth, claude_bridge, db, main, path_safety
|
||
for m in (path_safety, db, auth, claude_bridge, main):
|
||
importlib.reload(m)
|
||
db.init_db()
|
||
from fastapi.testclient import TestClient
|
||
return auth, main, TestClient(main.app), tmp_path
|
||
|
||
|
||
def _h(auth, user="mallory@x", role="user", tab="tab-1"):
|
||
return {"Authorization": "Bearer " + auth._make_token(user, role), "X-Tab-Id": tab}
|
||
|
||
|
||
# ---- path traversal через заголовок вкладки ----
|
||
|
||
def test_traversal_read_blocked(env):
|
||
auth, main, client, tmp = env
|
||
h = _h(auth, tab="../../../../etc")
|
||
r = client.get("/api/files/passwd", headers=h)
|
||
assert r.status_code == 400 # UnsafePath → чистый 400, не 200 с /etc/passwd
|
||
|
||
|
||
def test_traversal_delete_does_not_wipe_outside(env):
|
||
auth, main, client, tmp = env
|
||
sentinel = tmp / "sentinel.txt" # лежит ВЫШЕ DATA_DIR (tmp/data)
|
||
sentinel.write_text("keep me")
|
||
r = client.post("/api/clear-files", headers=_h(auth, tab="../.."))
|
||
assert r.status_code == 400
|
||
assert sentinel.exists() # без guard clear-files снёс бы этот файл
|
||
|
||
|
||
def test_legit_tab_still_works(env):
|
||
auth, main, client, tmp = env
|
||
# обычный tab_id (не traversal) — 200 и пустой список, не 400
|
||
r = client.get("/api/files", headers=_h(auth, tab="normal-uuid-1234"))
|
||
assert r.status_code == 200
|
||
assert r.json() == []
|
||
|
||
|
||
# ---- анонимные эндпоинты закрыты ----
|
||
|
||
def test_gen_download_requires_auth(env):
|
||
_auth, _main, client, _tmp = env
|
||
r = client.get("/api/gen/download/anything") # без Authorization
|
||
assert r.status_code == 401
|
||
|
||
|
||
def test_check_yaml_requires_auth(env):
|
||
_auth, _main, client, _tmp = env
|
||
r = client.post("/api/check/yaml", json={"yaml": "x: 1"})
|
||
assert r.status_code == 401
|
||
|
||
|
||
def test_mounted_routers_and_gen_reject_anon(env):
|
||
"""Fable verify #1/#4: /api/gen|ref|wizard/* были полностью анонимны (жгли LLM/RAG,
|
||
грузили файлы). Ни один маршрут под этими префиксами не должен пускать без токена."""
|
||
import re as _re
|
||
_auth, main, client, _tmp = env
|
||
targets = []
|
||
for r in main.app.routes:
|
||
p = getattr(r, "path", "")
|
||
if p.startswith(("/api/ref/", "/api/wizard/", "/api/gen/")): # с '/' — не ловить /api/refresh
|
||
methods = getattr(r, "methods", None) or {"GET"}
|
||
m = "POST" if "POST" in methods else ("GET" if "GET" in methods else next(iter(methods)))
|
||
targets.append((m, _re.sub(r"\{[^}]+\}", "x", p)))
|
||
assert targets, "нет смонтированных маршрутов — тест бесполезен"
|
||
for m, url in targets:
|
||
resp = client.request(m, url) # без Authorization
|
||
assert resp.status_code == 401, f"{m} {url} → {resp.status_code}, ждали 401"
|
||
|
||
|
||
# ---- владелец job'а ----
|
||
|
||
def test_require_job_owner_helper(env):
|
||
_auth, main, _client, _tmp = env
|
||
from fastapi import HTTPException
|
||
assert main._require_job_owner({"user": "a@x"}, "a@x")["user"] == "a@x"
|
||
with pytest.raises(HTTPException):
|
||
main._require_job_owner({"user": "a@x"}, "b@x") # чужой → 404
|
||
with pytest.raises(HTTPException):
|
||
main._require_job_owner(None, "a@x") # нет job → 404
|
||
|
||
|
||
def test_batch_v3_status_foreign_is_404(env):
|
||
_auth, main, client, _tmp = env
|
||
auth = _auth
|
||
# заводим job вручную от имени owner@x, спрашиваем от mallory@x
|
||
import batch_v3
|
||
job = batch_v3.create_job("deadbeef")
|
||
job["user"] = "owner@x"
|
||
job["job_dir"] = "/tmp/nope"
|
||
r = client.get("/api/batch-v3/status/deadbeef", headers=_h(auth, user="mallory@x"))
|
||
assert r.status_code == 404
|