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
-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))