Harden entry safety, unify runtime config, bound document unpacking
Shared-IP safety: entry autoban and entry notifications default off, and a shared IP is treated as review evidence only. ban_user/ban_cluster refuse reason=entry_ip_collision (also with the legacy flag set to 1), so token status and quota are never touched; explicit admin moderation still works. Reproducible startup: new bot/runtime_config.py and scripts/run.py load the repository .env (or --env-file) without shell interpolation, normalize config/DB/upstream aliases, and make the bot, Mini App, gateway, econ cap, account admin, mk_daemon, entry admin and key notifications resolve the same paths. "run.py <target> --check" is an offline preflight that starts nothing and reports placeholders, missing upstream DB and invalid data directories. Resource limits: aggregate Office decompression, a 400 read-entry cap and a per-row XLSX cell budget stop early; truncated or corrupt archives are reported instead of raising. Deploy and docs: only source-backed systemd units remain, and deploy/runtime.env.example documents the environment contract including the 0600 session-secret file rules. Removed the destructive "cp bot/iishko_bot.py bot/grok_bot.py" instruction, the unused generated site/ snapshot and the unsupported iishko-ts staging unit; corrected .env.example, README, ARCHITECTURE, SECURITY, docs/native-gateway.md and iishko-ts/README.md. Tests: entry safety, runtime bootstrap, economy paths, file intake, deploy contract, abilities_guard CLI, and a startup smoke that launches all three components through scripts/run.py with non-loopback network blocked. Every config reader, selfcheck included, accepts a UTF-8 BOM. Verified on this tree: pytest 716 passed + 322 subtests, node --test 73/73, go test and go vet clean, selfcheck --source-only ok, gitleaks worktree and history 0 findings. No production or live-split changes are included.
This commit is contained in:
+211
-51
@@ -4,6 +4,7 @@ from __future__ import annotations
|
||||
import io
|
||||
import re
|
||||
import zipfile
|
||||
import zlib
|
||||
from dataclasses import dataclass, field
|
||||
from html import unescape
|
||||
|
||||
@@ -11,9 +12,19 @@ MAX_FILE_BYTES = 8 * 1024 * 1024
|
||||
TEXT_BUDGET = 24000
|
||||
_MAX_PDF_PAGES = 60
|
||||
_MAX_XLSX_ROWS = 400
|
||||
_MAX_XLSX_CELLS = 2000
|
||||
_MAX_ZIP_ENTRIES = 200
|
||||
_MAX_PPTX_SLIDES = 300
|
||||
_MAX_UNPACKED_BYTES = 64 * 1024 * 1024
|
||||
|
||||
# A ZIP amplifies its input: an 8 MB .pptx inflates into hundreds of MB. The old
|
||||
# code read every entry in full, so a per-entry limit bounded nothing in memory.
|
||||
# Here both the entry and the whole archive are bounded, and reads are chunked.
|
||||
_OFFICE_ENTRY_MAX_BYTES = 8 * 1024 * 1024
|
||||
_OFFICE_TOTAL_MAX_BYTES = 24 * 1024 * 1024
|
||||
_OFFICE_SLIDE_MAX_BYTES = 4 * 1024 * 1024
|
||||
_OFFICE_MAX_SLIDES = 200
|
||||
_OFFICE_MAX_ENTRIES = 400
|
||||
_OFFICE_READ_CHUNK = 128 * 1024
|
||||
_OFFICE_MAX_WARNINGS = 6
|
||||
|
||||
TEXT_EXTS = {
|
||||
".txt", ".md", ".markdown", ".rst", ".log", ".csv", ".tsv", ".json", ".jsonl",
|
||||
@@ -85,68 +96,190 @@ def _looks_binary(text: str) -> bool:
|
||||
return len(_CTRL_RE.findall(sample)) / len(sample) > 0.02
|
||||
|
||||
|
||||
def _finish(text: str, kind: str, warnings: list | None = None) -> ExtractResult:
|
||||
def _finish(text: str, kind: str, warnings: list | None = None, cut: bool = False) -> ExtractResult:
|
||||
"""Build the result. `cut` means the content is knowingly incomplete."""
|
||||
clean = text.replace("\r\n", "\n").replace("\r", "\n")
|
||||
clean = re.sub(r"\n{3,}", "\n\n", clean).strip()
|
||||
truncated = len(clean) > TEXT_BUDGET
|
||||
if truncated:
|
||||
notes = list(warnings or [])
|
||||
truncated = bool(cut) or len(clean) > TEXT_BUDGET
|
||||
if len(clean) > TEXT_BUDGET:
|
||||
clean = clean[:TEXT_BUDGET]
|
||||
warnings = list(warnings or [])
|
||||
warnings.append(f"показаны первые {TEXT_BUDGET} символов")
|
||||
notes.append(f"показаны первые {TEXT_BUDGET} символов")
|
||||
if not clean:
|
||||
return ExtractResult(ok=False, kind=kind, reason="в файле нет извлекаемого текста")
|
||||
return ExtractResult(
|
||||
ok=False, kind=kind, reason="в файле нет извлекаемого текста",
|
||||
truncated=truncated, warnings=notes,
|
||||
)
|
||||
return ExtractResult(
|
||||
ok=True, kind=kind, text=clean, chars=len(clean),
|
||||
truncated=truncated, warnings=list(warnings or []),
|
||||
truncated=truncated, warnings=notes,
|
||||
)
|
||||
|
||||
|
||||
def _read_entry(zf: zipfile.ZipFile, name: str) -> str:
|
||||
info = zf.getinfo(name)
|
||||
if info.file_size > 32 * 1024 * 1024:
|
||||
raise RuntimeError(f"entry {name} распаковывается в {info.file_size // 1048576} МБ — слишком много")
|
||||
return zf.read(name).decode("utf-8", "replace")
|
||||
class _OfficeBudget:
|
||||
"""Read Office archive entries under one shared decompression budget.
|
||||
|
||||
Only bytes actually read are charged (never the declared `file_size`), the
|
||||
budget is shared by the whole archive, and reads go in `chunk` blocks. Every
|
||||
entry we refuse or clip is recorded in `warnings`, and `cut` tells the caller
|
||||
that the extracted text is incomplete.
|
||||
"""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
zf: zipfile.ZipFile,
|
||||
entry_limit: int = _OFFICE_ENTRY_MAX_BYTES,
|
||||
total_limit: int = _OFFICE_TOTAL_MAX_BYTES,
|
||||
chunk: int = _OFFICE_READ_CHUNK,
|
||||
max_entries: int = _OFFICE_MAX_ENTRIES,
|
||||
) -> None:
|
||||
self.zf = zf
|
||||
self.entry_limit = entry_limit
|
||||
self.total_limit = total_limit
|
||||
self.chunk = chunk
|
||||
self.max_entries = max_entries
|
||||
self.consumed = 0 # bytes actually decompressed
|
||||
self.entries_read = 0
|
||||
self.cut = False
|
||||
self.warnings: list[str] = []
|
||||
|
||||
def note(self, msg: str, cut: bool = True) -> None:
|
||||
"""Record a warning; `cut=True` marks the extracted text as incomplete."""
|
||||
if cut:
|
||||
self.cut = True
|
||||
if msg not in self.warnings and len(self.warnings) < _OFFICE_MAX_WARNINGS:
|
||||
self.warnings.append(msg)
|
||||
|
||||
@property
|
||||
def remaining(self) -> int:
|
||||
return max(0, self.total_limit - self.consumed)
|
||||
|
||||
@property
|
||||
def at_entry_limit(self) -> bool:
|
||||
return self.entries_read >= self.max_entries
|
||||
|
||||
def exhausted(self) -> bool:
|
||||
return self.remaining <= 0
|
||||
|
||||
def has(self, name: str) -> bool:
|
||||
try:
|
||||
self.zf.getinfo(name)
|
||||
except KeyError:
|
||||
return False
|
||||
return True
|
||||
|
||||
def read_prefix(self, name: str, limit: int | None = None) -> tuple[str, bool]:
|
||||
"""Read the head of one entry within the budget. Returns (text, clipped).
|
||||
|
||||
No lookahead byte is read: reaching the cap is reported as clipped, which
|
||||
is conservative (an entry of exactly cap bytes is treated as cut).
|
||||
"""
|
||||
if self.at_entry_limit:
|
||||
self.note(f"файлов в архиве больше {self.max_entries} — остальные не читаются")
|
||||
return "", True
|
||||
cap = self.entry_limit if limit is None else min(limit, self.entry_limit)
|
||||
cap = min(cap, self.remaining)
|
||||
if cap <= 0:
|
||||
self.note("предел распаковки Office-архива исчерпан — часть документа не прочитана")
|
||||
return "", True
|
||||
self.entries_read += 1
|
||||
parts: list[bytes] = []
|
||||
got = 0
|
||||
with self.zf.open(name) as fh:
|
||||
while got < cap:
|
||||
block = fh.read(min(self.chunk, cap - got))
|
||||
if not block:
|
||||
break
|
||||
parts.append(block)
|
||||
got += len(block)
|
||||
self.consumed += got
|
||||
text = b"".join(parts).decode("utf-8", "replace")
|
||||
clipped = got >= cap
|
||||
if clipped:
|
||||
# Cut in the middle of the XML: drop the trailing partial tag.
|
||||
text = re.sub(r"<[^>]*$", "", text)
|
||||
self.note("часть документа не прочитана: превышен предел распаковки")
|
||||
return text, clipped
|
||||
|
||||
|
||||
def _from_docx(zf: zipfile.ZipFile) -> str:
|
||||
xml = _read_entry(zf, "word/document.xml")
|
||||
def _from_docx(reader: _OfficeBudget) -> str:
|
||||
xml, _ = reader.read_prefix("word/document.xml")
|
||||
xml = xml.replace("</w:p>", "\n").replace("<w:tab/>", "\t").replace("<w:br/>", "\n")
|
||||
return unescape(_TAG_RE.sub("", xml))
|
||||
|
||||
|
||||
def _from_pptx(zf: zipfile.ZipFile) -> str:
|
||||
def _from_pptx(reader: _OfficeBudget) -> str:
|
||||
slides = sorted(
|
||||
(n for n in zf.namelist() if re.fullmatch(r"ppt/slides/slide\d+\.xml", n)),
|
||||
key=lambda n: _num(n),
|
||||
(n for n in reader.zf.namelist() if re.fullmatch(r"ppt/slides/slide\d+\.xml", n)),
|
||||
key=_num,
|
||||
)
|
||||
out, chars, unpacked = [], 0, 0
|
||||
for n in slides[:_MAX_PPTX_SLIDES]:
|
||||
unpacked += zf.getinfo(n).file_size
|
||||
if unpacked > _MAX_UNPACKED_BYTES:
|
||||
raise RuntimeError(f"слайды распаковываются больше чем в {_MAX_UNPACKED_BYTES // 1048576} МБ")
|
||||
if chars > TEXT_BUDGET:
|
||||
break # _finish() truncates anyway; don't decompress the rest
|
||||
xml = _read_entry(zf, n)
|
||||
xml = xml.replace("</a:p>", "\n")
|
||||
out.append(f"--- {n.rsplit('/', 1)[-1]} ---\n" + unescape(_TAG_RE.sub("", xml)))
|
||||
chars += len(out[-1])
|
||||
total = len(slides)
|
||||
if total > _OFFICE_MAX_SLIDES:
|
||||
slides = slides[:_OFFICE_MAX_SLIDES]
|
||||
reader.note(f"в файле {total} слайдов — прочитаны первые {_OFFICE_MAX_SLIDES}")
|
||||
out: list[str] = []
|
||||
produced = 0
|
||||
for n in slides:
|
||||
if reader.at_entry_limit:
|
||||
reader.note(f"показаны не все слайды: {len(out)} из {total}")
|
||||
break
|
||||
if produced >= TEXT_BUDGET or reader.exhausted():
|
||||
reader.note(f"показаны не все слайды: {len(out)} из {total}")
|
||||
break
|
||||
xml, _ = reader.read_prefix(n, limit=_OFFICE_SLIDE_MAX_BYTES)
|
||||
text = unescape(_TAG_RE.sub("", xml.replace("</a:p>", "\n")))
|
||||
if text.strip():
|
||||
out.append(f"--- {n.rsplit('/', 1)[-1]} ---\n" + text)
|
||||
produced += len(text)
|
||||
return "\n".join(out)
|
||||
|
||||
|
||||
def _from_xlsx(zf: zipfile.ZipFile) -> str:
|
||||
def _from_xlsx(reader: _OfficeBudget) -> str:
|
||||
shared: list[str] = []
|
||||
if "xl/sharedStrings.xml" in zf.namelist():
|
||||
ss = _read_entry(zf, "xl/sharedStrings.xml")
|
||||
shared_clipped = False
|
||||
if reader.has("xl/sharedStrings.xml"):
|
||||
# Half the budget: otherwise the string table eats the limit and sheets stay empty.
|
||||
ss, shared_clipped = reader.read_prefix(
|
||||
"xl/sharedStrings.xml", limit=min(_OFFICE_ENTRY_MAX_BYTES, reader.total_limit // 2),
|
||||
)
|
||||
shared = [unescape(_TAG_RE.sub("", m)) for m in re.findall(r"<si>(.*?)</si>", ss, re.S)]
|
||||
sheets = [n for n in zf.namelist() if re.fullmatch(r"xl/worksheets/sheet\d+\.xml", n)]
|
||||
if shared_clipped:
|
||||
reader.note("таблица текстов прочитана частично — часть ячеек показана номером, а не значением")
|
||||
sheets = [n for n in reader.zf.namelist() if re.fullmatch(r"xl/worksheets/sheet\d+\.xml", n)]
|
||||
sheets.sort(key=lambda n: _num(n.rsplit("/", 1)[-1]))
|
||||
if len(sheets) > 3:
|
||||
reader.note(f"листов в книге {len(sheets)} — прочитаны первые 3")
|
||||
out: list[str] = []
|
||||
produced = 0
|
||||
for sheet in sheets[:3]:
|
||||
xml = _read_entry(zf, sheet)
|
||||
if reader.at_entry_limit:
|
||||
reader.note(f"показаны не все листы: {len(out)} из {len(sheets)}")
|
||||
break
|
||||
if produced >= TEXT_BUDGET or reader.exhausted():
|
||||
reader.note("предел распаковки Office-архива исчерпан — часть листов не прочитана")
|
||||
break
|
||||
label = sheet.rsplit('/', 1)[-1]
|
||||
xml, _ = reader.read_prefix(sheet)
|
||||
rows = []
|
||||
for row in re.findall(r"<row[^>]*>(.*?)</row>", xml, re.S)[:_MAX_XLSX_ROWS]:
|
||||
all_rows = re.findall(r"<row[^>]*>(.*?)</row>", xml, re.S)
|
||||
if len(all_rows) > _MAX_XLSX_ROWS:
|
||||
reader.note(f"строк в листе больше {_MAX_XLSX_ROWS} — показаны первые")
|
||||
for row in all_rows[:_MAX_XLSX_ROWS]:
|
||||
if produced >= TEXT_BUDGET:
|
||||
reader.note(f"показаны не все строки листа {label}")
|
||||
break
|
||||
cells = []
|
||||
for m in re.finditer(r"<c([^>]*)(?:/>|>(.*?)</c>)", row, re.S):
|
||||
row_chars = 0
|
||||
for count, m in enumerate(re.finditer(r"<c([^>]*)(?:/>|>(.*?)</c>)", row, re.S), start=1):
|
||||
if count > _MAX_XLSX_CELLS:
|
||||
reader.note(f"ячеек в строке больше {_MAX_XLSX_CELLS} — показаны первые")
|
||||
break
|
||||
left = TEXT_BUDGET - produced - row_chars
|
||||
if left <= 0:
|
||||
# A tiny shared string reused by many cells must not inflate
|
||||
# the output: stop expanding as soon as the budget is spent.
|
||||
reader.note(f"показаны не все ячейки листа {label}")
|
||||
break
|
||||
attrs, body = m.group(1) or "", m.group(2) or ""
|
||||
val = ""
|
||||
vm = re.search(r"<v>(.*?)</v>", body, re.S)
|
||||
@@ -158,16 +291,20 @@ def _from_xlsx(zf: zipfile.ZipFile) -> str:
|
||||
im = re.search(r"<t[^>]*>(.*?)</t>", body, re.S)
|
||||
if im:
|
||||
val = unescape(im.group(1))
|
||||
cells.append(val.replace("\t", " ").replace("\n", " "))
|
||||
val = val.replace("\t", " ").replace("\n", " ")[:left]
|
||||
row_chars += len(val)
|
||||
cells.append(val)
|
||||
if any(c.strip() for c in cells):
|
||||
rows.append("\t".join(cells))
|
||||
line = "\t".join(cells)
|
||||
rows.append(line)
|
||||
produced += len(line)
|
||||
if rows:
|
||||
out.append(f"--- {sheet.rsplit('/', 1)[-1]} ---\n" + "\n".join(rows))
|
||||
out.append(f"--- {label} ---\n" + "\n".join(rows))
|
||||
return "\n".join(out)
|
||||
|
||||
|
||||
def _from_odt(zf: zipfile.ZipFile) -> str:
|
||||
xml = _read_entry(zf, "content.xml")
|
||||
def _from_odt(reader: _OfficeBudget) -> str:
|
||||
xml, _ = reader.read_prefix("content.xml")
|
||||
xml = re.sub(r"</text:(p|h|list-item)>", "\n", xml)
|
||||
return unescape(_TAG_RE.sub("", xml))
|
||||
|
||||
@@ -175,16 +312,39 @@ def _from_odt(zf: zipfile.ZipFile) -> str:
|
||||
def _from_office(data: bytes, ext: str) -> ExtractResult:
|
||||
try:
|
||||
with zipfile.ZipFile(io.BytesIO(data)) as zf:
|
||||
names = set(zf.namelist())
|
||||
reader = _OfficeBudget(zf)
|
||||
count = len(zf.infolist())
|
||||
if count > _OFFICE_MAX_ENTRIES:
|
||||
# Informational only: the hard bound is enforced on actual reads.
|
||||
reader.note(
|
||||
f"в архиве {count} файлов — читаются не более {_OFFICE_MAX_ENTRIES}",
|
||||
cut=False,
|
||||
)
|
||||
names = zf.namelist() # central directory listing only, nothing decompressed
|
||||
text: str | None = None
|
||||
kind = ext.lstrip(".")
|
||||
if ext == ".docx" and "word/document.xml" in names:
|
||||
return _finish(_from_docx(zf), "docx")
|
||||
if ext == ".pptx" and any(n.startswith("ppt/slides/slide") for n in names):
|
||||
return _finish(_from_pptx(zf), "pptx")
|
||||
if ext in (".xlsx", ".xlsm") and any(n.startswith("xl/worksheets/") for n in names):
|
||||
return _finish(_from_xlsx(zf), "xlsx")
|
||||
if ext == ".odt" and "content.xml" in names:
|
||||
return _finish(_from_odt(zf), "odt")
|
||||
except (zipfile.BadZipFile, KeyError, ValueError, IndexError, RuntimeError) as exc:
|
||||
text, kind = _from_docx(reader), "docx"
|
||||
elif ext == ".pptx" and any(n.startswith("ppt/slides/slide") for n in names):
|
||||
text, kind = _from_pptx(reader), "pptx"
|
||||
elif ext in (".xlsx", ".xlsm") and any(n.startswith("xl/worksheets/") for n in names):
|
||||
text, kind = _from_xlsx(reader), "xlsx"
|
||||
elif ext == ".odt" and "content.xml" in names:
|
||||
text, kind = _from_odt(reader), "odt"
|
||||
if text is None:
|
||||
return ExtractResult(
|
||||
ok=False,
|
||||
reason=f"{ext} без ожидаемой структуры — возможно, старый формат (.doc/.xls/.ppt)",
|
||||
)
|
||||
res = _finish(text, kind, reader.warnings, cut=reader.cut)
|
||||
if not res.ok and reader.cut:
|
||||
return ExtractResult(
|
||||
ok=False, kind=kind, truncated=True,
|
||||
reason="текста нет: сработал предел распаковки Office-файла (архив слишком «плотный»)",
|
||||
warnings=list(reader.warnings),
|
||||
)
|
||||
return res
|
||||
except (zipfile.BadZipFile, KeyError, ValueError, IndexError, RuntimeError, EOFError, zlib.error) as exc:
|
||||
return ExtractResult(ok=False, reason=f"{ext} повреждён или слишком большой внутри: {type(exc).__name__}")
|
||||
return ExtractResult(ok=False, reason=f"{ext} без ожидаемой структуры — возможно, старый формат (.doc/.xls/.ppt)")
|
||||
|
||||
|
||||
Reference in New Issue
Block a user