fix: правки по Fable-ревью (P0 GLM-маскировка + корректность + покрытие)
Финальный Fable-ревью (2 адверсариальных агента) → фиксы: - P0: GLM-путь слал сырую ошибку юзеру и в историю — добавлена сигнатура «ошибка glm api» в error_mask → центральная маскировка ловит оба движка. Тест unit + интеграционный (кейс D). - .doc: catdoc -d utf-8 + guard на сплошные '?' (защита sandbox-Latin-1 от кириллицы-мусора). - _read_work_dir_files: рекурсия (файлы распакованных архивов в подпапках были невидимы) + catch-all для .rar/.7z/.ges (молчаливый пропуск → явное «не читается»). - .arp-ветка: проверка error перед positions (был KeyError). - .xls: общий xls_cell_str (числа 5→'5', даты→dd.mm.yyyy вместо серийника); MCP-tool — ошибка на несуществующий лист вместо молчаливого фолбэка на лист 0. - zip-листинг: единый _decode_zip_name (листинг и распаковка не расходятся на macOS-zip). - extract_archive: лимит 5ГБ/50k файлов (zip-бомба). - upload-ошибка: список форматов из ALLOWED_EXTENSIONS (был устаревший хардкод). - defusedxml в requirements+Dockerfile+хост (XXE-hardening; expat и так защищал). - Тесты: фиктивная .docx-проверка → явная проверка ТАБЛИЦ; .arp-числа заякорены; пер-сигнатурное покрытие error_mask; аудит agent_error проверяется. APP_VERSION→2026-07-15g. Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
This commit is contained in:
+34
-23
@@ -214,6 +214,7 @@ def _read_xls_via_xlrd(path: Path, max_chars: int) -> str | None:
|
||||
book = xlrd.open_workbook(str(path))
|
||||
except Exception:
|
||||
return None
|
||||
from gge_tools import xls_cell_str
|
||||
out: list[str] = []
|
||||
used = 0
|
||||
for sh in book.sheets():
|
||||
@@ -222,8 +223,8 @@ def _read_xls_via_xlrd(path: Path, max_chars: int) -> str | None:
|
||||
out.append(f"\n### Файл: {path.name}, Лист: {sh.name} "
|
||||
f"(строк: {sh.nrows}, колонок: {sh.ncols})")
|
||||
for r in range(sh.nrows):
|
||||
vals = [str(sh.cell_value(r, c))[:300] for c in range(sh.ncols)
|
||||
if str(sh.cell_value(r, c)).strip()]
|
||||
vals = [v[:300] for c in range(sh.ncols)
|
||||
if (v := xls_cell_str(sh.cell(r, c), book.datemode)).strip()]
|
||||
if not vals:
|
||||
continue
|
||||
line = f"стр{r + 1}: " + " | ".join(vals)
|
||||
@@ -235,18 +236,23 @@ def _read_xls_via_xlrd(path: Path, max_chars: int) -> str | None:
|
||||
|
||||
|
||||
def _read_doc_via_catdoc(path: Path) -> str | None:
|
||||
"""Старый .doc (OLE2) — python-docx не умеет; catdoc → текст. None если нет catdoc."""
|
||||
"""Старый .doc (OLE2) — python-docx не умеет; catdoc → текст. None если нет catdoc.
|
||||
`-d utf-8`: по умолчанию /etc/catdocrc = Latin-1, который НЕ кодирует кириллицу →
|
||||
русский .doc превращается в '?'. Сплошные '?' = битая кодировка → честный None,
|
||||
а не выдавать мусор за содержимое (выдуманное хуже пропуска)."""
|
||||
import shutil
|
||||
import subprocess
|
||||
if not shutil.which("catdoc"):
|
||||
return None
|
||||
try:
|
||||
r = subprocess.run(["catdoc", "-w", str(path)],
|
||||
r = subprocess.run(["catdoc", "-w", "-d", "utf-8", str(path)],
|
||||
capture_output=True, timeout=60)
|
||||
text = r.stdout.decode("utf-8", "replace").strip()
|
||||
return text or None
|
||||
except Exception:
|
||||
return None
|
||||
if not text or text.count("?") > len(text) * 0.3:
|
||||
return None
|
||||
return text
|
||||
|
||||
|
||||
def _read_docx(path: Path, max_chars: int) -> str:
|
||||
@@ -290,9 +296,11 @@ def _read_work_dir_files(work_dir: Path, max_chars: int = 150000) -> str:
|
||||
"""Read files from work directory and return text summary for LLM context."""
|
||||
parts = []
|
||||
total = 0
|
||||
for f in sorted(work_dir.iterdir()):
|
||||
if f.name.startswith(".") or not f.is_file():
|
||||
continue
|
||||
# Рекурсивно: файлы распакованных архивов лежат в подпапках (<stem>_extracted/…),
|
||||
# иначе они невидимы модели. Кап на число файлов — защита от огромных распаковок.
|
||||
all_files = [f for f in sorted(work_dir.rglob("*"))
|
||||
if f.is_file() and not f.name.startswith(".")]
|
||||
for f in all_files[:250]:
|
||||
ext = f.suffix.lower()
|
||||
try:
|
||||
if ext in (".xlsx", ".xlsm"):
|
||||
@@ -376,12 +384,15 @@ def _read_work_dir_files(work_dir: Path, max_chars: int = 150000) -> str:
|
||||
elif ext in (".arp", ".arps"):
|
||||
from gge_tools import parse_arp_file
|
||||
a = parse_arp_file(f)
|
||||
poss = "\n".join(f" {p['code']} | {p['name'][:80]} | {p['unit']} | {p['total']} руб"
|
||||
for p in a["positions"][:40])
|
||||
chunk = (f"\n### Смета .arp: {f.name}\nШифр: {a['code']} | {a['name']}\n"
|
||||
f"Итог: {a['total']} руб | позиций: {a['positions_count']}\n{poss}")
|
||||
parts.append(chunk)
|
||||
total += len(chunk)
|
||||
if "error" in a:
|
||||
parts.append(f"\n### Файл: {f.name} (.arp, ошибка: {a['error']})")
|
||||
else:
|
||||
poss = "\n".join(f" {p['code']} | {p['name'][:80]} | {p['unit']} | {p['total']} руб"
|
||||
for p in a["positions"][:40])
|
||||
chunk = (f"\n### Смета .arp: {f.name}\nШифр: {a['code']} | {a['name']}\n"
|
||||
f"Итог: {a['total']} руб | позиций: {a['positions_count']}\n{poss}")
|
||||
parts.append(chunk)
|
||||
total += len(chunk)
|
||||
elif ext in _UNSUPPORTED_SMETA:
|
||||
parts.append(f"\n### Файл: {f.name} (формат {ext} проприетарный, "
|
||||
f"автоматически не читается — экспортируйте смету в АРПС (.arp) или Excel)")
|
||||
@@ -428,16 +439,11 @@ def _read_work_dir_files(work_dir: Path, max_chars: int = 150000) -> str:
|
||||
lines = []
|
||||
MAX_LISTED = 100
|
||||
total_size = 0
|
||||
from gge_tools import _decode_zip_name
|
||||
for info in infos:
|
||||
# Декодирование имён: zipfile отдаёт всё как cp437, если флаг
|
||||
# UTF-8 (0x800) не выставлен. Для архивов из Windows имена
|
||||
# обычно в cp866 — пытаемся восстановить.
|
||||
name = info.filename
|
||||
if not (info.flag_bits & 0x800):
|
||||
try:
|
||||
name = name.encode("cp437").decode("cp866")
|
||||
except (UnicodeEncodeError, UnicodeDecodeError):
|
||||
pass
|
||||
# Единый декодер имён (utf-8→cp866, без replacement) — как при
|
||||
# распаковке, иначе листинг и распаковка расходятся на macOS-zip.
|
||||
name = _decode_zip_name(info)
|
||||
total_size += info.file_size
|
||||
if len(lines) < MAX_LISTED:
|
||||
kind = "/" if info.is_dir() else ""
|
||||
@@ -452,6 +458,11 @@ def _read_work_dir_files(work_dir: Path, max_chars: int = 150000) -> str:
|
||||
chunk = f"{header}\n{body}"
|
||||
parts.append(chunk)
|
||||
total += len(chunk)
|
||||
else:
|
||||
# Нераспознанный формат (.rar/.7z/.ges/.smr/.smt и пр.) — назвать
|
||||
# явно, а не пропустить молча (иначе модель сошлётся на историю).
|
||||
parts.append(f"\n### Файл: {f.name} (формат {ext or '?'} автоматически "
|
||||
f"не читается — открой инструментом или попроси экспорт в Excel/АРПС)")
|
||||
except Exception as e:
|
||||
parts.append(f"\n### Файл: {f.name} (ошибка чтения: {e})")
|
||||
|
||||
|
||||
@@ -22,6 +22,8 @@ _ERROR_SIGNATURES = (
|
||||
"insufficient_quota",
|
||||
'"type":"error"',
|
||||
'"type": "error"',
|
||||
"ошибка glm api", # GLM-путь (claude_bridge_glm) оборачивает ЛЮБОЕ исключение
|
||||
# в «Ошибка GLM API: …» — иначе сырой 401/URL бэкенда утечёт юзеру
|
||||
)
|
||||
|
||||
PROVIDER_ERROR_MESSAGE = (
|
||||
|
||||
@@ -41,14 +41,22 @@ def extract_archive(zip_path: Path, target_dir: Path) -> dict:
|
||||
Возвращает: {target: <abs path>, total_files: N, gge_files: M, skipped: K}
|
||||
"""
|
||||
import os
|
||||
# Лимиты против zip-бомбы: пишем в host-диск (/data), --memory контейнера не спасает.
|
||||
MAX_BYTES = 5 * 1024 ** 3 # 5 ГБ распакованного
|
||||
MAX_FILES = 50000
|
||||
target_dir.mkdir(parents=True, exist_ok=True)
|
||||
target_resolved = target_dir.resolve()
|
||||
total = gge = skipped = 0
|
||||
written_bytes = 0
|
||||
aborted = False
|
||||
with zipfile.ZipFile(zip_path) as z:
|
||||
for info in z.infolist():
|
||||
if info.is_dir():
|
||||
continue
|
||||
total += 1
|
||||
if total > MAX_FILES or written_bytes > MAX_BYTES:
|
||||
aborted = True
|
||||
break
|
||||
name = _decode_zip_name(info).replace('\\', '/')
|
||||
# path traversal guard
|
||||
out = (target_dir / name).resolve()
|
||||
@@ -61,16 +69,23 @@ def extract_archive(zip_path: Path, target_dir: Path) -> dict:
|
||||
try:
|
||||
with z.open(info) as src, open(out, 'wb') as dst:
|
||||
while chunk := src.read(64 * 1024):
|
||||
written_bytes += len(chunk)
|
||||
if written_bytes > MAX_BYTES:
|
||||
aborted = True
|
||||
break
|
||||
dst.write(chunk)
|
||||
if name.lower().endswith('.gge'):
|
||||
gge += 1
|
||||
except Exception:
|
||||
skipped += 1
|
||||
if aborted:
|
||||
break
|
||||
return {
|
||||
'target': str(target_dir),
|
||||
'total_files': total,
|
||||
'gge_files': gge,
|
||||
'skipped': skipped,
|
||||
'aborted': aborted,
|
||||
}
|
||||
|
||||
|
||||
@@ -168,6 +183,24 @@ def parse_gge_file(path: Path) -> dict:
|
||||
}
|
||||
|
||||
|
||||
def xls_cell_str(cell, datemode) -> str:
|
||||
"""Значение ячейки .xls (xlrd) → человекочитаемая строка. xlrd отдаёт числа и
|
||||
даты как float: целое 5→'5.0', дата→серийник (43831.0). Форматируем по ctype."""
|
||||
import xlrd
|
||||
v = cell.value
|
||||
if cell.ctype == xlrd.XL_CELL_DATE:
|
||||
try:
|
||||
dt = xlrd.xldate.xldate_as_datetime(v, datemode)
|
||||
if dt.hour == dt.minute == dt.second == 0:
|
||||
return dt.strftime("%d.%m.%Y")
|
||||
return dt.strftime("%d.%m.%Y %H:%M")
|
||||
except Exception:
|
||||
return str(v)
|
||||
if cell.ctype == xlrd.XL_CELL_NUMBER and float(v).is_integer():
|
||||
return str(int(v))
|
||||
return str(v)
|
||||
|
||||
|
||||
def _ru_float(s: str) -> float:
|
||||
"""ГРАНД пишет десятичные с запятой (Data.xml) или точкой (Properties.txt)."""
|
||||
if not s:
|
||||
|
||||
@@ -138,7 +138,7 @@ MAX_MESSAGE_LEN = 10_000
|
||||
|
||||
# ⚠️ Версия UI — единый источник. БАМПАТЬ ПРИ КАЖДОМ ДЕПЛОЕ (формат: YYYY-MM-DD + буква).
|
||||
# Фронт берёт её через GET /api/version (chat.html + admin.html, элемент .app-version).
|
||||
APP_VERSION = "2026-07-15f"
|
||||
APP_VERSION = "2026-07-15g"
|
||||
|
||||
# Audit: path → action name mapping
|
||||
_AUDIT_MAP = [
|
||||
@@ -583,10 +583,12 @@ async def upload(request: Request, file: UploadFile):
|
||||
raise HTTPException(400, "Invalid filename")
|
||||
|
||||
if not is_allowed_file(safe_name):
|
||||
raise HTTPException(
|
||||
400,
|
||||
f"File type not allowed. Allowed: xlsx, xls, docx, pdf, csv, txt, xml, json, yaml, gge, esw, zip",
|
||||
)
|
||||
try:
|
||||
from claude_bridge_glm import ALLOWED_EXTENSIONS as _ALLOWED
|
||||
except Exception:
|
||||
from claude_bridge import ALLOWED_EXTENSIONS as _ALLOWED
|
||||
allowed = ", ".join(sorted(e.lstrip(".") for e in _ALLOWED))
|
||||
raise HTTPException(400, f"Формат не поддерживается. Разрешены: {allowed}")
|
||||
|
||||
chunks = []
|
||||
total = 0
|
||||
|
||||
@@ -17,4 +17,5 @@ faiss-cpu==1.13.2
|
||||
xlrd==2.0.2 # легаси .xls (BIFF) — openpyxl не умеет
|
||||
pytesseract==0.3.13 # OCR PDF-сканов (нужен apt: tesseract-ocr tesseract-ocr-rus)
|
||||
Pillow>=10 # рендер страниц PDF для OCR
|
||||
defusedxml>=0.7 # XXE/billion-laughs-safe парсинг user-uploaded XML (.gsfx/.gge)
|
||||
# apt-зависимости (не pip): catdoc (чтение старых .doc), tesseract-ocr + tesseract-ocr-rus (OCR)
|
||||
|
||||
+1
-1
@@ -10,7 +10,7 @@ RUN apt-get update && apt-get install -y --no-install-recommends \
|
||||
RUN pip3 install --break-system-packages --no-cache-dir \
|
||||
openpyxl python-docx pymupdf pandas \
|
||||
faiss-cpu pyyaml pydantic typer openai rank-bm25 \
|
||||
xlrd pytesseract pillow
|
||||
xlrd pytesseract pillow defusedxml
|
||||
|
||||
# Claude Code CLI
|
||||
RUN npm install -g @anthropic-ai/claude-code
|
||||
|
||||
+6
-3
@@ -70,14 +70,17 @@ def tool_read_xlsx_sheet(*, filename: str, sheet: str | None = None, max_rows: i
|
||||
book = xlrd.open_workbook(str(fpath))
|
||||
except Exception as e:
|
||||
return {"error": f"Не удалось открыть .xls: {e}"}
|
||||
from gge_tools import xls_cell_str
|
||||
names = book.sheet_names()
|
||||
sh = book.sheet_by_name(sheet) if sheet in names else book.sheet_by_index(0)
|
||||
if sheet is not None and sheet not in names:
|
||||
return {"error": f"Лист «{sheet}» не найден", "available_sheets": names}
|
||||
sh = book.sheet_by_name(sheet) if sheet else book.sheet_by_index(0)
|
||||
rows_x: list[dict] = []
|
||||
real_x = 0
|
||||
for r in range(sh.nrows):
|
||||
cells = {get_column_letter(c + 1): str(sh.cell_value(r, c))[:300]
|
||||
cells = {get_column_letter(c + 1): v[:300]
|
||||
for c in range(sh.ncols)
|
||||
if str(sh.cell_value(r, c)).strip()}
|
||||
if (v := xls_cell_str(sh.cell(r, c), book.datemode)).strip()}
|
||||
if not cells:
|
||||
continue
|
||||
real_x += 1
|
||||
|
||||
@@ -18,10 +18,12 @@ with zipfile.ZipFile(SRC) as z:
|
||||
r = parse_arp_file(p)
|
||||
assert "error" not in r, r
|
||||
print(f" code={r['code']} | total={r['total']} | positions={r['positions_count']}")
|
||||
assert r["code"], "нет шифра сметы"
|
||||
assert r["code"] == "00-02-7-00-01Р", r["code"] # реальный якорь (не только непустота)
|
||||
assert abs(r["total"] - 6105760.71) < 0.01, r["total"] # ловит съезд индекса поля итога
|
||||
assert r["positions_count"] > 0, r
|
||||
p0 = r["positions"][0]
|
||||
assert p0["code"] and p0["name"] and p0["unit"], p0
|
||||
assert p0["total"] > 0, p0 # ловит съезд индекса стоимости позиции
|
||||
print(f" пример: {p0}")
|
||||
shutil.rmtree(tmp, ignore_errors=True)
|
||||
print("ALL PASS")
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
"""Юнит-тест детекции ошибок провайдера. Mutation-safe: убери сигнатуру
|
||||
'authentication_error' в error_mask → тест реального 401 упадёт."""
|
||||
"""Юнит-тест детекции ошибок провайдера. Покрытие пер-сигнатурное: каждая сигнатура
|
||||
имеет тест со строкой, где она ЕДИНСТВЕННАЯ совпадающая — удали её → тест упадёт
|
||||
(REAL_401 матчит несколько сигнатур сразу, поэтому одиночная мутация его не роняет)."""
|
||||
import os
|
||||
import sys
|
||||
|
||||
@@ -28,6 +29,30 @@ def test_overloaded_masked():
|
||||
assert looks_like_provider_error('{"type":"error","error":{"type":"overloaded_error"}}') is True
|
||||
|
||||
|
||||
def test_glm_error_masked():
|
||||
# GLM-путь оборачивает любое исключение в «Ошибка GLM API: …» — оно НЕ содержит
|
||||
# claude-сигнатур, ловится только своей. Регресс на реальный дефект (сырой 401 юзеру).
|
||||
assert looks_like_provider_error(
|
||||
"Ошибка GLM API: Client error '401 Unauthorized' for url 'https://open.bigmodel.cn/api/paas/v4/'"
|
||||
) is True
|
||||
|
||||
|
||||
def test_per_signature_isolated():
|
||||
# Каждая сигнатура — строка, где совпадает ТОЛЬКО она (пер-сигнатурное покрытие).
|
||||
cases = {
|
||||
"authentication_error": '{"error":{"type":"authentication_error"}}',
|
||||
"failed to authenticate": "Failed to authenticate with provider",
|
||||
"invalid authentication": "Invalid authentication credentials",
|
||||
"api error:": "API Error: 500 something",
|
||||
"rate_limit_error": '{"kind":"rate_limit_error"}',
|
||||
"overloaded_error": '{"kind":"overloaded_error"}',
|
||||
"insufficient_quota": "insufficient_quota for account",
|
||||
"ошибка glm api": "Ошибка GLM API: timeout",
|
||||
}
|
||||
for sig, s in cases.items():
|
||||
assert looks_like_provider_error(s) is True, f"не поймана сигнатура {sig}"
|
||||
|
||||
|
||||
def test_normal_smeta_answer_not_masked():
|
||||
# Реальный по духу ответ — не должен ложно маскироваться.
|
||||
answer = (
|
||||
|
||||
@@ -54,7 +54,19 @@ if ".doc" in got:
|
||||
seg = out.split("sample.doc")[1][:400] if "sample.doc" in out else ""
|
||||
chk(".doc читается (catdoc)", "не удалось" not in seg and len(seg.strip()) > 20, "пустой/ошибка")
|
||||
if ".docx" in got:
|
||||
chk(".docx читается", "sample.docx" in out, "нет вывода")
|
||||
seg = out.split("sample.docx")[1][:600] if "sample.docx" in out else ""
|
||||
chk(".docx читается", "не удалось" not in seg and len(seg.strip()) > 30, "пусто/ошибка")
|
||||
|
||||
# Отдельно — ТАБЛИЦЫ docx (главная фича п.5) на СИНТЕТИЧЕСКОМ docx с таблицей.
|
||||
from claude_bridge_glm import _read_docx
|
||||
import docx as _docxlib
|
||||
_d = _docxlib.Document()
|
||||
_t = _d.add_table(rows=2, cols=2)
|
||||
_t.rows[0].cells[0].text = "Работа"; _t.rows[0].cells[1].text = "Объём"
|
||||
_t.rows[1].cells[0].text = "Копание ям"; _t.rows[1].cells[1].text = "411 м3"
|
||||
_tp = tmp / "tbl.docx"; _d.save(str(_tp))
|
||||
_txt = _read_docx(_tp, 10000)
|
||||
chk(".docx таблицы читаются", "Копание ям" in _txt and "411 м3" in _txt and " | " in _txt, "таблица упущена")
|
||||
if ".gsfx" in got:
|
||||
chk(".gsfx парсится (Смета)", "Смета .gsfx" in out and "Шифр:" in out, "не распознан")
|
||||
if ".esw" in got:
|
||||
|
||||
@@ -68,8 +68,23 @@ outC = drive([_sse("text", {"text": normal}), _sse("done", {"result": ""})], tab
|
||||
fails += check("C: нормальный ответ в стриме", normal in outC)
|
||||
fails += check("C: нормальный ответ в БД", saved_assistant(tabC) == normal)
|
||||
|
||||
# Case D — ошибка GLM-пути («Ошибка GLM API: …») тоже маскируется (регресс P0:
|
||||
# раньше сырой 401 с URL бэкенда утекал юзеру и в историю на GLM-пути).
|
||||
tabD = "mask-D"
|
||||
clear_history(USER, tabD)
|
||||
GLM_ERR = "Ошибка GLM API: Client error '401 Unauthorized' for url 'https://open.bigmodel.cn/'"
|
||||
outD = drive([_sse("text", {"text": GLM_ERR})], tabD)
|
||||
fails += check("D: GLM-ошибка → friendly в стриме, без сырого", FRIENDLY in outD and "401" not in outD)
|
||||
fails += check("D: GLM-ошибка → friendly в БД", saved_assistant(tabD) == FRIENDLY)
|
||||
|
||||
# Аудит: замаскированный инцидент виден оператору (log_action agent_error) —
|
||||
# единственный канал, по которому узнают о проблеме. Удали log_action → упадёт.
|
||||
from db import get_audit_log
|
||||
fails += check("инцидент залогирован (agent_error)",
|
||||
len(get_audit_log(action="agent_error", limit=10)) > 0)
|
||||
|
||||
# cleanup
|
||||
for t in ("mask-A", "mask-B", "mask-C"):
|
||||
for t in ("mask-A", "mask-B", "mask-C", "mask-D"):
|
||||
clear_history(USER, t)
|
||||
|
||||
print("ALL PASS" if not fails else f"{fails} FAILED")
|
||||
|
||||
Reference in New Issue
Block a user