Merge pull request #3 from Alpaq92/security/docx-cap-and-core-pin
Bound the cut of an upload; repin dredd-core to v0.23.1
This commit is contained in:
@@ -18,7 +18,7 @@ permissive (no copyleft).
|
||||
The core is pinned by tag in `backend/requirements.txt`:
|
||||
|
||||
```
|
||||
dredd-core @ git+https://github.com/Alpaq92/dredd-core@v0.22.0
|
||||
dredd-core @ git+https://github.com/Alpaq92/dredd-core@v0.23.1
|
||||
```
|
||||
|
||||
It is a **private** repository, so installing it needs a token — see `README.md` for the
|
||||
|
||||
@@ -22,7 +22,7 @@ writer, the security primitives, the shared enums and error types, and the engin
|
||||
factories all come from one installed package. `backend/requirements.txt` pins it by tag:
|
||||
|
||||
```
|
||||
dredd-core @ git+https://github.com/Alpaq92/dredd-core@v0.22.0
|
||||
dredd-core @ git+https://github.com/Alpaq92/dredd-core@v0.23.1
|
||||
```
|
||||
|
||||
The app-side files that used to hold that code (`services/auth.py`, `models/__init__.py`,
|
||||
|
||||
@@ -19,8 +19,12 @@ from ..services import sources as service
|
||||
router = APIRouter(prefix="/sources", tags=["sources"])
|
||||
|
||||
|
||||
async def _read_upload(file: UploadFile) -> bytes:
|
||||
data = await file.read(MAX_FILE_BYTES + 1)
|
||||
def _read_upload(file: UploadFile) -> bytes:
|
||||
"""The upload's bytes, read synchronously. The routes that take a file are plain `def` on
|
||||
purpose: the cut runs in the request (`services/sources.py`) and is CPU-bound, and in an
|
||||
`async def` it would run on the event loop and stall every other request of this worker.
|
||||
Starlette has spooled the body by now, so this read is from that file."""
|
||||
data = file.file.read(MAX_FILE_BYTES + 1)
|
||||
if len(data) > MAX_FILE_BYTES:
|
||||
raise ValidationError("Plik jest za duży.", {"code": "file_too_large"})
|
||||
return data
|
||||
@@ -50,13 +54,13 @@ def raw(source_id: uuid.UUID, request: Request, download: bool = False,
|
||||
|
||||
|
||||
@router.post("/upload", status_code=201)
|
||||
async def upload(request: Request, file: UploadFile = File(...),
|
||||
title: str | None = Form(None, max_length=200),
|
||||
note: str | None = Form(None, max_length=4000),
|
||||
shared: bool = Form(False),
|
||||
db: Session = Depends(get_db),
|
||||
user: AppUser = Depends(get_current_user)) -> dict:
|
||||
data = await _read_upload(file)
|
||||
def upload(request: Request, file: UploadFile = File(...),
|
||||
title: str | None = Form(None, max_length=200),
|
||||
note: str | None = Form(None, max_length=4000),
|
||||
shared: bool = Form(False),
|
||||
db: Session = Depends(get_db),
|
||||
user: AppUser = Depends(get_current_user)) -> dict:
|
||||
data = _read_upload(file)
|
||||
out = service.create_from_file(db, user, data=data, name=file.filename or "plik",
|
||||
title=title, note=note, shared=shared, ip=client_ip(request))
|
||||
db.commit()
|
||||
@@ -75,10 +79,10 @@ def from_document(body: SourceDocumentIn, request: Request, db: Session = Depend
|
||||
|
||||
|
||||
@router.post("/{source_id}/file")
|
||||
async def new_file(source_id: uuid.UUID, request: Request, file: UploadFile = File(...),
|
||||
db: Session = Depends(get_db),
|
||||
user: AppUser = Depends(get_current_user)) -> dict:
|
||||
data = await _read_upload(file)
|
||||
def new_file(source_id: uuid.UUID, request: Request, file: UploadFile = File(...),
|
||||
db: Session = Depends(get_db),
|
||||
user: AppUser = Depends(get_current_user)) -> dict:
|
||||
data = _read_upload(file)
|
||||
out = service.replace_file(db, user, source_id, data=data, name=file.filename or "plik",
|
||||
ip=client_ip(request))
|
||||
db.commit()
|
||||
|
||||
@@ -19,18 +19,32 @@ and have all three import it — a change in the Compass repo, listed for the ow
|
||||
**Plain text too.** `.txt` / `.md` sources are read as UTF-8 and parsed the same way; the seed's demo
|
||||
source is one, so the demo stands without a PDF or DOCX. A text file has no pages.
|
||||
|
||||
**Bounded, because any user of the module can upload.** A source is at most
|
||||
`plain_files.MAX_FILE_BYTES`, but what it unpacks into is not: a DOCX is a ZIP, and
|
||||
`compass_ingestion` reads `word/document.xml` whole with `ZipFile.read`, whatever size it unpacks
|
||||
to (deflate packs about a thousand to one, and CPython inflates up to 1 GiB in a single step) — a
|
||||
few MiB of upload is gigabytes of memory in this process. So a DOCX reaches the reader only as a
|
||||
copy rebuilt here (`_bounded_docx`): the two parts the reader uses, each read in small chunks and
|
||||
refused past `MAX_DOCX_PART_BYTES`, stored or deflated only. Then the text (`MAX_TEXT_CHARS`) and
|
||||
the clauses (`MAX_CLAUSES`) are bounded too, since every clause is a row written in the request
|
||||
and a line in the typing queue. ponytail: the ZIP bound belongs in `compass_ingestion` itself
|
||||
(Arbiter uses the same reader); once it is there, `_bounded_docx` can go.
|
||||
|
||||
No session, no ORM, no I/O beyond the one temporary file `extract_text` needs a path for.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import io
|
||||
import os
|
||||
import tempfile
|
||||
import zipfile
|
||||
from bisect import bisect_right
|
||||
from collections.abc import Sequence
|
||||
from dataclasses import dataclass, field
|
||||
from pathlib import Path
|
||||
|
||||
from compass_ingestion.decimal_structure import parse_decimal_structure
|
||||
from compass_ingestion.numbering import NUMBERING_PART
|
||||
from compass_ingestion.structure import parse_structure
|
||||
from compass_ingestion.text import UnsupportedDocumentError, extract_text
|
||||
from compass_schemas.structure import NodePath, StructureNode, find_nodes, node_at_offset
|
||||
@@ -45,6 +59,24 @@ UNREADABLE = "Nie udało się odczytać tekstu pliku."
|
||||
#: Compass's `services/clauses.NO_CLAUSES`, said for a library rather than for an engine run.
|
||||
NO_NUMBERING = ("W dokumencie nie znaleziono numeracji (§ ani 1.1), więc nie ma klauzul do "
|
||||
"biblioteki.")
|
||||
TOO_LARGE = "Dokument jest za duży, żeby go pociąć."
|
||||
TOO_MANY = "Dokument ma za dużo klauzul, żeby go pociąć."
|
||||
|
||||
#: The DOCX parts `compass_ingestion.extract_text` reads; nothing else of the archive is passed on.
|
||||
DOCX_DOCUMENT_PART = "word/document.xml"
|
||||
DOCX_PARTS = (DOCX_DOCUMENT_PART, NUMBERING_PART)
|
||||
#: One unpacked DOCX part. A two-hundred-page contract's `document.xml` is a few MiB.
|
||||
MAX_DOCX_PART_BYTES = 16 * 1024 * 1024
|
||||
#: The read size while unpacking: what one step may inflate to, so the bound is checked often.
|
||||
_DOCX_CHUNK = 64 * 1024
|
||||
#: The extracted text of one source, in characters: about two thousand pages.
|
||||
MAX_TEXT_CHARS = 4_000_000
|
||||
#: The clauses of one cut: each is a row written in the request and a line sent to the typing model.
|
||||
MAX_CLAUSES = 5000
|
||||
|
||||
|
||||
class TooLarge(ValueError):
|
||||
"""A source past one of the bounds above; its row fails with `TOO_LARGE`."""
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
@@ -136,16 +168,55 @@ def cut(data: bytes, name: str) -> Cut:
|
||||
text, pages = data.decode("utf-8-sig"), None
|
||||
else:
|
||||
text, pages = _extract(data, suffix)
|
||||
except TooLarge:
|
||||
return Cut(reason=TOO_LARGE, failed=True)
|
||||
except (UnicodeDecodeError, UnsupportedDocumentError, OSError, ValueError):
|
||||
return Cut(reason=UNREADABLE, failed=True)
|
||||
except Exception: # noqa: BLE001 — a hostile file may break the reader any way it likes
|
||||
return Cut(reason=UNREADABLE, failed=True)
|
||||
if len(text) > MAX_TEXT_CHARS:
|
||||
return Cut(reason=TOO_LARGE, failed=True)
|
||||
clauses = clauses_of_text(text, pages)
|
||||
if len(clauses) > MAX_CLAUSES:
|
||||
return Cut(reason=TOO_MANY, failed=True)
|
||||
return Cut(clauses=clauses) if clauses else Cut(reason=NO_NUMBERING)
|
||||
|
||||
|
||||
def _bounded_docx(data: bytes) -> bytes:
|
||||
"""The DOCX as a new archive holding only `DOCX_PARTS`, each unpacked here in chunks of
|
||||
`_DOCX_CHUNK` and refused past `MAX_DOCX_PART_BYTES` (module docstring). Only the bytes read
|
||||
here go on, so a part that inflates past the size it declares cannot reach the reader either.
|
||||
Raises `TooLarge` past the bound, `zipfile.BadZipFile` for a damaged archive, and `ValueError`
|
||||
for a compression a Word document does not use (only stored and deflated: the others inflate a
|
||||
whole read at once, whatever size is asked for). A part the archive lacks is left out, and
|
||||
`extract_text` says what is missing."""
|
||||
out = io.BytesIO()
|
||||
with zipfile.ZipFile(io.BytesIO(data)) as archive, \
|
||||
zipfile.ZipFile(out, "w", zipfile.ZIP_DEFLATED) as rebuilt:
|
||||
for name in DOCX_PARTS:
|
||||
try:
|
||||
info = archive.getinfo(name)
|
||||
except KeyError:
|
||||
continue
|
||||
if info.compress_type not in (zipfile.ZIP_STORED, zipfile.ZIP_DEFLATED):
|
||||
raise ValueError(f"{name}: compression {info.compress_type} is not read here")
|
||||
if info.file_size > MAX_DOCX_PART_BYTES:
|
||||
raise TooLarge(name)
|
||||
body = bytearray()
|
||||
with archive.open(info) as part:
|
||||
while chunk := part.read(_DOCX_CHUNK):
|
||||
body += chunk
|
||||
if len(body) > MAX_DOCX_PART_BYTES:
|
||||
raise TooLarge(name)
|
||||
rebuilt.writestr(name, bytes(body))
|
||||
return out.getvalue()
|
||||
|
||||
|
||||
def _extract(data: bytes, suffix: str) -> tuple[str, tuple[int, ...] | None]:
|
||||
"""`extract_text` wants a path; the copy is named by the suffix only, never the user's name."""
|
||||
"""`extract_text` wants a path; the copy is named by the suffix only, never the user's name.
|
||||
A DOCX is passed on only as `_bounded_docx`'s copy."""
|
||||
if suffix == ".docx":
|
||||
data = _bounded_docx(data)
|
||||
handle, path = tempfile.mkstemp(prefix="lexicon-cut-", suffix=suffix)
|
||||
try:
|
||||
with os.fdopen(handle, "wb") as out:
|
||||
|
||||
@@ -25,7 +25,7 @@
|
||||
# The repo is PRIVATE, so pip needs credentials to fetch it:
|
||||
# local — a GitHub PAT in your git credential helper (or an SSH `insteadOf` rewrite)
|
||||
# CI — the DREDD_CORE_TOKEN repo secret; see the auth step in .github/workflows/ci.yml
|
||||
dredd-core @ git+https://github.com/Alpaq92/dredd-core@v0.23.0
|
||||
dredd-core @ git+https://github.com/Alpaq92/dredd-core@v0.23.1
|
||||
|
||||
# Web framework
|
||||
fastapi==0.115.6
|
||||
|
||||
@@ -60,14 +60,14 @@ def test_what_cannot_be_read_fails_its_row_without_raising(data, name):
|
||||
assert cut.failed and cut.reason and cut.clauses == []
|
||||
|
||||
|
||||
def _docx(paragraphs: list[str]) -> bytes:
|
||||
def _docx(paragraphs: list[str], compression: int = zipfile.ZIP_STORED) -> bytes:
|
||||
body = "".join(f"<w:p><w:r><w:t xml:space=\"preserve\">{p}</w:t></w:r></w:p>"
|
||||
for p in paragraphs)
|
||||
document = ('<?xml version="1.0" encoding="UTF-8" standalone="yes"?>'
|
||||
'<w:document xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main">'
|
||||
f"<w:body>{body}</w:body></w:document>")
|
||||
out = io.BytesIO()
|
||||
with zipfile.ZipFile(out, "w") as z:
|
||||
with zipfile.ZipFile(out, "w", compression=compression) as z:
|
||||
z.writestr("[Content_Types].xml", '<?xml version="1.0"?><Types xmlns="http://schemas.'
|
||||
'openxmlformats.org/package/2006/content-types"/>')
|
||||
z.writestr("word/document.xml", document)
|
||||
@@ -124,6 +124,70 @@ def test_a_pdf_is_read_by_compass_ingestion_with_pages():
|
||||
assert {c["page"] for c in cut.clauses} == {1}
|
||||
|
||||
|
||||
DOCX_CLAUSES = [
|
||||
"UMOWA", "§ 1. Przedmiotem umowy jest dostawa sprzętu biurowego dla Zamawiającego.",
|
||||
"§ 2. Wynagrodzenie wynosi 1000 zł i jest płatne przelewem w terminie 14 dni."]
|
||||
|
||||
|
||||
def test_a_docx_that_unpacks_past_the_bound_is_refused_before_it_is_read(monkeypatch):
|
||||
"""A few KiB of upload inflating into far more is the bomb: the row fails, and
|
||||
`compass_ingestion` never gets the archive to read whole."""
|
||||
# Deflated, as a real bomb is: the default archive here is stored, which would not be small.
|
||||
data = _docx(DOCX_CLAUSES + ["x" * 200_000], compression=zipfile.ZIP_DEFLATED)
|
||||
assert len(data) < 20_000
|
||||
monkeypatch.setattr(cutting, "MAX_DOCX_PART_BYTES", 100_000)
|
||||
seen = []
|
||||
monkeypatch.setattr(cutting, "extract_text", lambda path: seen.append(path))
|
||||
cut = cutting.cut(data, "umowa.docx")
|
||||
assert (cut.failed, cut.reason, seen) == (True, cutting.TOO_LARGE, [])
|
||||
|
||||
|
||||
def test_a_docx_part_whose_declared_size_is_past_the_bound_is_never_unpacked(monkeypatch):
|
||||
monkeypatch.setattr(cutting, "MAX_DOCX_PART_BYTES", 10)
|
||||
with pytest.raises(cutting.TooLarge):
|
||||
cutting._bounded_docx(_docx(DOCX_CLAUSES))
|
||||
|
||||
|
||||
def test_only_the_parts_the_reader_uses_reach_it():
|
||||
data = _docx(DOCX_CLAUSES)
|
||||
out = io.BytesIO(data)
|
||||
with zipfile.ZipFile(out, "a") as z:
|
||||
z.writestr("word/media/huge.bin", b"\x00" * 100_000)
|
||||
with zipfile.ZipFile(io.BytesIO(cutting._bounded_docx(out.getvalue()))) as rebuilt:
|
||||
assert rebuilt.namelist() == [cutting.DOCX_DOCUMENT_PART]
|
||||
|
||||
|
||||
def test_a_docx_compressed_the_way_word_never_does_is_unreadable():
|
||||
out = io.BytesIO()
|
||||
with zipfile.ZipFile(out, "w") as z:
|
||||
z.writestr("word/document.xml", "<w:document/>", compress_type=zipfile.ZIP_BZIP2)
|
||||
cut = cutting.cut(out.getvalue(), "umowa.docx")
|
||||
assert (cut.failed, cut.reason) == (True, cutting.UNREADABLE)
|
||||
|
||||
|
||||
def test_text_past_the_bound_fails_its_row(monkeypatch):
|
||||
monkeypatch.setattr(cutting, "MAX_TEXT_CHARS", 50)
|
||||
cut = cutting.cut(PARAGRAPHS.encode("utf-8"), "umowa.txt")
|
||||
assert (cut.failed, cut.reason, cut.clauses) == (True, cutting.TOO_LARGE, [])
|
||||
|
||||
|
||||
def test_more_clauses_than_the_bound_fail_the_row(monkeypatch):
|
||||
monkeypatch.setattr(cutting, "MAX_CLAUSES", 3)
|
||||
cut = cutting.cut(PARAGRAPHS.encode("utf-8"), "umowa.txt")
|
||||
assert (cut.failed, cut.reason, cut.clauses) == (True, cutting.TOO_MANY, [])
|
||||
|
||||
|
||||
def test_the_routes_that_cut_an_upload_do_not_run_on_the_event_loop():
|
||||
"""The cut is CPU-bound and runs in the request; an `async def` route would run it on the
|
||||
event loop and stall every other request of the worker."""
|
||||
import inspect
|
||||
|
||||
from app.routers import sources as routes
|
||||
|
||||
assert not inspect.iscoroutinefunction(routes.upload)
|
||||
assert not inspect.iscoroutinefunction(routes.new_file)
|
||||
|
||||
|
||||
def test_only_the_cuttable_formats_are_accepted():
|
||||
assert cutting.can_cut("A.PDF") and cutting.can_cut("b.docx") and cutting.can_cut("c.txt")
|
||||
assert not cutting.can_cut("d.doc") and not cutting.can_cut("noext")
|
||||
|
||||
Reference in New Issue
Block a user