fix(security): правки по финальному Fable-sweep (регрессий нет, добиты латентные)

Fable подтвердил: явных регрессий от сессии нет. Добиты найденные им дефекты,
в т.ч. прошедшие ровно по только что тронутому коду:

- auth refresh (P1): роль и КАНОН email теперь из свежей записи БД, не из клиентского
  токена. Было: демоутнутый admin оставался админом до 7 дней; refresh со смешанным
  регистром email уводил work_dir/историю в другую папку (тихая пропажа файлов).
- /api/chat (P2): валидация tab_id ДО стрима/save_message → чистый 400 вместо
  грязного обрыва генератора с мусорной строкой в БД.
- search_engine (P2): лок на _morph.parse — после выноса поиска в to_thread
  pymorphy2 дёргается конкурентно (не гарантированно потокобезопасен).
- долг: удалены мёртвые _ssr_jobs/_require_job_owner/_auth_dep/_import_ssr_scripts,
  устаревшие записи _AUDIT_MAP, сломанные scripts/test_*batch.py (импортили удалённый batch).

Тесты: +демоут-admin, +канон-email, +chat-bad-tab-400. 306 passed.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
This commit is contained in:
anor
2026-07-18 21:05:02 +10:00
co-authored by Claude Opus 4.8
parent 1e6b4b46a2
commit 427d92fcb0
7 changed files with 59 additions and 238 deletions
+12 -8
View File
@@ -113,14 +113,18 @@ def refresh_access_token(refresh_token: str) -> str | None:
role = payload.get("role", "user") role = payload.get("role", "user")
except Exception: except Exception:
return None return None
# Заблокированный/удалённый юзер НЕ должен обновлять токен (был жив до 7 дней — # Legacy env-admin в БД нет — отдаём как есть.
# кнопка «заблокировать» фактически не работала). Legacy env-admin в БД нет — пропускаем. if LEGACY_USER and sub == LEGACY_USER:
if not (LEGACY_USER and sub == LEGACY_USER): return _make_token(sub, role)
from db import get_user_by_email # Заблокированный/удалённый юзер НЕ обновляет токен (был жив до 7 дней). РОЛЬ и
u = get_user_by_email(sub) # КАНОН email берём из СВЕЖЕЙ записи БД, а не из клиентского токена: демоут
if not u or u.get("blocked"): # admin→user действует сразу; и не дрейфит регистр email (иначе work_dir/история
return None # «уезжают» на case-sensitive ФС при рефреше со смешанным регистром). Fable sweep.
return _make_token(sub, role) from db import get_user_by_email
u = get_user_by_email(sub)
if not u or u.get("blocked"):
return None
return _make_token(u["email"], u["role"])
def authenticate(username: str, password: str, client_ip: str = "") -> str | None: def authenticate(username: str, password: str, client_ip: str = "") -> str | None:
+2 -47
View File
@@ -136,7 +136,7 @@ else:
app = FastAPI(title="smeta-web") app = FastAPI(title="smeta-web")
app.mount("/static", StaticFiles(directory="static"), name="static") app.mount("/static", StaticFiles(directory="static"), name="static")
from path_safety import UnsafePath from path_safety import UnsafePath, safe_work_dir
@app.exception_handler(UnsafePath) @app.exception_handler(UnsafePath)
@@ -163,18 +163,6 @@ _AUDIT_MAP = [
("GET", "/api/files", "list_files"), ("GET", "/api/files", "list_files"),
("POST", "/api/clear-files", "clear_files"), ("POST", "/api/clear-files", "clear_files"),
("POST", "/api/reset", "reset_session"), ("POST", "/api/reset", "reset_session"),
("POST", "/api/batch-v2/", "batch_v2"),
("GET", "/api/batch-v2/", "batch_v2"),
("POST", "/api/batch-v3/", "batch_v3"),
("GET", "/api/batch-v3/", "batch_v3"),
("POST", "/api/ssr/", "ssr"),
("GET", "/api/ssr/", "ssr"),
("POST", "/api/check/", "check"),
("POST", "/api/gen/", "generate"),
("GET", "/api/gen/", "generate"),
("POST", "/api/wizard/", "wizard"),
("GET", "/api/wizard/", "wizard"),
("GET", "/api/ref/", "reference"),
("GET", "/api/history", "history"), ("GET", "/api/history", "history"),
("GET", "/api/sessions", "sessions"), ("GET", "/api/sessions", "sessions"),
("GET", "/api/admin/", "admin"), ("GET", "/api/admin/", "admin"),
@@ -244,9 +232,6 @@ async def audit_middleware(request: Request, call_next):
if action == "download": if action == "download":
parts = path.split("/api/files/") parts = path.split("/api/files/")
detail = parts[1] if len(parts) > 1 else None detail = parts[1] if len(parts) > 1 else None
elif action in ("batch_v2", "batch_v3", "ssr", "generate"):
sub = path.split("/")[-1] if "/" in path else None
detail = sub
ip = request.client.host if request.client else None ip = request.client.host if request.client else None
try: try:
# to_thread: синхронный INSERT на КАЖДОМ запросе иначе морозит event loop # to_thread: синхронный INSERT на КАЖДОМ запросе иначе морозит event loop
@@ -290,20 +275,6 @@ def _get_tab(request: Request, body: dict | None = None) -> str:
return request.headers.get("x-tab-id", "default") return request.headers.get("x-tab-id", "default")
def _auth_dep(request: Request):
"""FastAPI-зависимость: требует валидный токен (для include_router-гейта)."""
_get_user(request)
def _require_job_owner(job: dict | None, user: str) -> dict:
"""Job принадлежит этому юзеру? Иначе 404 (не 403 — не палим существование
чужого job_id). Раньше batch/SSR-эндпоинты проверяли только факт логина, но не
владельца → любой залогиненный по угаданному id тянул чужую смету (Fable audit)."""
if not job or job.get("user") != user:
raise HTTPException(404, "Job not found")
return job
@app.get("/", response_class=HTMLResponse) @app.get("/", response_class=HTMLResponse)
async def index(request: Request): async def index(request: Request):
# Кэш-бастинг главной (как /admin): без актуального ?v= → 302 на URL с v=APP_VERSION # Кэш-бастинг главной (как /admin): без актуального ?v= → 302 на URL с v=APP_VERSION
@@ -619,6 +590,7 @@ async def chat(request: Request):
raise HTTPException(400, "Empty message") raise HTTPException(400, "Empty message")
if len(message) > MAX_MESSAGE_LEN: if len(message) > MAX_MESSAGE_LEN:
raise HTTPException(400, f"Message too long (max {MAX_MESSAGE_LEN} chars)") raise HTTPException(400, f"Message too long (max {MAX_MESSAGE_LEN} chars)")
safe_work_dir(user, tab_id, create=False) # валидируем tab_id ДО стрима/save_message → чистый 400, не обрыв (Fable)
ip = request.client.host if request.client else None ip = request.client.host if request.client else None
log_action(user, "chat", "POST", "/api/chat", f"tab={tab_id} | {message[:120]}", ip, 200) log_action(user, "chat", "POST", "/api/chat", f"tab={tab_id} | {message[:120]}", ip, 200)
@@ -1314,23 +1286,6 @@ async def admin_page(request: Request):
# === Batch V3: Generate + Verify + Auto-Retry === # === Batch V3: Generate + Verify + Auto-Retry ===
# ── SSR Generator ───────────────────────────────────────────────────────────
# In-memory SSR job store (same pattern as batch)
_ssr_jobs: dict[str, dict] = {}
def _import_ssr_scripts():
"""Import smeta-railway scripts (installed via pip install -e)."""
import sys
for scripts_dir in [
str(Path(__file__).resolve().parent / ".." / "smeta-railway" / "scripts"),
str(Path.home() / "smeta-railway" / "scripts"),
]:
if Path(scripts_dir).exists() and scripts_dir not in sys.path:
sys.path.insert(0, scripts_dir)
# ── Wizard Aggregator ────────────────────────────────────────────────────── # ── Wizard Aggregator ──────────────────────────────────────────────────────
def _import_smeta_railway(): def _import_smeta_railway():
-74
View File
@@ -1,74 +0,0 @@
#!/usr/bin/env python3
"""Manual test of batch processing pipeline."""
import json, sys, shutil, traceback, asyncio
from pathlib import Path
sys.path.insert(0, str(Path(__file__).parent.parent))
from batch import read_xlsx_xml, extract_zip, analyze_structure
import openpyxl
# Setup
source_dir = "/tmp/batch_manual/source"
Path(source_dir).mkdir(parents=True, exist_ok=True)
source_files = extract_zip("/tmp/smetas.zip", source_dir)
target_orig = "/tmp/ССР_сводный.xlsx"
target_file = "/tmp/batch_manual/result.xlsx"
shutil.copy2(target_orig, target_file)
print(f"Source files: {len(source_files)}")
print(f"Target: {target_file}")
# Get script from GLM
task = "B5=шифр, H29=строит работы, H30=монтаж, H31=оборуд, H32=прочие (тыс.руб). Внести в сводный файл по шифру (столбец B), значения в столбцы D,E,F,G"
analysis = asyncio.run(analyze_structure(source_files, target_orig, task))
script = analysis.get("python_script", "")
desc = analysis.get("description", "")
print(f"Description: {desc}")
print(f"Script ({len(script)} chars):")
print(script)
print("---")
if not script:
print("NO SCRIPT. Analysis:", json.dumps(analysis, ensure_ascii=False, indent=2)[:1000])
sys.exit(1)
# Fix common GLM mistakes
import re
script_fixed = script.replace("job['errors'] += 1", "job['errors'].append('error')")
script_fixed = script_fixed.replace('job["errors"] += 1', 'job["errors"].append("error")')
script_fixed = re.sub(r"wb_target\['([^']+)'\]", r"(wb_target['\1'] if '\1' in wb_target.sheetnames else wb_target.active)", script_fixed)
script_fixed = re.sub(r'wb_target\["([^"]+)"\]', r'(wb_target["\1"] if "\1" in wb_target.sheetnames else wb_target.active)', script_fixed)
# If wrapped in def main(), call it
if "def main()" in script_fixed and "if __name__" in script_fixed:
script_fixed = re.sub(r"if __name__\s*==\s*['\"]__main__['\"]\s*:\s*\n\s*main\(\)", "", script_fixed)
script_fixed += "\nmain()\n"
# Execute
job = {"processed": 0, "errors": []}
try:
exec(script_fixed, {
"__builtins__": __builtins__,
"source_files": source_files,
"target_file": target_file,
"job": job,
"read_xlsx_xml": read_xlsx_xml,
"Path": Path,
"openpyxl": openpyxl,
"json": json,
})
print(f"\nSUCCESS! Processed: {job['processed']}/{len(source_files)}")
print(f"Errors: {len(job['errors'])}")
except Exception:
traceback.print_exc()
print(f"\nFAILED. Processed: {job['processed']}")
# Verify result
wb = openpyxl.load_workbook(target_file)
ws = wb.active
print(f"\nResult (sheet '{ws.title}'):")
for r in range(3, 14):
vals = []
for c in range(1, 9):
v = ws.cell(r, c).value
vals.append(str(v) if v is not None else "")
print(" Row %d: %s" % (r, " | ".join(vals)))
-108
View File
@@ -1,108 +0,0 @@
#!/usr/bin/env python3
"""Test batch with real smeta files using smart detection."""
import sys, re, shutil
from pathlib import Path
sys.path.insert(0, str(Path(__file__).parent.parent))
from batch import read_xlsx_xml
import openpyxl
SOURCE_DIR = "/tmp/real_batch/source"
TARGET_ORIG = "/tmp/Раздел ПД N 9 Том 9.1 12.0866-СМ.ССР.xlsx"
TARGET_FILE = "/tmp/real_batch/result_real.xlsx"
# Copy target
shutil.copy2(TARGET_ORIG, TARGET_FILE)
# Get source files
source_files = list(Path(SOURCE_DIR).rglob("*.xlsx"))
print("Source files:", len(source_files))
# Open target
wb = openpyxl.load_workbook(TARGET_FILE)
ws = wb["ССРСС-1 ТУЦ"] if "ССРСС-1 ТУЦ" in wb.sheetnames else wb.active
print("Target sheet:", ws.title)
# Build code → row mapping
code_to_row = {}
for r in range(1, ws.max_row + 1):
v = ws.cell(r, 2).value # column B
if v and str(v).startswith("ЛС-"):
code_to_row[str(v).strip()] = r
print("Target codes:", list(code_to_row.keys())[:5], "...")
# Process each source file
processed = 0
errors = []
KEYWORDS = {
"строительные": "ВСЕГО строительные работы",
"монтажные": "ВСЕГО монтажные работы",
"оборудование": "ВСЕГО оборудование",
"прочие": "ВСЕГО прочие затраты",
}
TARGET_COLS = {"строительные": 4, "монтажные": 5, "оборудование": 6, "прочие": 7} # D,E,F,G
for f in source_files:
# Extract code from filename
m = re.match(r"(ЛС-\d{2}-\d{2}-\d+-\d{2}-\d{2})", f.name)
if not m:
errors.append("%s: no code in filename" % f.name)
continue
code = m.group(1)
if code not in code_to_row:
errors.append("%s: code %s not in target" % (f.name, code))
continue
target_row = code_to_row[code]
# Read file
data = read_xlsx_xml(str(f), max_rows=999)
if not data:
errors.append("%s: can't read" % f.name)
continue
rows = list(data.values())[0]
# Find totals by keywords (search from end)
for name, kw in KEYWORDS.items():
for i in range(len(rows) - 1, max(0, len(rows) - 100), -1):
found = False
for j in range(len(rows[i])):
v = str(rows[i][j]) if rows[i][j] else ""
if kw.lower() in v.lower():
# Find numeric value on same row
for vj in range(len(rows[i])):
val = rows[i][vj]
if val and vj != j:
try:
num = float(str(val).replace(",", ".").replace(" ", ""))
# Convert from rubles to thousands
num_tys = round(num / 1000, 2)
ws.cell(target_row, TARGET_COLS[name]).value = num_tys
found = True
break
except (ValueError, TypeError):
pass
break
if found:
break
processed += 1
print(" %s → row %d: OK" % (code, target_row))
wb.save(TARGET_FILE)
print("\nResult: %d/%d processed, %d errors" % (processed, len(source_files), len(errors)))
for e in errors:
print(" ERROR:", e)
# Show result
print("\nTarget values:")
for code, row in sorted(code_to_row.items()):
d = ws.cell(row, 4).value
e = ws.cell(row, 5).value
f_val = ws.cell(row, 6).value
g = ws.cell(row, 7).value
if d or e or f_val or g:
print(" %s: СМР=%s Монт=%s Обор=%s Проч=%s" % (code, d, e, f_val, g))
+7 -1
View File
@@ -7,6 +7,7 @@ full ГЭСН norms (181K), and winter cost zones. Uses pymorphy2 for normalizat
import json import json
import os import os
import re import re
import threading
from pathlib import Path from pathlib import Path
import pymorphy2 import pymorphy2
@@ -14,6 +15,10 @@ import pymorphy2
SMETA_DIR = Path(os.environ.get("SMETA_PROJECT_DIR", os.path.expanduser("~/smeta-railway"))) SMETA_DIR = Path(os.environ.get("SMETA_PROJECT_DIR", os.path.expanduser("~/smeta-railway")))
_morph = pymorphy2.MorphAnalyzer() _morph = pymorphy2.MorphAnalyzer()
# После выноса поиска в to_thread (claude_bridge_glm) _search_* идут в тредпуле
# параллельно; MorphAnalyzer.parse не гарантированно потокобезопасен (общий DAWG/кэш)
# → сериализуем разбор локом (parse дешёвый, глобальную конкуренцию не создаёт). Fable.
_morph_lock = threading.Lock()
def _normalize(word: str) -> str: def _normalize(word: str) -> str:
@@ -21,7 +26,8 @@ def _normalize(word: str) -> str:
word = re.sub(r'[^\w]', '', word) word = re.sub(r'[^\w]', '', word)
if len(word) <= 2 or word.isdigit(): if len(word) <= 2 or word.isdigit():
return word.lower() return word.lower()
return _morph.parse(word.lower())[0].normal_form with _morph_lock:
return _morph.parse(word.lower())[0].normal_form
# === ФССЦ (material prices, 86 regions) === # === ФССЦ (material prices, 86 regions) ===
+29
View File
@@ -80,6 +80,35 @@ def test_deleted_user_cannot_refresh(a):
assert auth.refresh_access_token(rt) is None # нет в БД → None assert auth.refresh_access_token(rt) is None # нет в БД → None
def test_refresh_reads_role_from_db_not_token(a):
"""Fable P1: демоутнутый admin не должен оставаться админом до 7 дней."""
import jose.jwt as _jwt
auth, db = a
db.create_user("adm@x.com", auth.hash_password("Secret123"), role="admin")
with db._conn() as c:
c.execute("UPDATE users SET verified=1 WHERE email='adm@x.com'")
rt = auth._make_refresh_token("adm@x.com", "admin") # старый admin-refresh
with db._conn() as c: # админа демоутнули в user
c.execute("UPDATE users SET role='user' WHERE email='adm@x.com'")
new = auth.refresh_access_token(rt)
assert new
payload = _jwt.decode(new, auth.SECRET, algorithms=[auth.ALGORITHM])
assert payload["role"] == "user" # роль из БД, не из токена
def test_refresh_canonicalizes_email_case(a):
"""Fable P1/P2: refresh со смешанным регистром sub → канон email (иначе work_dir уезжает)."""
import jose.jwt as _jwt
auth, db = a
db.create_user("mixed@x.com", auth.hash_password("Secret123"))
with db._conn() as c:
c.execute("UPDATE users SET verified=1 WHERE email='mixed@x.com'")
rt = auth._make_refresh_token("Mixed@X.com", "user") # неканоничный регистр
new = auth.refresh_access_token(rt)
payload = _jwt.decode(new, auth.SECRET, algorithms=[auth.ALGORITHM])
assert payload["sub"] == "mixed@x.com" # канон, а не Mixed@X.com
# ---- verify-email rate-limit ---- # ---- verify-email rate-limit ----
def test_verify_email_rate_limited(a): def test_verify_email_rate_limited(a):
+9
View File
@@ -71,6 +71,15 @@ def test_deprecated_pages_redirect(env):
assert r.headers.get("location", "").endswith("/"), f"{url} → {r.headers.get('location')}" assert r.headers.get("location", "").endswith("/"), f"{url} → {r.headers.get('location')}"
def test_chat_bad_tab_id_clean_400(env):
"""Fable P2: traversal-tab_id в /api/chat должен давать чистый 400 ДО стрима/save,
а не грязный обрыв внутри генератора с мусорной строкой в БД."""
auth, _main, client, _tmp = env
r = client.post("/api/chat", headers=_h(auth, tab="../../../../etc"),
json={"message": "привет"})
assert r.status_code == 400 # не 200-стрим, не 500
def test_deprecated_api_endpoints_gone(env): def test_deprecated_api_endpoints_gone(env):
_auth, _main, client, _tmp = env _auth, _main, client, _tmp = env
# exec-путь (batch v2/v3) + SSR + анонимные gen/check/ref/wizard удалены → маршрута нет # exec-путь (batch v2/v3) + SSR + анонимные gen/check/ref/wizard удалены → маршрута нет