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.
398 lines
18 KiB
Python
398 lines
18 KiB
Python
"""Office-извлечение: обычные файлы, битые архивы и пределы распаковки.
|
||
|
||
ZIP раздувает вход: 8 МБ .pptx распаковываются в сотни МБ. Тесты проверяют,
|
||
что читаются фактические байты, а не объявленный размер, что лимит общий на
|
||
архив, что чтение идёт кусками и что ранний выход срабатывает, когда текста уже
|
||
достаточно. Никаких гигантских файлов: лимиты подменяются на маленькие.
|
||
"""
|
||
import importlib
|
||
import io
|
||
import sys
|
||
import unittest
|
||
import warnings
|
||
import zipfile
|
||
from pathlib import Path
|
||
from unittest import mock
|
||
|
||
BOT = Path(__file__).resolve().parents[1] / "bot"
|
||
sys.path.insert(0, str(BOT))
|
||
file_intake = importlib.import_module("file_intake")
|
||
extract = file_intake.extract
|
||
_OfficeBudget = file_intake._OfficeBudget
|
||
|
||
|
||
def _zip_bytes(entries) -> bytes:
|
||
"""Собрать zip в памяти. `entries` — список пар (name, bytes); дубликаты разрешены."""
|
||
buf = io.BytesIO()
|
||
with warnings.catch_warnings():
|
||
warnings.simplefilter("ignore", UserWarning) # duplicate names are part of the scenario
|
||
with zipfile.ZipFile(buf, "w", zipfile.ZIP_DEFLATED) as zf:
|
||
for name, data in entries:
|
||
zf.writestr(name, data)
|
||
return buf.getvalue()
|
||
|
||
|
||
def _docx_bytes(text: str = "Привет, мир") -> bytes:
|
||
return _zip_bytes([
|
||
("[Content_Types].xml", b"<Types/>"),
|
||
("word/document.xml",
|
||
f'<?xml version="1.0"?><w:document><w:body><w:p><w:r><w:t>{text}</w:t></w:r></w:p></w:body></w:document>'.encode()),
|
||
])
|
||
|
||
|
||
def _slide_body(text: str) -> bytes:
|
||
return (
|
||
'<?xml version="1.0"?><p:sld><p:cSld><p:spTree><p:sp><p:txBody>'
|
||
f'<a:p><a:r><a:t>{text}</a:t></a:r></a:p>'
|
||
'</p:txBody></p:sp></p:spTree></p:cSld></p:sld>'
|
||
).encode()
|
||
|
||
|
||
def _pptx_bytes(texts) -> bytes:
|
||
entries = [("[Content_Types].xml", b"<Types/>")]
|
||
for i, text in enumerate(texts, start=1):
|
||
entries.append((f"ppt/slides/slide{i}.xml", _slide_body(text)))
|
||
return _zip_bytes(entries)
|
||
|
||
|
||
def _xlsx_bytes(shared, rows) -> bytes:
|
||
items = "".join(f"<si><t>{s}</t></si>" for s in shared)
|
||
cells = "".join(
|
||
f'<c r="A{n}" t="s"><v>{idx}</v></c>' for n, idx in enumerate(rows, start=1)
|
||
)
|
||
sheet = (
|
||
'<?xml version="1.0"?><worksheet><sheetData>'
|
||
f'<row r="1">{cells}</row>'
|
||
'</sheetData></worksheet>'
|
||
).encode()
|
||
return _zip_bytes([
|
||
("[Content_Types].xml", b"<Types/>"),
|
||
("xl/sharedStrings.xml", f"<sst>{items}</sst>".encode()),
|
||
("xl/worksheets/sheet1.xml", sheet),
|
||
])
|
||
|
||
|
||
def _odt_bytes(paras) -> bytes:
|
||
body = "".join(f"<text:p>{p}</text:p>" for p in paras)
|
||
return _zip_bytes([
|
||
("[Content_Types].xml", b"<Types/>"),
|
||
("content.xml", f'<?xml version="1.0"?><office:document><office:body>{body}</office:body></office:document>'.encode()),
|
||
])
|
||
|
||
|
||
class _SpyZip:
|
||
"""Прокси над ZipFile: считает открытия записей и запрошенные размеры read()."""
|
||
|
||
def __init__(self, zf: zipfile.ZipFile) -> None:
|
||
self._zf = zf
|
||
self.opened: list[str] = []
|
||
self.read_sizes: list[int] = []
|
||
|
||
def namelist(self):
|
||
return self._zf.namelist()
|
||
|
||
def infolist(self):
|
||
return self._zf.infolist()
|
||
|
||
def getinfo(self, name):
|
||
return self._zf.getinfo(name)
|
||
|
||
def open(self, name, *args, **kwargs):
|
||
self.opened.append(name)
|
||
raw = self._zf.open(name, *args, **kwargs)
|
||
spy = self
|
||
|
||
class _File:
|
||
def read(self, n=-1):
|
||
spy.read_sizes.append(n)
|
||
return raw.read(n)
|
||
|
||
def __enter__(self):
|
||
return self
|
||
|
||
def __exit__(self, *exc):
|
||
raw.close()
|
||
return False
|
||
|
||
return _File()
|
||
|
||
|
||
class _RecordingBudget(_OfficeBudget):
|
||
"""Запоминает созданные читатели, чтобы проверить фактический объём распаковки."""
|
||
|
||
created: list = []
|
||
|
||
def __init__(self, *args, **kwargs) -> None:
|
||
super().__init__(*args, **kwargs)
|
||
_RecordingBudget.created.append(self)
|
||
|
||
|
||
class OfficeExtractionTest(unittest.TestCase):
|
||
def setUp(self) -> None:
|
||
_RecordingBudget.created = []
|
||
|
||
# --- normal extraction --------------------------------------------------
|
||
|
||
def test_docx_plain_text(self) -> None:
|
||
res = extract("заметка.docx", _docx_bytes())
|
||
self.assertTrue(res.ok, res.reason)
|
||
self.assertEqual(res.kind, "docx")
|
||
self.assertIn("Привет, мир", res.text)
|
||
self.assertFalse(res.truncated)
|
||
self.assertEqual(res.chars, len(res.text))
|
||
|
||
def test_pptx_slides_order_and_labels(self) -> None:
|
||
res = extract("deck.pptx", _pptx_bytes(["первый", "второй", "третий"]))
|
||
self.assertTrue(res.ok, res.reason)
|
||
self.assertEqual(res.kind, "pptx")
|
||
self.assertLess(res.text.index("первый"), res.text.index("второй"))
|
||
self.assertLess(res.text.index("второй"), res.text.index("третий"))
|
||
self.assertIn("slide1.xml", res.text)
|
||
|
||
def test_xlsx_shared_strings_resolved(self) -> None:
|
||
res = extract("таблица.xlsx", _xlsx_bytes(["альфа", "бета"], [1, 0]))
|
||
self.assertTrue(res.ok, res.reason)
|
||
line = [ln for ln in res.text.splitlines() if "\t" in ln][0]
|
||
self.assertEqual(line.split("\t"), ["бета", "альфа"])
|
||
|
||
def test_odt_paragraphs(self) -> None:
|
||
res = extract("док.odt", _odt_bytes(["первый абзац", "второй абзац"]))
|
||
self.assertTrue(res.ok, res.reason)
|
||
self.assertEqual(res.kind, "odt")
|
||
self.assertIn("первый абзац", res.text)
|
||
self.assertIn("второй абзац", res.text)
|
||
|
||
# --- refusals -----------------------------------------------------------
|
||
|
||
def test_corrupt_archive_is_reported(self) -> None:
|
||
res = extract("битый.pptx", b"PK\x03\x04 definitely not a real zip")
|
||
self.assertFalse(res.ok)
|
||
self.assertIn("повреждён", res.reason)
|
||
|
||
def test_broken_compressed_stream_is_reported(self) -> None:
|
||
data = _pptx_bytes(["text"])
|
||
errors = (EOFError("truncated compressed stream"),
|
||
file_intake.zlib.error("invalid compressed stream"))
|
||
for error in errors:
|
||
with self.subTest(error=type(error).__name__):
|
||
with mock.patch.object(zipfile.ZipFile, "open", side_effect=error):
|
||
result = extract("broken.pptx", data)
|
||
self.assertFalse(result.ok)
|
||
self.assertIn("повреждён", result.reason)
|
||
|
||
def test_zip_without_office_structure(self) -> None:
|
||
data = _zip_bytes([("readme.txt", b"just a zip")])
|
||
res = extract("файл.docx", data)
|
||
self.assertFalse(res.ok)
|
||
self.assertIn("без ожидаемой структуры", res.reason)
|
||
|
||
def test_upload_limit_unchanged(self) -> None:
|
||
res = extract("big.docx", b"\0" * (file_intake.MAX_FILE_BYTES + 1))
|
||
self.assertFalse(res.ok)
|
||
self.assertIn("предел", res.reason)
|
||
self.assertEqual(file_intake.MAX_FILE_BYTES, 8 * 1024 * 1024)
|
||
|
||
# --- decompression limits -----------------------------------------------
|
||
|
||
def test_entry_limit_bounds_actual_bytes(self) -> None:
|
||
payload = ("слово " * 4000).encode() # ~24 KB of text, compresses well
|
||
data = _zip_bytes([("word/document.xml", payload)])
|
||
with zipfile.ZipFile(io.BytesIO(data)) as real:
|
||
spy = _SpyZip(real)
|
||
reader = _OfficeBudget(spy, entry_limit=1000)
|
||
text, clipped = reader.read_prefix("word/document.xml")
|
||
self.assertTrue(clipped)
|
||
self.assertLessEqual(reader.consumed, 1000)
|
||
self.assertLessEqual(sum(spy.read_sizes), 1000) # bytes actually read
|
||
self.assertEqual(sum(spy.read_sizes), reader.consumed)
|
||
self.assertNotIn(-1, spy.read_sizes)
|
||
self.assertLessEqual(len(text), 1000)
|
||
self.assertEqual(reader.entries_read, 1)
|
||
self.assertTrue(reader.cut)
|
||
self.assertTrue(reader.warnings)
|
||
|
||
def test_exact_cap_needs_no_lookahead(self) -> None:
|
||
"""Ровно лимит байт: без досмотра лишнего байта, но помечается как обрезанное."""
|
||
payload = b"a" * 1024
|
||
data = _zip_bytes([("word/document.xml", payload)])
|
||
with zipfile.ZipFile(io.BytesIO(data)) as real:
|
||
spy = _SpyZip(real)
|
||
reader = _OfficeBudget(spy, entry_limit=1024, chunk=4096)
|
||
text, clipped = reader.read_prefix("word/document.xml")
|
||
self.assertEqual(spy.read_sizes, [1024]) # a single read, exactly the cap
|
||
self.assertEqual(sum(spy.read_sizes), reader.consumed)
|
||
self.assertLessEqual(sum(spy.read_sizes), 1024)
|
||
self.assertEqual(len(text), 1024)
|
||
self.assertTrue(clipped) # an entry exactly at the cap is conservatively reported as cut
|
||
self.assertTrue(reader.cut)
|
||
|
||
def test_entry_limit_does_not_trust_declared_size(self) -> None:
|
||
# small input, large decompressed size: only real reads are charged
|
||
payload = b"a" * 200_000
|
||
data = _zip_bytes([("word/document.xml", payload)])
|
||
self.assertLess(len(data), 5000)
|
||
with zipfile.ZipFile(io.BytesIO(data)) as zf:
|
||
reader = _OfficeBudget(zf, entry_limit=5000)
|
||
reader.read_prefix("word/document.xml")
|
||
self.assertLessEqual(reader.consumed, 5000)
|
||
|
||
def test_total_budget_shared_across_entries(self) -> None:
|
||
data = _zip_bytes([
|
||
("ppt/slides/slide1.xml", b"x" * 5000),
|
||
("ppt/slides/slide2.xml", b"x" * 5000),
|
||
("ppt/slides/slide3.xml", b"x" * 5000),
|
||
])
|
||
with zipfile.ZipFile(io.BytesIO(data)) as real:
|
||
spy = _SpyZip(real)
|
||
reader = _OfficeBudget(spy, entry_limit=5000, total_limit=12_000)
|
||
for name in ("ppt/slides/slide1.xml", "ppt/slides/slide2.xml", "ppt/slides/slide3.xml"):
|
||
reader.read_prefix(name)
|
||
self.assertLessEqual(reader.consumed, 12_000)
|
||
self.assertLessEqual(sum(spy.read_sizes), 12_000)
|
||
self.assertEqual(sum(spy.read_sizes), reader.consumed)
|
||
self.assertTrue(reader.cut)
|
||
self.assertTrue(any("предел" in w for w in reader.warnings))
|
||
|
||
def test_entry_cap_bounds_actual_reads(self) -> None:
|
||
"""Жёсткий предел на число записей: дальше лимита записи не открываются."""
|
||
names = [f"part{i}.xml" for i in range(1, 21)]
|
||
data = _zip_bytes([(n, b"<x>tiny</x>") for n in names])
|
||
with zipfile.ZipFile(io.BytesIO(data)) as real:
|
||
spy = _SpyZip(real)
|
||
reader = _OfficeBudget(spy, max_entries=5)
|
||
for name in names[:8]:
|
||
reader.read_prefix(name)
|
||
self.assertEqual(reader.entries_read, 5)
|
||
self.assertEqual(len(spy.opened), 5) # nothing is opened past the entry cap
|
||
self.assertTrue(reader.cut)
|
||
self.assertTrue(any("не читаются" in w for w in reader.warnings))
|
||
|
||
def test_reads_are_chunked(self) -> None:
|
||
data = _zip_bytes([("word/document.xml", b"y" * 20_000)])
|
||
with zipfile.ZipFile(io.BytesIO(data)) as real:
|
||
spy = _SpyZip(real)
|
||
reader = _OfficeBudget(spy, entry_limit=20_000, chunk=1024)
|
||
reader.read_prefix("word/document.xml")
|
||
self.assertTrue(spy.read_sizes)
|
||
self.assertNotIn(-1, spy.read_sizes) # never read a whole entry at once
|
||
self.assertLessEqual(max(spy.read_sizes), 1024)
|
||
self.assertGreater(len(spy.read_sizes), 1)
|
||
|
||
def test_slide_count_capped(self) -> None:
|
||
texts = [f"слайд {i}" for i in range(1, 11)]
|
||
with mock.patch.object(file_intake, "_OFFICE_MAX_SLIDES", 3):
|
||
with zipfile.ZipFile(io.BytesIO(_pptx_bytes(texts))) as real:
|
||
spy = _SpyZip(real)
|
||
reader = _OfficeBudget(spy)
|
||
text = file_intake._from_pptx(reader)
|
||
self.assertEqual(len(spy.opened), 3)
|
||
self.assertIn("слайд 3", text)
|
||
self.assertNotIn("слайд 4", text)
|
||
self.assertTrue(any("прочитаны первые 3" in w for w in reader.warnings))
|
||
|
||
def test_slide_byte_limit(self) -> None:
|
||
texts = ["текст " * 2000, "хвост"]
|
||
with mock.patch.object(file_intake, "_OFFICE_SLIDE_MAX_BYTES", 400):
|
||
with zipfile.ZipFile(io.BytesIO(_pptx_bytes(texts))) as real:
|
||
reader = _OfficeBudget(real)
|
||
file_intake._from_pptx(reader)
|
||
self.assertLessEqual(reader.consumed, 800) # per-slide cap
|
||
self.assertTrue(reader.cut)
|
||
|
||
def test_markup_heavy_slide_stays_bounded(self) -> None:
|
||
markup = ('<a:p><a:r><a:rPr lang="ru-RU" sz="1800" b="1"/><a:t>'
|
||
+ "i" * 50 + "</a:t></a:r></a:p>") * 200 # ~24 KB of markup, ~10 KB of text
|
||
data = _zip_bytes([("ppt/slides/slide1.xml", markup.encode())])
|
||
with mock.patch.object(file_intake, "_OFFICE_SLIDE_MAX_BYTES", 2000):
|
||
res = extract("тяжёлый.pptx", data)
|
||
self.assertTrue(res.truncated)
|
||
self.assertLessEqual(len(res.text), file_intake.TEXT_BUDGET)
|
||
self.assertTrue(res.warnings)
|
||
|
||
def test_early_stop_when_enough_text(self) -> None:
|
||
texts = [f"слайд номер {i} " + "z" * 500 for i in range(1, 41)]
|
||
with mock.patch.object(file_intake, "TEXT_BUDGET", 300):
|
||
with zipfile.ZipFile(io.BytesIO(_pptx_bytes(texts))) as real:
|
||
spy = _SpyZip(real)
|
||
reader = _OfficeBudget(spy)
|
||
res = file_intake._finish(
|
||
file_intake._from_pptx(reader), "pptx", reader.warnings, cut=reader.cut,
|
||
)
|
||
self.assertTrue(res.ok, res.reason)
|
||
self.assertTrue(res.truncated)
|
||
self.assertLess(len(spy.opened), len(texts)) # stops before the end
|
||
self.assertLessEqual(len(res.text), 300)
|
||
self.assertTrue(any("показаны не все слайды" in w for w in res.warnings))
|
||
|
||
def test_eight_compressible_slides_bounded(self) -> None:
|
||
"""Исходный сценарий: 8 «плотных» слайдов. Объём ограничен байтами, не памятью."""
|
||
texts = [("слайд " + "q" * 3000) for _ in range(8)]
|
||
data = _pptx_bytes(texts)
|
||
self.assertLess(len(data), 20_000) # small input
|
||
with mock.patch.object(file_intake, "_OfficeBudget", _RecordingBudget):
|
||
res = extract("amplify.pptx", data)
|
||
self.assertTrue(_RecordingBudget.created)
|
||
reader = _RecordingBudget.created[-1]
|
||
self.assertLessEqual(reader.consumed, file_intake._OFFICE_TOTAL_MAX_BYTES)
|
||
self.assertLessEqual(len(res.text), file_intake.TEXT_BUDGET)
|
||
self.assertTrue(res.ok, res.reason)
|
||
|
||
def test_truncation_is_announced(self) -> None:
|
||
data = _pptx_bytes(["а" * 5000, "б" * 5000, "в" * 5000, "г" * 5000, "д" * 5000, "е" * 5000])
|
||
res = extract("long.pptx", data)
|
||
self.assertTrue(res.ok, res.reason)
|
||
self.assertTrue(res.truncated)
|
||
self.assertTrue(any("показаны первые" in w for w in res.warnings))
|
||
|
||
def test_duplicate_entry_read_once(self) -> None:
|
||
data = _zip_bytes([
|
||
("word/document.xml", "<w:document><w:p><w:t>старый</w:t></w:p></w:document>".encode()),
|
||
("word/document.xml", "<w:document><w:p><w:t>новый</w:t></w:p></w:document>".encode()),
|
||
])
|
||
with mock.patch.object(file_intake, "_OfficeBudget", _RecordingBudget):
|
||
res = extract("dubl.docx", data)
|
||
self.assertTrue(res.ok, res.reason)
|
||
reader = _RecordingBudget.created[-1]
|
||
self.assertEqual(reader.entries_read, 1)
|
||
self.assertIn("новый", res.text)
|
||
self.assertLessEqual(reader.consumed, len(data) * 8)
|
||
|
||
|
||
# --- XLSX: one row must not inflate the text ------------------
|
||
|
||
def test_xlsx_reused_string_cannot_inflate_output(self) -> None:
|
||
"""Одна короткая строка sharedStrings на 3000 ячеек не даёт длинный текст."""
|
||
data = _xlsx_bytes(["z" * 40], [0] * 3000)
|
||
self.assertLess(len(data), 20_000) # small input
|
||
with mock.patch.object(file_intake, "TEXT_BUDGET", 500):
|
||
with zipfile.ZipFile(io.BytesIO(data)) as real:
|
||
reader = _OfficeBudget(real)
|
||
text = file_intake._from_xlsx(reader)
|
||
self.assertLessEqual(len(text), 600)
|
||
self.assertTrue(any("ячейк" in w for w in reader.warnings))
|
||
self.assertTrue(reader.cut)
|
||
|
||
def test_xlsx_amplification_marked_truncated(self) -> None:
|
||
data = _xlsx_bytes(["z" * 40], [0] * 3000)
|
||
self.assertLess(len(data), 20_000) # small input, thousands of cells
|
||
with mock.patch.object(file_intake, "TEXT_BUDGET", 500):
|
||
res = extract("широкая.xlsx", data)
|
||
self.assertEqual(file_intake.TEXT_BUDGET, 500)
|
||
self.assertTrue(res.ok, res.reason)
|
||
self.assertTrue(res.truncated)
|
||
self.assertLessEqual(len(res.text), 500)
|
||
self.assertGreater(len(res.text), 100) # useful prefix survives
|
||
self.assertTrue(res.warnings)
|
||
|
||
def test_xlsx_cell_count_capped(self) -> None:
|
||
data = _xlsx_bytes(["z"], [0] * 3000)
|
||
with zipfile.ZipFile(io.BytesIO(data)) as real:
|
||
reader = _OfficeBudget(real)
|
||
text = file_intake._from_xlsx(reader)
|
||
self.assertTrue(any(f"ячеек в строке больше {file_intake._MAX_XLSX_CELLS}" in w
|
||
for w in reader.warnings))
|
||
self.assertEqual(text.splitlines()[-1].count("\t") + 1, file_intake._MAX_XLSX_CELLS)
|
||
|
||
|
||
if __name__ == "__main__":
|
||
unittest.main() |