fix(security): блок ② — убран депрекированный пакетный путь (exec на хосте)

По решению пользователя вместо песочницы — retire всего депрекированного пакетного
пути (страницы давно заменены чатом). Устраняет P0: batch v2/v3 исполняли
СГЕНЕРИРОВАННЫЙ ИИ по загруженной смете скрипт через exec() прямо в процессе
сервера (prompt-injection в смете контрагента → доступ к .env/БД/файлам всех).

- Удалены роуты: /api/batch-v2/*, /api/batch-v3/*, /api/ssr/*, /api/check/yaml,
  /api/gen/calculate, /api/gen/download + смонтированные /api/gen|ref|wizard.
- Страницы /batch|batch2|batch3|ssr|wizard|generate|reference|check → 302 на /.
- Удалены мёртвые модули batch.py (exec:393 + code-injection через имя листа) и
  batch_v3.py (три exec-точки), их HTML-страницы (заодно ушёл их XSS-surface).
- get_work_dir/ownership-хелперы для batch больше не нужны, но оставлены (dead,
  безвредны) — точечная зачистка отдельно.

Живой чат путь не затронут (batch_v3/extract_zip импортились только депрекированными
эндпоинтами). Тесты: pages→302, api→404. 297 passed.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
This commit is contained in:
anor
2026-07-18 20:28:20 +10:00
co-authored by Claude Opus 4.8
parent 728215557d
commit 27c7634ff0
12 changed files with 23 additions and 3634 deletions
+13 -49
View File
@@ -61,57 +61,21 @@ def test_legit_tab_still_works(env):
assert r.json() == []
# ---- анонимные эндпоинты закрыты ----
# ---- депрекированный пакетный путь убран целиком (exec на хосте + анонимные роуты) ----
def test_gen_download_requires_auth(env):
def test_deprecated_pages_redirect(env):
_auth, _main, client, _tmp = env
r = client.get("/api/gen/download/anything") # без Authorization
assert r.status_code == 401
for url in ("/batch2", "/batch3", "/ssr", "/generate", "/wizard", "/reference", "/check"):
r = client.get(url, follow_redirects=False)
assert r.status_code == 302, f"{url} → {r.status_code}"
assert r.headers.get("location", "").endswith("/"), f"{url} → {r.headers.get('location')}"
def test_check_yaml_requires_auth(env):
def test_deprecated_api_endpoints_gone(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
# exec-путь (batch v2/v3) + SSR + анонимные gen/check/ref/wizard удалены → маршрута нет
for m, url in [("POST", "/api/batch-v3/upload"), ("POST", "/api/batch-v2/upload"),
("POST", "/api/ssr/upload"), ("POST", "/api/check/yaml"),
("GET", "/api/gen/download/x"), ("POST", "/api/gen/parse"),
("POST", "/api/ref/search"), ("POST", "/api/wizard/upload")]:
assert client.request(m, url).status_code == 404, f"{m} {url} всё ещё жив"