diff --git a/app/infrastructure/file_store.py b/app/infrastructure/file_store.py
new file mode 100644
index 0000000..644e809
--- /dev/null
+++ b/app/infrastructure/file_store.py
@@ -0,0 +1,70 @@
+"""Local immutable originals; filenames never participate in storage paths."""
+import os
+from pathlib import Path
+import re
+import tempfile
+from uuid import uuid4
+
+
+class LocalFileStore:
+ def __init__(self, directory: Path):
+ self.directory = Path(directory).resolve()
+
+ def _path(self, key: str) -> Path:
+ if not re.fullmatch(r"[0-9a-f]{32}\.original", key):
+ raise ValueError("Invalid storage key")
+ path = self.directory / key
+ if path.is_symlink():
+ raise ValueError("Storage entries cannot be symlinks")
+ return path
+
+ def put(self, content: bytes) -> str:
+ self.directory.mkdir(parents=True, exist_ok=True)
+ key = uuid4().hex + ".original"
+ final = self._path(key)
+ descriptor, temporary = tempfile.mkstemp(prefix=".intake-", dir=self.directory)
+ try:
+ with os.fdopen(descriptor, "wb") as stream:
+ stream.write(content)
+ stream.flush()
+ os.fsync(stream.fileno())
+ # Atomic no-replace publication on the same filesystem (including NTFS).
+ os.link(temporary, final)
+ finally:
+ Path(temporary).unlink(missing_ok=True)
+ if os.name != "nt":
+ descriptor = os.open(self.directory, os.O_RDONLY)
+ try:
+ os.fsync(descriptor)
+ finally:
+ os.close(descriptor)
+ return key
+
+ def read(self, storage_key: str) -> bytes:
+ return self._path(storage_key).read_bytes()
+
+ def read_bounded(self, storage_key: str, limit: int) -> bytes:
+ with self._path(storage_key).open("rb") as stream:
+ content = stream.read(limit + 1)
+ if len(content) > limit:
+ raise ValueError("Original exceeds frozen byte limit")
+ return content
+
+ def discard_unused(self, storage_key: str) -> None:
+ """Only for this request's candidate after a confirmed committed replay."""
+ self._path(storage_key).unlink(missing_ok=True)
+
+ def inventory(self) -> dict:
+ if not self.directory.exists():
+ return {"originals": [], "temporary_files": [], "unexpected_entries": []}
+ result = {"originals": [], "temporary_files": [], "unexpected_entries": []}
+ for path in self.directory.iterdir():
+ if path.is_file() and not path.is_symlink():
+ if re.fullmatch(r"[0-9a-f]{32}\.original", path.name):
+ result["originals"].append(path.name)
+ continue
+ if path.name.startswith(".intake-"):
+ result["temporary_files"].append(path.name)
+ continue
+ result["unexpected_entries"].append(path.name)
+ return {name: sorted(values) for name, values in result.items()}
diff --git a/app/infrastructure/intake_repository.py b/app/infrastructure/intake_repository.py
new file mode 100644
index 0000000..82f8b08
--- /dev/null
+++ b/app/infrastructure/intake_repository.py
@@ -0,0 +1,117 @@
+"""Intake-specific transactional PostgreSQL boundary. No file or provider I/O."""
+import json
+from uuid import uuid4
+from sqlalchemy import text
+from app.infrastructure.database import check_compatibility
+from app.modules.documents.errors import IntakeError
+
+def administrator(connection, user_id):
+ row = connection.execute(text("""
+ SELECT organization_id FROM users
+ WHERE id=:id AND role='admin' AND is_enabled FOR SHARE
+ """), {"id": user_id}).mappings().one_or_none()
+ if row is None:
+ raise IntakeError("ADMINISTRATOR_REQUIRED", "Enabled administrator required")
+ return row["organization_id"]
+
+
+def document_status(connection, organization_id, document_id):
+ row = connection.execute(text("""
+ SELECT d.*, row_to_json(j) AS job FROM documents d
+ JOIN ingestion_jobs j ON j.document_id=d.id AND j.organization_id=d.organization_id
+ WHERE d.organization_id=:org AND d.id=:id
+ """), {"org": organization_id, "id": document_id}).mappings().one_or_none()
+ if row is None:
+ raise IntakeError("DOCUMENT_NOT_FOUND", "Document not found")
+ result = dict(row)
+ result["searchable"] = (result["status"] == "ready" and result["is_active"]
+ and result["deleted_at"] is None
+ and result["content_purged_at"] is None)
+ return result
+
+
+class SqlIntakeRepository:
+ def __init__(self, engine):
+ self.engine = engine
+
+ def lookup(self, settings, administrator_id, request_id):
+ with self.engine.begin() as connection:
+ check_compatibility(connection, settings.embedding_profile)
+ org = administrator(connection, administrator_id)
+ previous = connection.execute(text("""
+ SELECT id,size_bytes,upload_payload_hash FROM documents
+ WHERE organization_id=:org AND upload_request_id=:request
+ """), {"org": org, "request": request_id}).mappings().one_or_none()
+ return org, previous
+
+ def replay(self, org, administrator_id, previous, submitted_hash):
+ with self.engine.begin() as connection:
+ if administrator(connection, administrator_id) != org:
+ raise IntakeError("DOCUMENT_NOT_FOUND", "Document not found")
+ if submitted_hash != previous["upload_payload_hash"]:
+ raise IntakeError("IDEMPOTENCY_CONFLICT", "Key already used with a different payload")
+ result = document_status(connection, org, previous["id"])
+ return result
+
+ def create(self, settings, prepared, key, administrator_id, request_id, expected_org):
+ document_id, job_id = uuid4(), uuid4()
+ # Any exception (including ambiguous commit) retains the candidate as an orphan.
+ # Never risk deleting bytes referenced by a possibly committed document.
+ with self.engine.begin() as connection:
+ org = administrator(connection, administrator_id)
+ if org != expected_org:
+ raise IntakeError("DOCUMENT_NOT_FOUND", "Document not found")
+ inserted = connection.execute(text("""
+ INSERT INTO documents
+ (id,organization_id,uploaded_by,title,original_filename,upload_request_id,
+ upload_payload_hash,storage_key,file_sha256,mime_type,size_bytes,processing_profile)
+ VALUES (:id,:org,:actor,:title,:filename,:request,:hash,:key,:sha,:mime,:size,
+ CAST(:profile AS jsonb))
+ ON CONFLICT (organization_id,upload_request_id) DO NOTHING RETURNING id
+ """), {"id": document_id, "org": org, "actor": administrator_id,
+ "title": prepared["title"], "filename": prepared["filename"],
+ "request": request_id, "hash": prepared["payload_hash"], "key": key,
+ "sha": prepared["sha"], "mime": prepared["mime"],
+ "size": len(prepared["content"]),
+ "profile": json.dumps(settings.processing_profile())}).scalar_one_or_none()
+ replayed = inserted is None
+ if replayed:
+ previous = connection.execute(text("""
+ SELECT id,upload_payload_hash FROM documents
+ WHERE organization_id=:org AND upload_request_id=:request
+ """), {"org": org, "request": request_id}).mappings().one()
+ if previous["upload_payload_hash"] != prepared["payload_hash"]:
+ conflict = True
+ result = None
+ else:
+ conflict = False
+ result = document_status(connection, org, previous["id"])
+ else:
+ conflict = False
+ connection.execute(text("""
+ INSERT INTO ingestion_jobs(id,organization_id,document_id)
+ VALUES (:id,:org,:document)
+ """), {"id": job_id, "org": org, "document": document_id})
+ connection.execute(text("""
+ INSERT INTO audit_events
+ (id,organization_id,actor_user_id,action,target_id,idempotency_key,
+ request_hash,response_json)
+ VALUES (:id,:org,:actor,'upload',:document,:request,:hash,CAST(:response AS jsonb))
+ """), {"id": uuid4(), "org": org, "actor": administrator_id,
+ "document": document_id, "request": request_id,
+ "hash": prepared["payload_hash"],
+ "response": json.dumps({"document_id": str(document_id), "job_id": str(job_id)})})
+ result = document_status(connection, org, document_id)
+ return replayed, conflict, result
+
+ def status(self, administrator_id, document_id):
+ with self.engine.begin() as connection:
+ org = administrator(connection, administrator_id)
+ return document_status(connection, org, document_id)
+
+ def original_references(self):
+ with self.engine.connect() as connection:
+ rows = connection.execute(text("""
+ SELECT id,storage_key FROM documents WHERE content_purged_at IS NULL
+ """)).mappings().all()
+ return rows
diff --git a/app/modules/documents/errors.py b/app/modules/documents/errors.py
new file mode 100644
index 0000000..25704a8
--- /dev/null
+++ b/app/modules/documents/errors.py
@@ -0,0 +1,5 @@
+"""Safe ingestion domain errors shared across application and persistence."""
+class IntakeError(ValueError):
+ def __init__(self, code, message):
+ super().__init__(message)
+ self.code = code
diff --git a/app/modules/documents/formats.py b/app/modules/documents/formats.py
new file mode 100644
index 0000000..ba51695
--- /dev/null
+++ b/app/modules/documents/formats.py
@@ -0,0 +1,248 @@
+"""Bounded intake identification, not extraction or evidence quality acceptance."""
+from io import BytesIO
+from pathlib import PurePosixPath
+import re
+import stat
+import struct
+import unicodedata
+import warnings
+import zlib
+from zipfile import ZipFile, BadZipFile, ZIP_STORED, ZIP_DEFLATED
+
+from .errors import IntakeError
+
+DOCX_MIME = "application/vnd.openxmlformats-officedocument.wordprocessingml.document"
+CONTENT_NS = "http://schemas.openxmlformats.org/package/2006/content-types"
+REL_NS = "http://schemas.openxmlformats.org/package/2006/relationships"
+WORD_NAMESPACES = ("http://schemas.openxmlformats.org/wordprocessingml/2006/main",
+ "http://purl.oclc.org/ooxml/wordprocessingml/main")
+MAIN_TYPE = "application/vnd.openxmlformats-officedocument.wordprocessingml.document.main+xml"
+
+
+def _zip_payload_bounds(content, member, member_end):
+ """Derive the physical member span from adjacent local headers, not file_size."""
+ offset = member.header_offset
+ if offset < 0 or offset + 30 > member_end:
+ raise ValueError("Invalid archive local header")
+ signature, version, flags, method, _, _, crc, compressed, expanded, name_length, extra_length = struct.unpack_from(
+ "<4s5H3L2H", content, offset)
+ if (signature != b"PK\x03\x04" or version >= 45 or flags != member.flag_bits
+ or flags & ~0x080e or method != member.compress_type):
+ raise ValueError("Unsupported archive local header")
+ data_start = offset + 30 + name_length + extra_length
+ if data_start > member_end:
+ raise ValueError("Invalid archive local header length")
+ encoding = "utf-8" if flags & 0x800 else "cp437"
+ if content[offset + 30:offset + 30 + name_length].decode(encoding) != member.orig_filename:
+ raise ValueError("Local and central archive names differ")
+ # Refuse ZIP64 fields even when small values would otherwise hide their use.
+ cursor = offset + 30 + name_length
+ while cursor < data_start:
+ if cursor + 4 > data_start:
+ raise ValueError("Invalid archive extra field")
+ kind, length = struct.unpack_from("<2H", content, cursor)
+ cursor += 4 + length
+ if kind == 1 or cursor > data_start:
+ raise ValueError("Unsupported archive extra field")
+ expected = (member.CRC, member.compress_size, member.file_size)
+ if flags & 8:
+ # ZIP32 data descriptors may be signed (16 bytes) or unsigned (12).
+ # Require the descriptor to occupy the entire physical trailing span.
+ if any(value not in (0, wanted) for value, wanted in zip((crc, compressed, expanded), expected)):
+ raise ValueError("Local and central archive metadata differ")
+ for length in (16, 12):
+ data_end = member_end - length
+ if data_end < data_start or data_end - data_start != member.compress_size:
+ continue
+ descriptor = content[data_end:member_end]
+ if length == 16:
+ if descriptor[:4] != b"PK\x07\x08":
+ continue
+ descriptor = descriptor[4:]
+ if struct.unpack("<3L", descriptor) == expected:
+ return data_start, data_end
+ raise ValueError("Invalid archive data descriptor")
+ if (crc, compressed, expanded) != expected or member_end - data_start != member.compress_size:
+ raise ValueError("Invalid archive physical member boundary")
+ return data_start, member_end
+
+
+def _read_zip_member(content, member, member_end, settings, remaining_bytes, *, retain):
+ """Bound actual expansion; never use ZipExtFile's declared-size truncation."""
+ start, end = _zip_payload_bounds(content, member, member_end)
+ compressed_length = end - start
+ budget = min(settings.max_docx_member_bytes, remaining_bytes,
+ compressed_length * settings.max_docx_compression_ratio)
+ expanded, crc, retained = 0, 0, bytearray()
+
+ def consume(block):
+ nonlocal expanded, crc
+ expanded += len(block)
+ if expanded > budget:
+ raise ValueError("Archive actual expansion budget exceeded")
+ crc = zlib.crc32(block, crc)
+ if retain:
+ retained.extend(block)
+
+ position = start
+ if member.compress_type == ZIP_STORED:
+ while position < end:
+ stop = min(end, position + 65536, position + budget - expanded + 1)
+ consume(content[position:stop])
+ position = stop
+ else:
+ decoder = zlib.decompressobj(-15)
+ pending = b""
+ while not decoder.eof:
+ if not pending and position < end:
+ stop = min(end, position + 65536)
+ pending = content[position:stop]
+ position = stop
+ # One extra output byte detects overflow promptly, even if both
+ # headers and a descriptor claim a short prefix with its valid CRC.
+ block = decoder.decompress(pending, min(65536, budget - expanded + 1))
+ consume(block)
+ pending = decoder.unconsumed_tail
+ if decoder.eof:
+ if decoder.unused_data or pending or position != end:
+ raise ValueError("Archive compressed stream has trailing bytes")
+ elif not block and not pending and position == end:
+ raise ValueError("Incomplete archive compressed stream")
+ # No flush(): its argument is an allocation hint, not an output bound.
+ if expanded != member.file_size or crc != member.CRC:
+ raise ValueError("Archive full-stream length or CRC mismatch")
+ return expanded, bytes(retained)
+
+
+def validate_docx(content, settings):
+ from defusedxml.ElementTree import fromstring
+ # Reject ZIP64/multidisk and bound entry count before ZipFile builds its inventory.
+ offset = content.rfind(b"PK\x05\x06", max(0, len(content) - 65557))
+ if not content.startswith(b"PK\x03\x04") or offset < 0 or offset + 22 > len(content):
+ raise ValueError("Missing archive directory")
+ _, disk, directory_disk, disk_count, count, size, start, comment = struct.unpack_from(
+ "<4s4H2LH", content, offset)
+ if (disk or directory_disk or disk_count != count or count == 65535
+ or count > settings.max_docx_entries or start + size != offset
+ or offset + 22 + comment != len(content)):
+ raise ValueError("Unsupported or oversized archive directory")
+ # The EOCD count is untrusted. Walk raw central headers first so a forged
+ # small count cannot cause ZipFile to allocate an unbounded member list.
+ cursor = start
+ for _ in range(count):
+ if cursor + 46 > offset or content[cursor:cursor + 4] != b"PK\x01\x02":
+ raise ValueError("Invalid archive directory entry")
+ name_length, extra_length, comment_length, member_disk = struct.unpack_from("<4H", content, cursor + 28)
+ compressed, expanded = struct.unpack_from("<2L", content, cursor + 20)
+ if (name_length > 1024 or member_disk or compressed == 0xffffffff or expanded == 0xffffffff):
+ raise ValueError("Unsupported archive directory entry")
+ cursor += 46 + name_length + extra_length + comment_length
+ if cursor > offset:
+ raise ValueError("Invalid archive directory length")
+ if cursor != offset:
+ raise ValueError("Archive directory count mismatch")
+ required = {"[Content_Types].xml", "_rels/.rels", "word/document.xml"}
+ xml = {}
+ with ZipFile(BytesIO(content)) as archive:
+ members = archive.infolist()
+ if len(members) != count:
+ raise ValueError("Invalid archive inventory")
+ ordered = sorted(members, key=lambda member: member.header_offset)
+ offsets = [member.header_offset for member in ordered]
+ if not offsets or offsets[0] != 0 or len(set(offsets)) != len(offsets):
+ raise ValueError("Invalid archive member offsets")
+ names, total = set(), 0
+ for index, member in enumerate(ordered):
+ name = member.filename
+ if (name in names or member.orig_filename != name or len(name) > 1024
+ or name.startswith("/") or "\\" in name or ":" in name
+ or ".." in PurePosixPath(name).parts
+ or stat.S_ISLNK(member.external_attr >> 16)
+ or member.flag_bits & ~0x080e or member.compress_type not in (ZIP_STORED, ZIP_DEFLATED)):
+ raise ValueError("Unsupported archive member")
+ names.add(name)
+ member_end = offsets[index + 1] if index + 1 < len(offsets) else start
+ if not member.header_offset < member_end <= start:
+ raise ValueError("Invalid archive member physical span")
+ actual_length, value = _read_zip_member(
+ content, member, member_end, settings,
+ settings.max_docx_expanded_bytes - total, retain=name in required)
+ total += actual_length
+ if name in required:
+ xml[name] = fromstring(value, forbid_dtd=True, forbid_entities=True, forbid_external=True)
+ if not required <= xml.keys():
+ raise ValueError("Missing DOCX package structure")
+ types = xml["[Content_Types].xml"]
+ relationships = xml["_rels/.rels"]
+ document = xml["word/document.xml"]
+ if (types.tag != "{" + CONTENT_NS + "}Types"
+ or not any(e.get("PartName") == "/word/document.xml" and e.get("ContentType") == MAIN_TYPE
+ for e in types.findall("{" + CONTENT_NS + "}Override"))
+ or relationships.tag != "{" + REL_NS + "}Relationships"
+ or not any(e.get("Type") in (
+ "http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument",
+ "http://purl.oclc.org/ooxml/officeDocument/relationships/officeDocument")
+ and e.get("Target") in ("word/document.xml", "/word/document.xml")
+ and e.get("TargetMode", "Internal") == "Internal"
+ for e in relationships.findall("{" + REL_NS + "}Relationship"))
+ or not any(document.tag == "{" + ns + "}document" and document.find("{" + ns + "}body") is not None
+ for ns in WORD_NAMESPACES)):
+ raise ValueError("Invalid DOCX package structure")
+
+ return document
+
+def validate_image(extension, content, settings):
+ from PIL import Image
+ expected = "PNG" if extension == ".png" else "JPEG"
+ with warnings.catch_warnings():
+ warnings.simplefilter("error", Image.DecompressionBombWarning)
+ with Image.open(BytesIO(content), formats=[expected]) as image:
+ width, height = image.size
+ if (width <= 0 or height <= 0 or width > settings.max_image_width
+ or height > settings.max_image_height or width * height > settings.max_image_pixels
+ or getattr(image, "n_frames", 1) != 1):
+ raise ValueError("Image resource limit exceeded")
+ image.verify()
+ # JPEG verify alone does not decode pixels; validate bounded decode too.
+ with Image.open(BytesIO(content), formats=[expected]) as image:
+ image.load()
+ return "image/png" if expected == "PNG" else "image/jpeg"
+
+
+def validate_format(extension, content, settings):
+ if extension == ".pdf":
+ if not re.match(rb"%PDF-[12]\.[0-9](?:\r|\n|\s)", content):
+ raise IntakeError("INVALID_FILE", "PDF signature does not match the file type")
+ return "application/pdf"
+ if extension == ".md":
+ try:
+ decoded = content.decode("utf-8-sig")
+ except UnicodeDecodeError:
+ raise IntakeError("INVALID_FILE", "Markdown must be UTF-8 text") from None
+ if (decoded.lstrip().startswith("%PDF-")
+ or any(unicodedata.category(c) == "Cc" and c not in "\t\r\n" for c in decoded)):
+ raise IntakeError("INVALID_FILE", "Content does not match Markdown text")
+ return "text/markdown"
+ if extension == ".docx":
+ from defusedxml.common import DefusedXmlException
+ valid = False
+ try:
+ validate_docx(content, settings)
+ valid = True
+ except (ValueError, OSError, BadZipFile, RuntimeError, NotImplementedError,
+ SyntaxError, DefusedXmlException, EOFError, zlib.error, struct.error):
+ pass
+ if not valid:
+ raise IntakeError("INVALID_FILE", "Invalid DOCX package or configured archive limit exceeded")
+ return DOCX_MIME
+ if extension in (".jpg", ".jpeg", ".png"):
+ from PIL import Image
+ valid_mime = None
+ try:
+ valid_mime = validate_image(extension, content, settings)
+ except (ValueError, OSError, SyntaxError, Image.DecompressionBombError, Image.DecompressionBombWarning):
+ pass
+ if valid_mime is None:
+ raise IntakeError("INVALID_FILE", "Invalid image or configured image limit exceeded")
+ return valid_mime
+ raise IntakeError("UNSUPPORTED_FILE_TYPE", "Unsupported file format")
diff --git a/app/modules/documents/intake.py b/app/modules/documents/intake.py
new file mode 100644
index 0000000..62c0dc4
--- /dev/null
+++ b/app/modules/documents/intake.py
@@ -0,0 +1,138 @@
+"""Trusted local intake: short database transactions, no provider initialization."""
+import hashlib
+import json
+import logging
+import os
+import stat
+from pathlib import Path
+import re
+import unicodedata
+from uuid import UUID
+
+from .errors import IntakeError
+from .ports import FileStore, IntakeRepository
+
+
+logger = logging.getLogger(__name__)
+
+
+def unsafe_display_character(character: str) -> bool:
+ return (unicodedata.category(character) in {"Cc", "Cs"}
+ or unicodedata.bidirectional(character) in
+ {"RLO", "LRO", "RLE", "LRE", "PDF", "LRI", "RLI", "FSI", "PDI"})
+
+
+def normalized_title(path: Path, title: str | None) -> str:
+ filename = unicodedata.normalize("NFC", Path(path).name)
+ value = unicodedata.normalize("NFC", title if title is not None else Path(filename).stem)
+ return " ".join(value.split())
+
+
+def payload_hash(sha: str, title: str) -> str:
+ payload = json.dumps({"file_sha256": sha, "title": title},
+ ensure_ascii=False, sort_keys=True, separators=(",", ":"))
+ return hashlib.sha256(payload.encode("utf-8")).hexdigest()
+
+
+def replay_payload_hash(path: Path, title: str | None, size_bytes: int) -> str:
+ """Stream at most the accepted length plus one byte, with constant memory."""
+ path = Path(path)
+ digest, total = hashlib.sha256(), 0
+ try:
+ if not path.is_file():
+ raise IntakeError("INVALID_FILE", "Input must be a regular file")
+ with path.open("rb") as stream:
+ if not stat.S_ISREG(os.fstat(stream.fileno()).st_mode):
+ raise IntakeError("INVALID_FILE", "Input must be a regular file")
+ while total <= size_bytes:
+ block = stream.read(min(65536, size_bytes + 1 - total))
+ if not block:
+ break
+ total += len(block)
+ digest.update(block)
+ except OSError:
+ raise IntakeError("INVALID_FILE", "Cannot read input file") from None
+ if total != size_bytes:
+ raise IntakeError("IDEMPOTENCY_CONFLICT", "Key already used with a different payload")
+ return payload_hash(digest.hexdigest(), normalized_title(path, title))
+
+
+def prepare_file(path: Path, title: str | None, settings) -> dict:
+ path = Path(path)
+ filename = unicodedata.normalize("NFC", path.name)
+ # Display names are portable and reject path delimiters, controls and bidi marks.
+ if (not filename or len(filename) > 255 or filename.rstrip(" .") != filename
+ or any(c in '<>:"/\\|?*' or unsafe_display_character(c)
+ for c in filename)
+ or re.fullmatch(r"(?i)(con|prn|aux|nul|com[1-9]|lpt[1-9])(?:\..*)?", filename)):
+ raise IntakeError("INVALID_FILE", "Unsafe display filename")
+ extension = Path(filename).suffix.lower()
+ if extension not in settings.accepted_formats:
+ raise IntakeError("UNSUPPORTED_FILE_TYPE", "Unsupported file format")
+ canonical_title = normalized_title(path, title)
+ if (not canonical_title or len(canonical_title) > 200
+ or any(unsafe_display_character(c) for c in canonical_title)):
+ raise IntakeError("INVALID_FILE", "Title must contain 1-200 display characters")
+ try:
+ if not path.is_file():
+ raise IntakeError("INVALID_FILE", "Input must be a regular file")
+ with path.open("rb") as stream:
+ if not stat.S_ISREG(os.fstat(stream.fileno()).st_mode):
+ raise IntakeError("INVALID_FILE", "Input must be a regular file")
+ content = stream.read(settings.max_original_bytes + 1)
+ except OSError:
+ raise IntakeError("INVALID_FILE", "Cannot read input file") from None
+ if len(content) > settings.max_original_bytes:
+ raise IntakeError("FILE_TOO_LARGE", "Original exceeds the configured size limit")
+ if not content:
+ raise IntakeError("INVALID_FILE", "Original cannot be empty")
+ from .formats import validate_format
+ mime = validate_format(extension, content, settings)
+ sha = hashlib.sha256(content).hexdigest()
+ # Filename is display metadata; the replay contract covers bytes and normalized title.
+ return {"content": content, "filename": filename, "title": canonical_title,
+ "sha": sha, "payload_hash": payload_hash(sha, canonical_title),
+ "mime": mime}
+
+
+def import_document(repository: IntakeRepository, store: FileStore, settings, *, path,
+ administrator_id, request_id, title=None):
+ administrator_id, request_id = UUID(str(administrator_id)), UUID(str(request_id))
+ org, previous = repository.lookup(settings, administrator_id, request_id)
+ if previous is not None:
+ # Existing requests compare payloads independently of current acceptance policy.
+ # File I/O is outside database transactions and creates no candidate.
+ submitted_hash = replay_payload_hash(path, title, previous["size_bytes"])
+ result = repository.replay(org, administrator_id, previous, submitted_hash)
+ return {"replayed": True, "document": result}
+ prepared = prepare_file(path, title, settings)
+ key = store.put(prepared["content"])
+ replayed, conflict, result = repository.create(
+ settings, prepared, key, administrator_id, request_id, org)
+ if replayed:
+ try:
+ store.discard_unused(key)
+ except Exception:
+ # Confirmed unused candidate only. Never clean uncertain commits.
+ logger.warning("Unused intake candidate retained; run report-only reconciliation.")
+ if conflict:
+ raise IntakeError("IDEMPOTENCY_CONFLICT", "Key already used with a different payload")
+ return {"replayed": replayed, "document": result}
+
+
+def status(repository: IntakeRepository, *, administrator_id, document_id):
+ return repository.status(UUID(str(administrator_id)), UUID(str(document_id)))
+
+
+def reconcile(repository: IntakeRepository, store: FileStore):
+ # Global report for a trusted operator. No deletion or content mutation.
+ rows = repository.original_references()
+ inventory = store.inventory()
+ present = set(inventory["originals"])
+ referenced = {row["storage_key"] for row in rows}
+ return {"orphan_files": sorted(present - referenced),
+ "missing_originals": [{"document_id": str(row["id"]), "storage_key": row["storage_key"]}
+ for row in rows if row["storage_key"] not in present],
+ "temporary_files": inventory["temporary_files"],
+ "unexpected_entries": inventory["unexpected_entries"],
+ "report_only": True}
diff --git a/data/documents/-2348240626507047168_13449360743721.docx b/data/documents/-2348240626507047168_13449360743721.docx
new file mode 100644
index 0000000..734b613
Binary files /dev/null and b/data/documents/-2348240626507047168_13449360743721.docx differ
diff --git a/data/documents/5905170444656189186_13450510740952.pdf b/data/documents/5905170444656189186_13450510740952.pdf
new file mode 100644
index 0000000..b28d199
Binary files /dev/null and b/data/documents/5905170444656189186_13450510740952.pdf differ
diff --git a/data/documents/7364346504113364738_13450847753183.pdf b/data/documents/7364346504113364738_13450847753183.pdf
new file mode 100644
index 0000000..74433ba
Binary files /dev/null and b/data/documents/7364346504113364738_13450847753183.pdf differ
diff --git a/data/documents/photo_1_2026-10-06_09-05-11.jpg b/data/documents/photo_1_2026-10-06_09-05-11.jpg
new file mode 100644
index 0000000..381625b
Binary files /dev/null and b/data/documents/photo_1_2026-10-06_09-05-11.jpg differ
diff --git a/tests/integration/test_intake.py b/tests/integration/test_intake.py
new file mode 100644
index 0000000..319bc77
--- /dev/null
+++ b/tests/integration/test_intake.py
@@ -0,0 +1,489 @@
+"""Local intake acceptance against isolated PostgreSQL/pgvector."""
+from concurrent.futures import ThreadPoolExecutor
+from threading import Barrier
+from uuid import uuid4
+
+import pytest
+from sqlalchemy import text
+from sqlalchemy.exc import IntegrityError
+
+from app.infrastructure.file_store import LocalFileStore
+from app.infrastructure.intake_repository import SqlIntakeRepository
+from app.modules.documents.intake import IntakeError, import_document, reconcile, status
+from tests.support.formats import format_bytes, raw_docx
+
+
+@pytest.fixture
+def intake(migrated_db, settings, tmp_path):
+ engine, _ = migrated_db
+ org, actor = uuid4(), uuid4()
+ with engine.begin() as connection:
+ connection.execute(text("INSERT INTO organizations(id,name) VALUES (:id,'intake')"), {"id": org})
+ connection.execute(text("""
+ INSERT INTO users(id,organization_id,username,password_hash,role)
+ VALUES (:id,:org,:name,'test-only','admin')
+ """), {"id": actor, "org": org, "name": str(actor)})
+ path = tmp_path / "source.md"
+ path.write_bytes("# Intake\nOriginal bytes\n".encode())
+ store = LocalFileStore(tmp_path / "originals")
+ def run(request=None, **kwargs):
+ return import_document(SqlIntakeRepository(engine), store, settings, path=kwargs.pop("path", path),
+ administrator_id=kwargs.pop("administrator_id", actor),
+ request_id=request or uuid4(), **kwargs)
+ return engine, settings, store, path, org, actor, run
+
+
+def counts(engine):
+ with engine.connect() as connection:
+ return tuple(connection.execute(text("SELECT count(*) FROM " + table)).scalar_one()
+ for table in ("documents", "ingestion_jobs", "audit_events", "document_chunks"))
+
+
+def test_durable_intake_replay_independent_documents_and_profile(intake):
+ engine, settings, store, path, org, actor, run = intake
+ request = uuid4()
+ first = run(request, title=" A title ")
+ doc = first["document"]
+ assert first["replayed"] is False
+ assert doc["organization_id"] == org and doc["uploaded_by"] == actor
+ assert doc["status"] == doc["job"]["status"] == "queued"
+ assert doc["is_active"] is False and doc["chunk_count"] == 0 and not doc["searchable"]
+ assert doc["processing_profile"] == settings.processing_profile()
+ assert LocalFileStore(store.directory).read(doc["storage_key"]) == path.read_bytes()
+ # Dispose all pooled connections to simulate application restart.
+ engine.dispose()
+ renamed = path.with_name("renamed.md")
+ renamed.write_bytes(path.read_bytes())
+ second = run(request, title="A title", path=renamed)
+ assert second["replayed"] is True
+ assert second["document"]["id"] == doc["id"]
+ assert second["document"]["job"]["id"] == doc["job"]["id"]
+ assert second["document"]["original_filename"] == "source.md"
+ third = run(title="A title")
+ assert third["document"]["id"] != doc["id"]
+ assert third["document"]["storage_key"] != doc["storage_key"]
+ assert counts(engine) == (2, 2, 2, 0)
+ assert status(SqlIntakeRepository(engine), administrator_id=actor, document_id=doc["id"])["job"]["id"] == doc["job"]["id"]
+ assert reconcile(SqlIntakeRepository(engine), store)["orphan_files"] == []
+ assert store.inventory()["temporary_files"] == []
+
+
+@pytest.mark.parametrize("change", ["bytes", "title"])
+def test_payload_conflict(intake, change):
+ engine, _, store, path, _, _, run = intake
+ request = uuid4()
+ original = run(request)
+ if change == "bytes":
+ path.write_bytes(b"Changed bytes")
+ with pytest.raises(IntakeError) as error:
+ run(request, **({"title": "Changed title"} if change == "title" else {}))
+ assert error.value.code == "IDEMPOTENCY_CONFLICT"
+ assert counts(engine) == (1, 1, 1, 0)
+ assert store.read(original["document"]["storage_key"]) == b"# Intake\nOriginal bytes\n"
+ assert len(store.inventory()["originals"]) == 1
+
+
+@pytest.mark.parametrize("extension", [".md", ".docx", ".jpg", ".png"])
+@pytest.mark.parametrize("changed", [False, True])
+def test_concurrent_replay_and_conflict(intake, changed, extension):
+ engine, settings, store, path, _, actor, _ = intake
+ if extension != ".md":
+ path = path.with_suffix(extension)
+ path.write_bytes(format_bytes(extension))
+ barrier, request = Barrier(4), uuid4()
+ class RacingStore(LocalFileStore):
+ def put(self, content):
+ key = super().put(content)
+ barrier.wait(timeout=15)
+ return key
+ racing = RacingStore(store.directory)
+ def run(index):
+ try:
+ return import_document(SqlIntakeRepository(engine), racing, settings, path=path, administrator_id=actor,
+ request_id=request, title=str(index) if changed else "same")
+ except IntakeError as error:
+ return error.code
+ with ThreadPoolExecutor(max_workers=4) as pool:
+ results = list(pool.map(run, range(4)))
+ successes = [result for result in results if isinstance(result, dict)]
+ assert len(successes) == (1 if changed else 4)
+ assert sum(not result["replayed"] for result in successes) == 1
+ assert len({result["document"]["id"] for result in successes}) == 1
+ assert len({result["document"]["job"]["id"] for result in successes}) == 1
+ if changed:
+ assert results.count("IDEMPOTENCY_CONFLICT") == 3
+ assert counts(engine) == (1, 1, 1, 0)
+ assert len(store.inventory()["originals"]) == 1
+ assert store.inventory()["temporary_files"] == []
+
+
+@pytest.mark.parametrize("extension", [".md", ".docx", ".jpg", ".png"])
+@pytest.mark.parametrize("failure_at", ["job", "audit"])
+def test_database_rollback_never_acknowledges_and_reconciliation_reports(intake, failure_at, extension):
+ engine, _, store, path, _, _, run = intake
+ if extension != ".md":
+ path = path.with_suffix(extension)
+ path.write_bytes(format_bytes(extension))
+ with engine.begin() as connection:
+ table = "ingestion_jobs" if failure_at == "job" else "audit_events"
+ connection.execute(text(f"ALTER TABLE {table} ADD CONSTRAINT reject_intake CHECK (false)"))
+ with pytest.raises(IntegrityError):
+ run(path=path)
+ assert counts(engine) == (0, 0, 0, 0)
+ inventory = store.inventory()
+ report = reconcile(SqlIntakeRepository(engine), store)
+ assert report["orphan_files"] == inventory["originals"] and len(report["orphan_files"]) == 1
+ assert report["report_only"] and report["missing_originals"] == []
+ assert store.inventory() == inventory
+ assert inventory["temporary_files"] == []
+
+
+def test_missing_original_temporary_and_unexpected_entries_report_only(intake):
+ engine, _, store, _, _, _, run = intake
+ doc = run()["document"]
+ # Simulated external loss, not a product purge operation.
+ (store.directory / doc["storage_key"]).unlink()
+ (store.directory / ".intake-abandoned").write_bytes(b"partial")
+ (store.directory / "unexpected").write_bytes(b"unknown")
+ before = store.inventory()
+ report = reconcile(SqlIntakeRepository(engine), store)
+ assert report["missing_originals"] == [{"document_id": str(doc["id"]), "storage_key": doc["storage_key"]}]
+ assert report["temporary_files"] == [".intake-abandoned"]
+ assert report["unexpected_entries"] == ["unexpected"]
+ assert store.inventory() == before
+ assert counts(engine) == (1, 1, 1, 0)
+
+
+@pytest.mark.parametrize("identity", ["disabled", "user", "unknown"])
+def test_administrator_required_before_storage(intake, identity):
+ engine, _, store, _, _, actor, run = intake
+ if identity == "unknown":
+ actor = uuid4()
+ else:
+ with engine.begin() as connection:
+ connection.execute(text("UPDATE users SET is_enabled=:enabled,role=:role WHERE id=:id"),
+ {"enabled": identity != "disabled",
+ "role": "user" if identity == "user" else "admin", "id": actor})
+ with pytest.raises(IntakeError) as error:
+ run(administrator_id=actor)
+ assert error.value.code == "ADMINISTRATOR_REQUIRED"
+ assert counts(engine) == (0, 0, 0, 0) and store.inventory()["originals"] == []
+
+
+def test_administrator_rechecked_after_file_write(intake):
+ engine, _, store, _, _, actor, run = intake
+ original_put = store.put
+ def disable(content):
+ key = original_put(content)
+ with engine.begin() as connection:
+ connection.execute(text("UPDATE users SET is_enabled=false WHERE id=:id"), {"id": actor})
+ return key
+ store.put = disable
+ with pytest.raises(IntakeError):
+ run()
+ assert counts(engine) == (0, 0, 0, 0)
+ assert len(reconcile(SqlIntakeRepository(engine), store)["orphan_files"]) == 1
+
+
+def test_status_cannot_cross_organization(intake):
+ engine, _, _, _, _, _, run = intake
+ doc = run()["document"]
+ other_org, other_actor = uuid4(), uuid4()
+ with engine.begin() as connection:
+ connection.execute(text("INSERT INTO organizations(id,name) VALUES (:id,'other')"), {"id": other_org})
+ connection.execute(text("""
+ INSERT INTO users(id,organization_id,username,password_hash,role)
+ VALUES (:id,:org,:name,'test-only','admin')
+ """), {"id": other_actor, "org": other_org, "name": str(other_actor)})
+ with pytest.raises(IntakeError) as error:
+ status(SqlIntakeRepository(engine), administrator_id=other_actor, document_id=doc["id"])
+ assert error.value.code == "DOCUMENT_NOT_FOUND"
+
+
+def test_file_finalization_failure_creates_no_database_rows(intake, monkeypatch):
+ import os
+ engine, _, store, _, _, _, run = intake
+ def fail(*args):
+ raise OSError("disk failure")
+ monkeypatch.setattr(os, "link", fail)
+ with pytest.raises(OSError):
+ run()
+ assert counts(engine) == (0, 0, 0, 0)
+ assert store.inventory()["originals"] == store.inventory()["temporary_files"] == []
+
+def test_ambiguous_commit_preserves_original_and_same_key_recovers(intake):
+ from contextlib import contextmanager
+ engine, settings, store, path, _, actor, _ = intake
+ request = uuid4()
+ class LostAcknowledgment:
+ calls = 0
+ @contextmanager
+ def begin(self):
+ self.calls += 1
+ with engine.begin() as connection:
+ yield connection
+ if self.calls == 2:
+ raise OSError("acknowledgment lost after commit")
+ with pytest.raises(OSError):
+ import_document(SqlIntakeRepository(LostAcknowledgment()), store, settings, path=path,
+ administrator_id=actor, request_id=request)
+ assert counts(engine) == (1, 1, 1, 0)
+ assert reconcile(SqlIntakeRepository(engine), store)["orphan_files"] == []
+ result = import_document(SqlIntakeRepository(engine), store, settings, path=path,
+ administrator_id=actor, request_id=request)
+ assert result["replayed"] is True
+ assert store.read(result["document"]["storage_key"]) == path.read_bytes()
+ assert len(store.inventory()["originals"]) == 1
+
+
+def test_cli_structured_import_status_and_reconciliation(intake, monkeypatch, capsys):
+ import json
+ import app.ingest as cli
+ engine, settings, store, path, _, actor, _ = intake
+ monkeypatch.setattr(cli, "IngestionSettings", lambda: settings)
+ monkeypatch.setattr(cli, "create_database", lambda _: engine)
+ monkeypatch.setattr(cli, "LocalFileStore", lambda _: store)
+ request = str(uuid4())
+ args = ["import", str(path), "--administrator-id", str(actor),
+ "--idempotency-key", request]
+ assert cli.main(args) == 0
+ imported = json.loads(capsys.readouterr().out)
+ doc = imported["document"]
+ assert cli.main(["status", doc["id"], "--administrator-id", str(actor)]) == 0
+ assert json.loads(capsys.readouterr().out)["document"]["job"]["id"] == doc["job"]["id"]
+ assert cli.main(args) == 0
+ assert json.loads(capsys.readouterr().out)["replayed"]
+ assert cli.main(["reconcile"]) == 0
+ assert json.loads(capsys.readouterr().out)["orphan_files"] == []
+ assert cli.main(args + ["--title", "changed"]) == 1
+ captured = capsys.readouterr()
+ assert captured.out == ""
+ assert json.loads(captured.err)["error"]["code"] == "IDEMPOTENCY_CONFLICT"
+
+def test_replay_preserves_processing_snapshot_after_limit_changes(intake):
+ engine, settings, store, path, _, actor, run = intake
+ request = uuid4()
+ first = run(request)
+ changed = settings.model_copy(update={"chunk_size_characters": 1200})
+ replay = import_document(SqlIntakeRepository(engine), store, changed, path=path,
+ administrator_id=actor, request_id=request)
+ assert replay["replayed"]
+ assert replay["document"]["processing_profile"] == first["document"]["processing_profile"]
+ assert replay["document"]["processing_profile"] != changed.processing_profile()
+
+@pytest.mark.parametrize("policy", ["size", "format", "both"])
+def test_replay_after_policy_changes_and_new_import_enforcement(intake, policy):
+ engine, settings, store, path, _, actor, run = intake
+ request = uuid4()
+ first = run(request, title=" Stable title ")
+ doc = first["document"]
+ original_bytes = path.read_bytes()
+ before_counts = counts(engine)
+ with engine.connect() as connection:
+ audits = connection.execute(text("SELECT * FROM audit_events")).mappings().all()
+ overrides = {"chunk_size_characters": 1200}
+ if policy in {"size", "both"}:
+ overrides["max_original_bytes"] = 1
+ if policy in {"format", "both"}:
+ overrides["accepted_formats"] = (".pdf",)
+ changed = settings.model_copy(update=overrides)
+ def submit(key, title="Stable title"):
+ return import_document(SqlIntakeRepository(engine), store, changed, path=path,
+ administrator_id=actor, request_id=key, title=title)
+ replay = submit(request)
+ assert replay["replayed"] and replay["document"] == doc
+ assert replay["document"]["processing_profile"] != changed.processing_profile()
+ assert store.read(doc["storage_key"]) == original_bytes
+ assert store.inventory()["originals"] == [doc["storage_key"]]
+ with pytest.raises(IntakeError) as error:
+ submit(request, title="Different title")
+ assert error.value.code == "IDEMPOTENCY_CONFLICT"
+ for different in [b"", b"x" * len(original_bytes), b"x" * (len(original_bytes) + 100)]:
+ path.write_bytes(different)
+ with pytest.raises(IntakeError) as error:
+ submit(request)
+ assert error.value.code == "IDEMPOTENCY_CONFLICT"
+ path.write_bytes(original_bytes)
+ with pytest.raises(IntakeError) as error:
+ submit(uuid4())
+ assert error.value.code == ("UNSUPPORTED_FILE_TYPE" if policy in {"format", "both"} else "FILE_TOO_LARGE")
+ assert counts(engine) == before_counts == (1, 1, 1, 0)
+ with engine.connect() as connection:
+ assert connection.execute(text("SELECT * FROM audit_events")).mappings().all() == audits
+ assert store.read(doc["storage_key"]) == original_bytes
+ assert reconcile(SqlIntakeRepository(engine), store)["orphan_files"] == []
+
+
+@pytest.mark.parametrize("conflict", [False, True])
+def test_candidate_cleanup_failure_keeps_confirmed_cli_outcome(intake, monkeypatch, capsys, conflict):
+ import json
+ import app.ingest as cli
+ engine, settings, store, path, _, actor, _ = intake
+ request = uuid4()
+ candidate_keys, winner = [], []
+ original_put = store.put
+ def concurrent_winner(content):
+ candidate_keys.append(original_put(content))
+ # Another importer commits after the outer request checked for an existing key.
+ winner.append(import_document(SqlIntakeRepository(engine), LocalFileStore(store.directory), settings,
+ path=path, administrator_id=actor,
+ request_id=request, title="winner")["document"])
+ return candidate_keys[-1]
+ def failed_discard(key):
+ raise OSError("dummy-secret-path " + key)
+ monkeypatch.setattr(store, "put", concurrent_winner)
+ monkeypatch.setattr(store, "discard_unused", failed_discard)
+ monkeypatch.setattr(cli, "IngestionSettings", lambda: settings)
+ monkeypatch.setattr(cli, "create_database", lambda _: engine)
+ monkeypatch.setattr(cli, "LocalFileStore", lambda _: store)
+ result = cli.main(["import", str(path), "--administrator-id", str(actor),
+ "--idempotency-key", str(request),
+ "--title", "changed" if conflict else "winner"])
+ captured = capsys.readouterr()
+ diagnostics = [json.loads(line) for line in captured.err.splitlines()]
+ assert diagnostics[0]["warning"]["code"] == "UNUSED_CANDIDATE_CLEANUP_FAILED"
+ assert "dummy-secret-path" not in captured.err and candidate_keys[0] not in captured.err
+ if conflict:
+ assert result == 1 and captured.out == ""
+ assert diagnostics[1]["error"]["code"] == "IDEMPOTENCY_CONFLICT"
+ else:
+ assert result == 0
+ replay = json.loads(captured.out)
+ assert replay["replayed"] and replay["document"]["id"] == str(winner[0]["id"])
+ assert len(diagnostics) == 1
+ assert counts(engine) == (1, 1, 1, 0)
+ assert store.read(winner[0]["storage_key"]) == path.read_bytes()
+ assert reconcile(SqlIntakeRepository(engine), store)["orphan_files"] == candidate_keys
+ assert reconcile(SqlIntakeRepository(engine), store)["missing_originals"] == []
+
+
+@pytest.mark.parametrize("guard", ["disabled", "embedding", "organization"])
+def test_existing_key_does_not_bypass_identity_scope_or_compatibility(intake, guard):
+ from app.infrastructure.database import CompatibilityError
+ engine, settings, store, path, _, actor, run = intake
+ request = uuid4()
+ run(request)
+ changed = settings.model_copy(update={"max_original_bytes": 1, "accepted_formats": (".pdf",)})
+ if guard == "disabled":
+ with engine.begin() as connection:
+ connection.execute(text("UPDATE users SET is_enabled=false WHERE id=:id"), {"id": actor})
+ expected, code = IntakeError, "ADMINISTRATOR_REQUIRED"
+ elif guard == "embedding":
+ changed = changed.model_copy(update={"embedding_model": "other-model"})
+ expected, code = CompatibilityError, None
+ else:
+ org, actor = uuid4(), uuid4()
+ with engine.begin() as connection:
+ connection.execute(text("INSERT INTO organizations(id,name) VALUES (:id,'other')"), {"id": org})
+ connection.execute(text("""
+ INSERT INTO users(id,organization_id,username,password_hash,role)
+ VALUES (:id,:org,:name,'test-only','admin')
+ """), {"id": actor, "org": org, "name": str(actor)})
+ expected, code = IntakeError, "UNSUPPORTED_FILE_TYPE"
+ with pytest.raises(expected) as error:
+ import_document(SqlIntakeRepository(engine), store, changed, path=path, administrator_id=actor, request_id=request)
+ if code:
+ assert error.value.code == code
+ assert counts(engine) == (1, 1, 1, 0)
+
+def test_replay_rechecks_enabled_administrator_after_payload_read(intake, monkeypatch):
+ import app.modules.documents.intake as module
+ engine, settings, store, path, _, actor, run = intake
+ request = uuid4()
+ original = run(request)["document"]
+ hash_payload = module.replay_payload_hash
+ def disable_after_read(*args, **kwargs):
+ result = hash_payload(*args, **kwargs)
+ with engine.begin() as connection:
+ connection.execute(text("UPDATE users SET is_enabled=false WHERE id=:id"), {"id": actor})
+ return result
+ monkeypatch.setattr(module, "replay_payload_hash", disable_after_read)
+ with pytest.raises(IntakeError) as error:
+ import_document(SqlIntakeRepository(engine), store, settings, path=path, administrator_id=actor, request_id=request)
+ assert error.value.code == "ADMINISTRATOR_REQUIRED"
+ assert counts(engine) == (1, 1, 1, 0)
+ assert store.read(original["storage_key"]) == path.read_bytes()
+
+
+@pytest.mark.parametrize("extension", [".docx", ".jpg", ".jpeg", ".png"])
+def test_new_format_transactions_and_profile_replay(intake, extension):
+ engine, settings, store, path, _, actor, run = intake
+ path = path.with_name("\u0633\u0646\u062f\u200c\u4e2d\U0001f600" + extension)
+ path.write_bytes(format_bytes(extension))
+ request = uuid4()
+ first = run(request, path=path)["document"]
+ assert first["original_filename"] == path.name
+ assert first["status"] == first["job"]["status"] == "queued"
+ assert not first["is_active"] and first["chunk_count"] == 0
+ assert first["processing_profile"] == settings.processing_profile()
+ changed = settings.model_copy(update={"accepted_formats": (".md",), "max_original_bytes": 1,
+ "quality_policy": "new-quality", "vision_provider": "new", "vision_endpoint": "https://vision.invalid",
+ "vision_model": "new-model", "vision_api_key": "dummy-secret"})
+ result = import_document(SqlIntakeRepository(engine), store, changed, path=path, administrator_id=actor, request_id=request)
+ assert result["replayed"] and result["document"] == first
+ assert store.read(first["storage_key"]) == path.read_bytes()
+ assert counts(engine) == (1, 1, 1, 0)
+
+
+def test_legacy_snapshot_replays_byte_for_byte(intake):
+ import json
+ engine, settings, store, path, _, actor, run = intake
+ request = uuid4()
+ first = run(request)["document"]
+ legacy = {"extractor": "pypdf-markdown-v1", "normalizer": "unicode-line-endings-v1",
+ "chunker": "paragraph-v1", "chunk_size": 1000, "overlap": 200,
+ "size_unit": "characters", "embedding": settings.processing_profile()["embedding"],
+ "limits": settings.processing_profile()["limits"]}
+ with engine.begin() as connection:
+ connection.execute(text("UPDATE documents SET processing_profile=CAST(:profile AS jsonb) WHERE id=:id"),
+ {"profile": json.dumps(legacy), "id": first["id"]})
+ changed = settings.model_copy(update={"max_original_bytes": 1, "accepted_formats": (".docx",)})
+ replay = import_document(SqlIntakeRepository(engine), store, changed, path=path, administrator_id=actor, request_id=request)
+ assert replay["replayed"] and replay["document"]["id"] == first["id"]
+ assert replay["document"]["job"]["id"] == first["job"]["id"]
+ assert replay["document"]["processing_profile"] == legacy
+ assert counts(engine) == (1, 1, 1, 0)
+
+
+def test_administrator_scope_change_during_file_io_is_rejected(intake):
+ engine, settings, store, path, _, actor, _ = intake
+ other = uuid4()
+ with engine.begin() as connection:
+ connection.execute(text("INSERT INTO organizations(id,name) VALUES (:id,'other')"), {"id": other})
+ class ChangingStore(LocalFileStore):
+ def put(self, content):
+ key = super().put(content)
+ with engine.begin() as connection:
+ connection.execute(text("UPDATE users SET organization_id=:org WHERE id=:id"), {"org": other, "id": actor})
+ return key
+ with pytest.raises(IntakeError) as error:
+ import_document(SqlIntakeRepository(engine), ChangingStore(store.directory), settings, path=path,
+ administrator_id=actor, request_id=uuid4())
+ assert error.value.code == "DOCUMENT_NOT_FOUND" and counts(engine) == (0, 0, 0, 0)
+ assert len(reconcile(SqlIntakeRepository(engine), store)["orphan_files"]) == 1
+
+
+@pytest.mark.parametrize("descriptor", [None, "signed", "unsigned"])
+@pytest.mark.parametrize("size", [20, 1024 * 1024])
+def test_dishonest_docx_rejected_before_candidate_and_database_writes(intake, descriptor, size):
+ engine, _, store, path, _, _, run = intake
+ path = path.with_suffix(".docx")
+ path.write_bytes(raw_docx(b"x" * size, declared_length=4, descriptor=descriptor))
+ with pytest.raises(IntakeError) as error: run(path=path)
+ assert error.value.code == "INVALID_FILE"
+ assert counts(engine) == (0, 0, 0, 0)
+ assert store.inventory()["originals"] == []
+
+
+@pytest.mark.parametrize("method", [0, 8])
+@pytest.mark.parametrize("descriptor", ["signed", "unsigned"])
+def test_descriptor_docx_atomic_intake_and_replay(intake, method, descriptor):
+ engine, _, store, path, _, _, run = intake
+ path = path.with_suffix(".docx")
+ path.write_bytes(raw_docx(method=method, descriptor=descriptor))
+ request = uuid4()
+ first = run(request, path=path)
+ replay = run(request, path=path)
+ assert replay["replayed"] and replay["document"] == first["document"]
+ assert counts(engine) == (1, 1, 1, 0)
+ assert store.read(first["document"]["storage_key"]) == path.read_bytes()
diff --git a/tests/support/formats.py b/tests/support/formats.py
new file mode 100644
index 0000000..5809b7f
--- /dev/null
+++ b/tests/support/formats.py
@@ -0,0 +1,69 @@
+"""Small valid inputs; no providers or heavyweight document libraries."""
+from io import BytesIO
+from zipfile import ZipFile, ZIP_DEFLATED
+from PIL import Image
+
+
+def docx_bytes(extra=None, document=None):
+ members = {
+ "[Content_Types].xml": b'',
+ "_rels/.rels": b'',
+ "word/document.xml": document or b'FAQ',
+ }
+ members.update(extra or {})
+ output = BytesIO()
+ with ZipFile(output, "w", compression=ZIP_DEFLATED) as archive:
+ for name, value in members.items():
+ archive.writestr(name, value)
+ return output.getvalue()
+
+
+def image_bytes(format="JPEG", size=(32, 24)):
+ output = BytesIO()
+ Image.new("RGB", size, "white").save(output, format=format)
+ return output.getvalue()
+
+
+def format_bytes(extension):
+ return docx_bytes() if extension == ".docx" else image_bytes("PNG" if extension == ".png" else "JPEG")
+
+
+def raw_docx(payload=b"extra", *, method=8, descriptor=None, declared_length=None,
+ compressed_suffix=b"", truncate=0, crc_prefix_length=None):
+ """Raw ZIP32 fixture, including mutually dishonest local/central metadata."""
+ import struct
+ import zlib
+ with ZipFile(BytesIO(docx_bytes())) as archive:
+ members = [(entry.filename, archive.read(entry)) for entry in archive.infolist()]
+ members.append(("word/extra.bin", payload))
+ local, central = bytearray(), bytearray()
+ for name, value in members:
+ name = name.encode("utf-8")
+ flags = 0x800 | (8 if descriptor else 0)
+ if method == 8:
+ encoder = zlib.compressobj(wbits=-15)
+ compressed = encoder.compress(value) + encoder.flush()
+ else:
+ compressed = value
+ length = len(value)
+ crc = zlib.crc32(value)
+ if name == b"word/extra.bin":
+ if declared_length is not None:
+ length = declared_length
+ crc = zlib.crc32(value[:length])
+ if crc_prefix_length is not None:
+ crc = zlib.crc32(value[:crc_prefix_length])
+ if truncate:
+ compressed = compressed[:-truncate]
+ compressed += compressed_suffix
+ offset = len(local)
+ local += struct.pack("<4s5H3L2H", b"PK\x03\x04", 20, flags, method, 0, 0,
+ 0 if descriptor else crc, 0 if descriptor else len(compressed),
+ 0 if descriptor else length, len(name), 0) + name + compressed
+ if descriptor:
+ if descriptor == "signed": local += b"PK\x07\x08"
+ local += struct.pack("<3L", crc, len(compressed), length)
+ central += struct.pack("<4s6H3L5H2L", b"PK\x01\x02", 20, 20, flags, method, 0, 0,
+ crc, len(compressed), length, len(name), 0, 0, 0, 0, 0, offset) + name
+ return bytes(local + central + struct.pack("<4s4H2LH", b"PK\x05\x06", 0, 0,
+ len(members), len(members), len(central), len(local), 0))
diff --git a/tests/unit/test_docx_streams.py b/tests/unit/test_docx_streams.py
new file mode 100644
index 0000000..d7d77ec
--- /dev/null
+++ b/tests/unit/test_docx_streams.py
@@ -0,0 +1,107 @@
+"""Full raw-stream integrity and bounded rejection of forged ZIP declarations."""
+from io import BytesIO
+from zipfile import ZipFile
+import pytest
+from app.modules.documents.intake import IntakeError, prepare_file
+from tests.support.formats import raw_docx
+
+
+@pytest.mark.parametrize("budget", ["member", "aggregate", "ratio"])
+@pytest.mark.parametrize("descriptor", [None, "signed", "unsigned"])
+def test_forged_prefix_cannot_bypass_expansion_budgets(tmp_path, settings, budget, descriptor):
+ payload = b"p" * 64 + b"x" * (1024 * 1024)
+ content = raw_docx(payload, declared_length=64, descriptor=descriptor)
+ # Demonstrate the reviewed ZipExtFile truncation and dishonest prefix CRC.
+ with ZipFile(BytesIO(content)) as archive:
+ assert archive.read("word/extra.bin") == payload[:64]
+ overrides = {"member": {"max_docx_member_bytes": 4096},
+ "aggregate": {"max_docx_expanded_bytes": 2000},
+ "ratio": {"max_docx_compression_ratio": 20}}[budget]
+ path = tmp_path / "forged.docx"
+ path.write_bytes(content)
+ with pytest.raises(IntakeError):
+ prepare_file(path, None, settings.model_copy(update=overrides))
+
+
+@pytest.mark.parametrize("method", [0, 8])
+@pytest.mark.parametrize("descriptor", [None, "signed", "unsigned"])
+def test_stored_and_deflated_descriptor_acceptance(tmp_path, settings, method, descriptor):
+ path = tmp_path / "valid.docx"
+ path.write_bytes(raw_docx(method=method, descriptor=descriptor))
+ assert prepare_file(path, None, settings)["mime"].endswith("wordprocessingml.document")
+
+
+@pytest.mark.parametrize("descriptor", [None, "signed", "unsigned"])
+@pytest.mark.parametrize("fault", ["short_length", "truncated", "trailing", "concatenated", "stored_short", "full_crc"])
+def test_full_stream_length_crc_completion_and_boundaries(tmp_path, settings, descriptor, fault):
+ kwargs = {"descriptor": descriptor}
+ if fault == "full_crc": kwargs["crc_prefix_length"] = 4
+ if fault == "short_length": kwargs["declared_length"] = 4
+ if fault == "stored_short": kwargs.update(method=0, declared_length=4)
+ if fault == "truncated": kwargs["truncate"] = 1
+ if fault == "trailing": kwargs["compressed_suffix"] = b"extra bytes"
+ if fault == "concatenated": kwargs["compressed_suffix"] = b"\x03\x00"
+ path = tmp_path / "invalid.docx"
+ path.write_bytes(raw_docx(b"faithful whole member", **kwargs))
+ with pytest.raises(IntakeError): prepare_file(path, None, settings)
+
+
+@pytest.mark.parametrize("method", [0, 8])
+@pytest.mark.parametrize("descriptor", [None, "signed", "unsigned"])
+def test_multiblock_crc_and_member_completion(tmp_path, settings, method, descriptor):
+ import random
+ path = tmp_path / "multiblock.docx"
+ path.write_bytes(raw_docx(random.Random(17).randbytes(220000), method=method, descriptor=descriptor))
+ assert prepare_file(path, None, settings)["content"] == path.read_bytes()
+
+
+@pytest.mark.parametrize("method,budget", [(0, "member"), (0, "aggregate"), (8, "member"), (8, "aggregate"), (8, "ratio")])
+def test_actual_budget_stops_promptly_with_bounded_output(tmp_path, settings, monkeypatch, method, budget):
+ import zlib
+ from app.modules.documents.formats import validate_docx
+ payload = b"prefix" * 12 + b"x" * (8 * 1024 * 1024)
+ content = raw_docx(payload, method=method, declared_length=64)
+ overrides = {"member": {"max_docx_member_bytes": 4096},
+ "aggregate": {"max_docx_expanded_bytes": 2000},
+ "ratio": {"max_docx_compression_ratio": 20}}[budget]
+ configured = settings.model_copy(update=overrides)
+ original, emitted = zlib.decompressobj, []
+ class BoundedDecoder:
+ def __init__(self, *args):
+ self.decoder = original(*args)
+ self.output = 0
+ emitted.append(self)
+ def decompress(self, data, max_length=0):
+ assert 0 < max_length <= 65536
+ result = self.decoder.decompress(data, max_length)
+ self.output += len(result)
+ return result
+ def __getattr__(self, name): return getattr(self.decoder, name)
+ def flush(self, *args): pytest.fail("Flush must not bypass output bounds")
+ monkeypatch.setattr(zlib, "decompressobj", BoundedDecoder)
+ with pytest.raises(ValueError, match="actual expansion budget"):
+ validate_docx(content, configured)
+ if method == 8:
+ target = emitted[-1]
+ if budget == "member": assert target.output <= 4097
+ if budget == "aggregate": assert sum(item.output for item in emitted) <= 2001
+ if budget == "ratio":
+ with ZipFile(BytesIO(content)) as archive:
+ bound = archive.getinfo("word/extra.bin").compress_size * 20
+ assert target.output <= bound + 1
+ assert target.output < len(payload) // 10
+
+
+@pytest.mark.parametrize("method", [0, 8])
+@pytest.mark.parametrize("descriptor", ["signed", "unsigned"])
+@pytest.mark.parametrize("field", [0, 1, 2])
+def test_descriptor_crc_and_sizes_are_checked(tmp_path, settings, method, descriptor, field):
+ import struct
+ content = bytearray(raw_docx(method=method, descriptor=descriptor))
+ end = content.rindex(b"PK\x05\x06")
+ central_start = struct.unpack_from("]>&a;'})),
+ (".docx", docx_bytes({"_rels/.rels": b''})),
+ (".docx", docx_bytes({"[Content_Types].xml": b''})),
+])
+def test_malformed_and_mismatched_formats(tmp_path, settings, extension, content):
+ path = tmp_path / ("input" + extension)
+ path.write_bytes(content)
+ with pytest.raises(IntakeError) as error:
+ prepare_file(path, None, settings)
+ assert error.value.code == "INVALID_FILE"
+ assert error.value.__context__ is None
+
+
+@pytest.mark.parametrize("limit,value", [
+ ("max_docx_entries", 2), ("max_docx_member_bytes", 20),
+ ("max_docx_expanded_bytes", 30), ("max_docx_compression_ratio", 1)])
+def test_archive_limits(tmp_path, settings, limit, value):
+ path = tmp_path / "input.docx"
+ path.write_bytes(docx_bytes({"word/large.xml": b"x" * 4096}))
+ with pytest.raises(IntakeError):
+ prepare_file(path, None, settings.model_copy(update={limit: value}))
+
+
+@pytest.mark.parametrize("change", ["duplicate", "missing", "encrypted", "count", "forged_count", "crc"])
+def test_archive_inventory_integrity(tmp_path, settings, change):
+ content = docx_bytes()
+ if change in ("duplicate", "missing"):
+ output = BytesIO()
+ with ZipFile(BytesIO(content)) as original, ZipFile(output, "w") as target:
+ for entry in original.infolist():
+ if change == "missing" and entry.filename == "word/document.xml":
+ continue
+ target.writestr(entry.filename, original.read(entry))
+ if change == "duplicate":
+ with pytest.warns(UserWarning):
+ target.writestr("word/document.xml", b"duplicate")
+ content = output.getvalue()
+ else:
+ data = bytearray(content)
+ if change == "encrypted":
+ central = data.index(b"PK\x01\x02")
+ struct.pack_into("