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,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
|
||||
Reference in New Issue
Block a user