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:
@@ -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}
|
||||
Reference in New Issue
Block a user