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
+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