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
+489
View File
@@ -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()
+69
View File
@@ -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'<Types xmlns="http://schemas.openxmlformats.org/package/2006/content-types"><Override PartName="/word/document.xml" ContentType="application/vnd.openxmlformats-officedocument.wordprocessingml.document.main+xml"/></Types>',
"_rels/.rels": b'<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships"><Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument" Target="word/document.xml"/></Relationships>',
"word/document.xml": document or b'<w:document xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main"><w:body><w:p><w:r><w:t>FAQ</w:t></w:r></w:p></w:body></w:document>',
}
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))
+107
View File
@@ -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("<L", content, end + 16)[0]
# Last descriptor's values are the final twelve bytes before the directory.
content[central_start - 12 + 4 * field] ^= 1
path = tmp_path / "descriptor.docx"
path.write_bytes(content)
with pytest.raises(IntakeError): prepare_file(path, None, settings)
+139
View File
@@ -0,0 +1,139 @@
"""Explicit allowlist, bounded actual-type validation and supplied intake samples."""
from pathlib import Path
from zipfile import ZipFile
from io import BytesIO
import struct
import pytest
from app.modules.documents.intake import IntakeError, prepare_file
from tests.support.formats import docx_bytes, image_bytes, format_bytes
@pytest.mark.parametrize("extension,mime", [
(".docx", "application/vnd.openxmlformats-officedocument.wordprocessingml.document"),
(".jpg", "image/jpeg"), (".jpeg", "image/jpeg"), (".png", "image/png")])
def test_formats_unicode_and_disabled_policy(tmp_path, settings, extension, mime):
path = tmp_path / ("\u0633\u0646\u062f\u200c\u4e2d\U0001f600" + extension.upper())
path.write_bytes(format_bytes(extension))
result = prepare_file(path, "\u0639\u0646\u0648\u0627\u0646\u200c\u4e2d\U0001f600", settings)
assert result["mime"] == mime and result["content"] == path.read_bytes()
assert result["filename"] == path.name
assert result["title"] == "\u0639\u0646\u0648\u0627\u0646\u200c\u4e2d\U0001f600"
with pytest.raises(IntakeError) as error:
prepare_file(path, None, settings.model_copy(update={"accepted_formats": (".md",)}))
assert error.value.code == "UNSUPPORTED_FILE_TYPE"
@pytest.mark.parametrize("extension,content", [
(".docx", b"not a zip"), (".docx", image_bytes()), (".docx", b"PK\x03\x04"),
(".jpg", docx_bytes()), (".jpg", image_bytes("PNG")), (".png", image_bytes()),
(".jpg", image_bytes()[:-20]), (".png", image_bytes("PNG")[:-20]),
(".docx", docx_bytes({"word/document.xml": b"not xml"})),
(".docx", docx_bytes({"../escape": b"x"})),
(".docx", docx_bytes({"word/document.xml": b'<!DOCTYPE document [<!ENTITY a "secret">]><document>&a;</document>'})),
(".docx", docx_bytes({"_rels/.rels": b'<Relationships/>'})),
(".docx", docx_bytes({"[Content_Types].xml": b'<Types/>'})),
])
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("<H", data, central + 8, 1)
elif change == "count":
end = data.rindex(b"PK\x05\x06")
struct.pack_into("<HH", data, end + 8, 65535, 65535)
elif change == "forged_count":
end = data.rindex(b"PK\x05\x06")
struct.pack_into("<HH", data, end + 8, 1, 1)
else:
central = data.index(b"PK\x01\x02")
struct.pack_into("<I", data, central + 16, 123)
content = bytes(data)
path = tmp_path / "input.docx"
path.write_bytes(content)
with pytest.raises(IntakeError):
prepare_file(path, None, settings)
@pytest.mark.parametrize("limit,value", [("max_image_width", 31), ("max_image_height", 23), ("max_image_pixels", 767)])
@pytest.mark.parametrize("extension", [".png", ".jpg"])
def test_image_limits_before_decode(tmp_path, settings, extension, limit, value):
path = tmp_path / ("input" + extension)
path.write_bytes(format_bytes(extension))
with pytest.raises(IntakeError):
prepare_file(path, None, settings.model_copy(update={limit: value}))
def test_image_bomb_is_safe_error(tmp_path, settings, monkeypatch):
from PIL import Image
monkeypatch.setattr(Image, "MAX_IMAGE_PIXELS", 400)
path = tmp_path / "input.jpg"
path.write_bytes(image_bytes())
with pytest.raises(IntakeError):
prepare_file(path, None, settings)
def test_supplied_docx_jpeg_samples(settings):
root = Path(__file__).resolve().parents[2] / "data/documents"
samples = [root / "-2348240626507047168_13449360743721.docx",
root / "photo_1_2026-10-06_09-05-11.jpg"]
# Local sample evidence remains conditional; generated fixtures always run.
if not all(path.exists() for path in samples):
pytest.skip("User-supplied samples absent from this checkout")
for path in samples:
assert prepare_file(path, None, settings)["content"] == path.read_bytes()
def test_animated_png_is_not_supported(tmp_path, settings):
from PIL import Image
output = BytesIO()
Image.new("RGB", (4, 4), "white").save(output, format="PNG", save_all=True,
append_images=[Image.new("RGB", (4, 4), "black")])
path = tmp_path / "animated.png"
path.write_bytes(output.getvalue())
with pytest.raises(IntakeError): prepare_file(path, None, settings)
def test_archive_claimed_count_checked_before_inventory_allocation(tmp_path, settings, monkeypatch):
import app.modules.documents.formats as module
data = bytearray(docx_bytes())
end = data.rindex(b"PK\x05\x06")
struct.pack_into("<HH", data, end + 8, 1, 1)
path = tmp_path / "forged.docx"
path.write_bytes(data)
def forbidden(*args, **kwargs):
pytest.fail("Invalid directory must fail before ZipFile allocation")
monkeypatch.setattr(module, "ZipFile", forbidden)
with pytest.raises(IntakeError): prepare_file(path, None, settings)
+215
View File
@@ -0,0 +1,215 @@
"""Provider-free intake validation and filesystem guarantees."""
import os
from pathlib import Path
import subprocess
import sys
from uuid import uuid4
import pytest
from app.infrastructure.file_store import LocalFileStore
from app.modules.documents.intake import IntakeError, prepare_file
@pytest.mark.parametrize("name,content,code", [
("empty.md", b"", "INVALID_FILE"),
("binary.md", b"hello\x00world", "INVALID_FILE"),
("wrong.md", b"%PDF-1.7\n", "INVALID_FILE"),
("encoding.md", b"\xff", "INVALID_FILE"),
("wrong.pdf", b"markdown", "INVALID_FILE"),
("unsupported.txt", b"text", "UNSUPPORTED_FILE_TYPE"),
("CON.md", b"text", "INVALID_FILE"),
("trailing.md ", b"text", "INVALID_FILE"),
])
def test_invalid_files(tmp_path, settings, name, content, code):
path = tmp_path / name
path.write_bytes(content)
with pytest.raises(IntakeError) as error:
prepare_file(path, None, settings)
assert error.value.code == code
@pytest.mark.parametrize("name", ["bad|file.md", "ab:cd.md", "bad\u202efile.md", "bad\x01.md"])
def test_unsafe_display_names(tmp_path, settings, name):
# Validate before touching the filesystem, including names Windows cannot create.
with pytest.raises(IntakeError, match="Unsafe"):
prepare_file(tmp_path / name, None, settings)
def test_size_title_format_and_normalization(tmp_path, settings):
path = tmp_path / "persian.MD"
content = "# عنوان\nمتن با نیم\u200cفاصله\n".encode()
path.write_bytes(content)
result = prepare_file(path, " Cafe\u0301 عنوان ", settings)
assert result["title"] == "Café عنوان"
assert result["content"] == content
assert result["mime"] == "text/markdown"
assert result["payload_hash"] == prepare_file(path, "Café عنوان", settings)["payload_hash"]
assert result["payload_hash"] != prepare_file(path, "Other", settings)["payload_hash"]
with pytest.raises(IntakeError, match="size"):
prepare_file(path, None, settings.model_copy(update={"max_original_bytes": len(content)-1}))
for title in [" ", "a"*201, "a\u202eb"]:
with pytest.raises(IntakeError):
prepare_file(path, title, settings)
with pytest.raises(IntakeError):
prepare_file(path, None, settings.model_copy(update={"accepted_formats": (".pdf",)}))
pdf = tmp_path / "input.pdf"
pdf.write_bytes(b"%PDF-1.7\nmalformed body left for extraction")
assert prepare_file(pdf, None, settings)["mime"] == "application/pdf"
def test_store_restart_independence_and_paths(tmp_path):
store = LocalFileStore(tmp_path / "originals")
one, two = store.put(b"same"), store.put(b"same")
assert one != two
assert LocalFileStore(store.directory).read(one) == b"same"
assert store.inventory() == {"originals": sorted([one, two]),
"temporary_files": [], "unexpected_entries": []}
for key in ["../outside", "/outside", "C:\\outside", "nested/file", "..",
uuid4().hex + ".original/.."]:
with pytest.raises(ValueError):
store.read(key)
with pytest.raises(ValueError):
store.discard_unused(key)
assert store.read(one) == b"same"
def test_failed_finalization_cleans_temporary(tmp_path, monkeypatch):
store = LocalFileStore(tmp_path)
def fail(*args):
raise OSError("simulated")
monkeypatch.setattr(os, "link", fail)
with pytest.raises(OSError):
store.put(b"content")
assert list(tmp_path.iterdir()) == []
def test_generated_key_collision_never_overwrites(tmp_path, monkeypatch):
import app.infrastructure.file_store as module
key = uuid4()
monkeypatch.setattr(module, "uuid4", lambda: key)
store = LocalFileStore(tmp_path)
original = store.put(b"original")
with pytest.raises(FileExistsError):
store.put(b"replacement")
assert store.read(original) == b"original"
assert store.inventory()["temporary_files"] == []
@pytest.mark.parametrize("command", ["import", "status", "reconcile"])
def test_cli_help_independent_of_configuration_and_providers(command):
environment = {key: value for key, value in os.environ.items()
if not key.startswith(("INGEST_", "API_KEY", "LLM_"))}
result = subprocess.run([sys.executable, "-m", "app.ingest", command, "--help"],
capture_output=True, text=True, env=environment)
assert result.returncode == 0, result.stderr
def test_cli_database_failure_emits_no_success_or_secrets(monkeypatch, capsys):
import json
import app.ingest as cli
def failure():
raise RuntimeError("dummy-sensitive-value")
monkeypatch.setattr(cli, "IngestionSettings", failure)
assert cli.main(["reconcile"]) == 1
captured = capsys.readouterr()
assert captured.out == "" and "dummy-sensitive-value" not in captured.err
assert json.loads(captured.err)["error"]["code"] == "INTAKE_FAILED"
def test_symlink_storage_key_is_refused(tmp_path):
store = LocalFileStore(tmp_path)
outside = tmp_path.parent / (uuid4().hex + ".outside")
outside.write_bytes(b"outside")
link = tmp_path / (uuid4().hex + ".original")
try:
try:
link.symlink_to(outside)
except OSError:
pytest.skip("Host does not grant symlink creation")
with pytest.raises(ValueError):
store.read(link.name)
assert link.name in store.inventory()["unexpected_entries"]
finally:
outside.unlink()
def test_explicit_parent_path_uses_only_display_basename(tmp_path, settings):
source = tmp_path / "source.md"
source.write_bytes(b"text")
nested = tmp_path / "nested"
nested.mkdir()
result = prepare_file(nested / ".." / "source.md", None, settings)
assert result["filename"] == "source.md"
def test_persian_display_metadata_preserves_zwnj(tmp_path, settings):
name = "\u0646\u06cc\u0645\u200c\u0641\u0627\u0635\u0644\u0647"
path = tmp_path / (name + ".md")
path.write_bytes(b"content")
result = prepare_file(path, name, settings)
assert result["title"] == name
assert result["filename"] == name + ".md"
@pytest.mark.parametrize("encoding", ["ascii", "cp1252"])
def test_cli_unicode_metadata_on_restrictive_redirected_stdout(settings, tmp_path, monkeypatch, encoding):
import io
import json
import app.ingest as cli
title = "\u0639\u0646\u0648\u0627\u0646 \u0646\u06cc\u0645\u200c\u0641\u0627\u0635\u0644\u0647 \u6f22\u5b57 \U0001f600"
filename = title + ".md"
document = {"id": str(uuid4()), "title": title, "original_filename": filename,
"job": {"id": str(uuid4()), "status": "queued"}}
class Engine:
def dispose(self):
pass
monkeypatch.setattr(cli, "IngestionSettings", lambda: settings)
monkeypatch.setattr(cli, "create_database", lambda _: Engine())
monkeypatch.setattr(cli, "import_document", lambda *args, **kwargs: {"replayed": False, "document": document})
monkeypatch.setattr(cli, "status", lambda *args, **kwargs: document)
output_bytes, error_bytes = io.BytesIO(), io.BytesIO()
stdout = io.TextIOWrapper(output_bytes, encoding=encoding, errors="strict")
stderr = io.TextIOWrapper(error_bytes, encoding=encoding, errors="strict")
monkeypatch.setattr(sys, "stdout", stdout)
monkeypatch.setattr(sys, "stderr", stderr)
for args in [
["import", str(tmp_path / filename), "--administrator-id", str(uuid4()),
"--idempotency-key", str(uuid4()), "--title", title],
["status", document["id"], "--administrator-id", str(uuid4())],
]:
assert cli.main(args) == 0
stdout.flush()
stderr.flush()
decoded = [json.loads(line) for line in output_bytes.getvalue().decode(encoding).splitlines()]
assert all(result["document"] == document for result in decoded)
assert error_bytes.getvalue() == b""
def test_replay_hash_reads_are_bounded_by_accepted_size(tmp_path, monkeypatch):
from app.modules.documents.intake import replay_payload_hash, payload_hash
import hashlib
path = tmp_path / "original.md"
content = b"x" * 150000
path.write_bytes(content)
original_open, reads = Path.open, []
class TrackedStream:
def __init__(self, stream):
self.stream = stream
def __enter__(self):
return self
def __exit__(self, *args):
self.stream.close()
def fileno(self):
return self.stream.fileno()
def read(self, size):
result = self.stream.read(size)
reads.append((size, len(result)))
return result
monkeypatch.setattr(Path, "open", lambda self, *args, **kwargs:
TrackedStream(original_open(self, *args, **kwargs)))
assert replay_payload_hash(path, " Title ", len(content)) == payload_hash(hashlib.sha256(content).hexdigest(), "Title")
assert all(0 < requested <= 65536 for requested, _ in reads)
reads.clear()
with pytest.raises(IntakeError) as error:
replay_payload_hash(path, "Title", 100)
assert error.value.code == "IDEMPOTENCY_CONFLICT"
assert sum(actual for _, actual in reads) == 101
+67
View File
@@ -0,0 +1,67 @@
"""Application services run through injected ports with SQL imports forbidden."""
import os
import subprocess
import sys
def test_application_intake_status_and_reconcile_without_infrastructure(tmp_path):
path = tmp_path / "source.md"
path.write_bytes(b"Faithful original bytes")
script = r"""
import importlib.abc, sys
class BlockInfrastructure(importlib.abc.MetaPathFinder):
def find_spec(self, fullname, *args):
if fullname.startswith(("app.infrastructure", "sqlalchemy", "psycopg")):
raise AssertionError("Concrete infrastructure imported: " + fullname)
from pathlib import Path
from uuid import uuid4
from app.modules.documents.settings import IngestionSettings
settings = IngestionSettings(_env_file=None, database_url="postgresql+psycopg://unused/unused",
embedding_provider="test", embedding_endpoint="https://test.invalid/v1",
embedding_model="test", embedding_dimensions=3)
# Configuration URL validation deliberately uses SQLAlchemy's parser; it belongs
# before application execution. Clear its modules so service imports cannot hide
# a concrete SQL dependency behind a previously cached import.
for name in tuple(sys.modules):
if name.startswith(("app.infrastructure", "sqlalchemy", "psycopg")):
del sys.modules[name]
sys.meta_path.insert(0, BlockInfrastructure())
from app.modules.documents.intake import import_document, status, reconcile
class Repository:
def __init__(self): self.previous = None; self.calls = []; self.org = uuid4()
def lookup(self, settings, actor, request):
self.calls.append("lookup"); return self.org, self.previous
def create(self, settings, prepared, key, actor, request, org):
assert org == self.org
self.calls.append("create")
self.document = {"id": uuid4(), "storage_key": key,
"processing_profile": settings.processing_profile(), "job": {"id": uuid4()}}
self.previous = {"id": self.document["id"], "size_bytes": len(prepared["content"]),
"upload_payload_hash": prepared["payload_hash"]}
return False, False, self.document
def replay(self, org, actor, previous, submitted_hash):
assert org == self.org and submitted_hash == self.previous["upload_payload_hash"]
self.calls.append("replay"); return self.document
def status(self, actor, document):
assert document == self.document["id"]
self.calls.append("status"); return self.document
def original_references(self):
self.calls.append("references"); return [self.document]
class Store:
puts = 0
def put(self, content): self.puts += 1; return "candidate"
def inventory(self): return {"originals": ["candidate"], "temporary_files": [], "unexpected_entries": []}
def discard_unused(self, key): raise AssertionError("Unexpected deletion")
repository, store, actor, request = Repository(), Store(), uuid4(), uuid4()
first = import_document(repository, store, settings, path=Path(sys.argv[1]), administrator_id=actor, request_id=request)
assert not first["replayed"]
replay = import_document(repository, store, settings, path=Path(sys.argv[1]), administrator_id=actor, request_id=request)
assert replay["replayed"] and replay["document"] == first["document"] and store.puts == 1
assert status(repository, administrator_id=actor, document_id=first["document"]["id"]) == first["document"]
assert reconcile(repository, store) == {"orphan_files": [], "missing_originals": [],
"temporary_files": [], "unexpected_entries": [], "report_only": True}
assert repository.calls == ["lookup", "create", "lookup", "replay", "status", "references"]
"""
environment = {name: value for name, value in os.environ.items() if not name.upper().startswith("INGEST_")}
result = subprocess.run([sys.executable, "-c", script, str(path)], env=environment, capture_output=True, text=True)
assert result.returncode == 0, result.stderr
+50
View File
@@ -0,0 +1,50 @@
"""Canonical namespace separation without storage mutation."""
import os
from pathlib import Path
import pytest
from pydantic import ValidationError
from app.modules.documents.settings import IngestionSettings
def configure(settings, original, extraction):
return IngestionSettings(_env_file=None, **(settings.model_dump() | {
"original_directory": original, "extraction_directory": extraction}))
@pytest.mark.parametrize("case", ["equal", "child", "parent", "relative_alias", "dot_alias", "case_alias", "extended_alias"])
def test_overlapping_roots_rejected_without_creating_storage(settings, tmp_path, monkeypatch, case):
original = tmp_path / "originals"
extraction = original
if case == "child": extraction = original / "artifacts"
if case == "parent": extraction = tmp_path
if case == "relative_alias":
monkeypatch.chdir(tmp_path)
original = Path("originals")
extraction = tmp_path / "originals"
if case == "dot_alias": extraction = original / ".." / "originals"
if case in ("case_alias", "extended_alias"):
if os.name != "nt": pytest.skip("Windows path alias semantics")
extraction = Path(str(original).swapcase()) if case == "case_alias" else Path("\\\\?\\" + str(original))
before = list(tmp_path.iterdir())
with pytest.raises(ValidationError): configure(settings, original, extraction)
assert list(tmp_path.iterdir()) == before and not original.exists()
def test_sibling_roots_with_shared_prefix_are_valid(settings, tmp_path):
original, extraction = tmp_path / "files", tmp_path / "files-derived"
configure(settings, original, extraction)
assert list(tmp_path.iterdir()) == []
@pytest.mark.parametrize("nested", [False, True])
def test_symlink_root_alias_rejected(settings, tmp_path, nested):
original = tmp_path / "originals"
original.mkdir()
alias = tmp_path / "alias"
try:
alias.symlink_to(original, target_is_directory=True)
except OSError:
pytest.skip("Host does not grant directory symlink creation")
before = list(tmp_path.iterdir())
with pytest.raises(ValidationError): configure(settings, original, alias / "child" if nested else alias)
assert list(tmp_path.iterdir()) == before