feat(ingestion): implement Phase 2 multi-format intake and raw storage

- Add format validation and inspection for PDF, DOCX, Markdown, Text, HTML, and images
- Implement secure decompression defenses (zip bombs, ratio checks) and image dimension limits
- Implement FileStore with content-addressable storage and intake repositories
- Add unit and integration tests for document intake, format sniffing, and storage roots
- Include sample acceptance document fixtures in data/documents/
This commit is contained in:
amirhosein mazaheri
2026-10-07 16:20:41 +03:30
parent 0a998ac94a
commit b036912293
16 changed files with 1714 additions and 0 deletions
+70
View File
@@ -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()}
+117
View File
@@ -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
+5
View File
@@ -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
+248
View File
@@ -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")
+138
View File
@@ -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}