"""Regression coverage for Phase 3 repairs: body admission, Unicode filenames, proxy configs.""" import asyncio import json import tempfile from pathlib import Path from unittest.mock import MagicMock from uuid import UUID, uuid4 import httpx import pytest from app.main import app from app.api.v1 import dependencies from app.api.v1.dependencies import ( MAX_DECISION_BYTES, MAX_SELECTION_BYTES, receive_json, receive_empty, ) from app.api.v1.documents import get_document_services from app.api.v1.uploads import receive_upload from app.modules.auth.service import UserContext from app.modules.documents.intake import ( IntakeError, prepare_file, replay_payload_hash, normalized_title, ) from app.modules.documents.review import ReviewDecision from app.api.v1.knowledge import SelectionRequest from app.modules.voice.configuration import VoiceSettings from tests.unit.test_upload_boundary import Request as UploadRequest, multipart @pytest.fixture def test_admin(): return UserContext( id=uuid4(), organization_id=uuid4(), username='admin', role='admin', is_enabled=True, auth_session_id=uuid4(), access_epoch=1, ) @pytest.fixture def auth_overrides(test_admin): app.state.ready = True app.dependency_overrides[dependencies.require_admin] = lambda: test_admin app.dependency_overrides[dependencies.require_csrf] = lambda: None mock_services = MagicMock() app.dependency_overrides[get_document_services] = lambda: mock_services app.dependency_overrides[dependencies.get_engine] = lambda: MagicMock() yield mock_services app.dependency_overrides.clear() def test_unauthenticated_admission_zero_bytes_consumed(): app.state.ready = True mock_auth = MagicMock() mock_auth.get_current_user.side_effect = ValueError('No session') app.dependency_overrides[dependencies.get_auth_service] = lambda: mock_auth bytes_consumed = 0 async def counting_app(scope, receive, send): nonlocal bytes_consumed async def counting_receive(): nonlocal bytes_consumed msg = await receive() if msg.get('type') == 'http.request': bytes_consumed += len(msg.get('body', b'')) return msg await app(scope, counting_receive, send) async def stream_8mb(): for _ in range(128): yield b'X' * 65536 async def run(): nonlocal bytes_consumed transport = httpx.ASGITransport(app=counting_app) async with httpx.AsyncClient(transport=transport, base_url='http://localhost:8000') as client: # 1. Decisions route unauthenticated bytes_consumed = 0 doc_id = str(uuid4()) res1 = await client.post( f'/api/v1/documents/{doc_id}/extraction-review/decisions', content=stream_8mb(), headers={'Host': 'localhost:8000', 'Content-Type': 'application/json', 'Idempotency-Key': str(uuid4())} ) assert res1.status_code == 401 assert res1.json()['error']['code'] == 'AUTH_REQUIRED' assert bytes_consumed == 0 # 2. Knowledge selection route unauthenticated bytes_consumed = 0 res2 = await client.patch( '/api/v1/knowledge-selection', content=stream_8mb(), headers={'Host': 'localhost:8000', 'Content-Type': 'application/json'} ) assert res2.status_code == 401 assert res2.json()['error']['code'] == 'AUTH_REQUIRED' assert bytes_consumed == 0 try: asyncio.run(run()) finally: app.dependency_overrides.clear() def test_streamed_oversized_json_rejection(auth_overrides): async def stream_oversized(size): remaining = size chunk = 65536 while remaining > 0: yield b' ' * min(chunk, remaining) remaining -= chunk async def run(): transport = httpx.ASGITransport(app=app) async with httpx.AsyncClient(transport=transport, base_url='http://localhost:8000') as client: # Decisions exceeding MAX_DECISION_BYTES (DTO-derived bound) res1 = await client.post( f'/api/v1/documents/{uuid4()}/extraction-review/decisions', content=stream_oversized(MAX_DECISION_BYTES + 1024), headers={'Host': 'localhost:8000', 'Content-Type': 'application/json', 'Idempotency-Key': str(uuid4())} ) assert res1.status_code == 413 assert res1.json()['error']['code'] == 'PAYLOAD_TOO_LARGE' # Selection exceeding MAX_SELECTION_BYTES (1 MiB) res2 = await client.patch( '/api/v1/knowledge-selection', content=stream_oversized(MAX_SELECTION_BYTES + 1024), headers={'Host': 'localhost:8000', 'Content-Type': 'application/json'} ) assert res2.status_code == 413 assert res2.json()['error']['code'] == 'PAYLOAD_TOO_LARGE' asyncio.run(run()) def test_absent_and_misleading_content_length(auth_overrides): async def run(): transport = httpx.ASGITransport(app=app) async with httpx.AsyncClient(transport=transport, base_url='http://localhost:8000') as client: # 1. Content-Length header declaring oversized payload (e.g. 10 MB) res1 = await client.post( f'/api/v1/documents/{uuid4()}/extraction-review/decisions', content=b'{}', headers={'Host': 'localhost:8000', 'Content-Type': 'application/json', 'Content-Length': str(MAX_DECISION_BYTES + 1), 'Idempotency-Key': str(uuid4())} ) assert res1.status_code == 413 assert res1.json()['error']['code'] == 'PAYLOAD_TOO_LARGE' # 2. Misleading Content-Length (Content-Length smaller than actual received bytes) valid_payload = json.dumps({'expected_revision': 1, 'document_ids': []}).encode() res2 = await client.patch( '/api/v1/knowledge-selection', content=valid_payload, headers={'Host': 'localhost:8000', 'Content-Type': 'application/json', 'Content-Length': str(len(valid_payload) - 5)} ) assert res2.status_code == 422 assert res2.json()['error']['code'] == 'VALIDATION_ERROR' # 3. Negative or invalid Content-Length res3 = await client.patch( '/api/v1/knowledge-selection', content=valid_payload, headers={'Host': 'localhost:8000', 'Content-Type': 'application/json', 'Content-Length': '-1'} ) assert res3.status_code == 422 assert res3.json()['error']['code'] == 'VALIDATION_ERROR' asyncio.run(run()) def test_slow_body_receive_timeout(auth_overrides, monkeypatch): monkeypatch.setattr(dependencies, 'JSON_RECEIVE_SECONDS', 0.05) async def slow_stream(): yield b'{"expected_revision":' await asyncio.sleep(0.1) yield b' 1, "document_ids": []}' async def run(): transport = httpx.ASGITransport(app=app) async with httpx.AsyncClient(transport=transport, base_url='http://localhost:8000') as client: res = await client.patch( '/api/v1/knowledge-selection', content=slow_stream(), headers={'Host': 'localhost:8000', 'Content-Type': 'application/json'} ) assert res.status_code == 503 assert res.json()['error']['code'] == 'DEPENDENCY_UNAVAILABLE' asyncio.run(run()) def test_valid_large_dtos(auth_overrides): # 1. 10,000 UUIDs in SelectionRequest (~400 KB) doc_ids = [uuid4() for _ in range(10000)] sel = SelectionRequest(expected_revision=1, document_ids=doc_ids) assert len(sel.document_ids) == 10000 serialized_sel = json.dumps({'expected_revision': 1, 'document_ids': [str(u) for u in doc_ids]}).encode() assert len(serialized_sel) < MAX_SELECTION_BYTES # 2. 10,000 excluded group IDs in ReviewDecision (~500 KB) group_ids = tuple(f'group_{i}' for i in range(10000)) rev = ReviewDecision( evidence_sha256='a' * 64, decision='approve', checked=('factual_authority',), note='Validated 10,000 exclusions', excluded_group_ids=group_ids, ) assert len(rev.excluded_group_ids) == 10000 serialized_rev = json.dumps(rev.model_dump(mode='json')).encode() assert len(serialized_rev) < MAX_DECISION_BYTES def test_retry_admission_and_cancellation(auth_overrides, monkeypatch): mock_services = auth_overrides async def run(): transport = httpx.ASGITransport(app=app) async with httpx.AsyncClient(transport=transport, base_url='http://localhost:8000') as client: # 1. Nonempty body rejected before worker retry res1 = await client.post( f'/api/v1/documents/{uuid4()}/retry', content=b'data', headers={'Host': 'localhost:8000', 'Idempotency-Key': str(uuid4())} ) assert res1.status_code == 422 assert res1.json()['error']['code'] == 'VALIDATION_ERROR' assert mock_services.worker.retry.call_count == 0 # 2. Content-Length > 0 rejected before worker retry res2 = await client.post( f'/api/v1/documents/{uuid4()}/retry', headers={'Host': 'localhost:8000', 'Idempotency-Key': str(uuid4()), 'Content-Length': '10'} ) assert res2.status_code == 422 assert res2.json()['error']['code'] == 'VALIDATION_ERROR' assert mock_services.worker.retry.call_count == 0 # 3. Stalled / unfinished retry body times out with 503 monkeypatch.setattr(dependencies, 'RETRY_RECEIVE_SECONDS', 0.05) async def stalled(): await asyncio.sleep(0.1) yield b'' res3 = await client.post( f'/api/v1/documents/{uuid4()}/retry', content=stalled(), headers={'Host': 'localhost:8000', 'Idempotency-Key': str(uuid4())} ) assert res3.status_code == 503 assert res3.json()['error']['code'] == 'DEPENDENCY_UNAVAILABLE' assert mock_services.worker.retry.call_count == 0 # 4. Cancelled retry stream does not invoke worker class CancelledRequest: headers = {} async def stream(self): yield b'' raise asyncio.CancelledError() with pytest.raises(asyncio.CancelledError): await receive_empty(CancelledRequest()) assert mock_services.worker.retry.call_count == 0 asyncio.run(run()) def test_unicode_filename_boundary_and_replay_preservation(settings): with tempfile.TemporaryDirectory() as td: file_path = Path(td) / 'payload' content = b'# Heading\nBody text.' file_path.write_bytes(content) # 128 Arabic chars + .md = 131 chars, 259 UTF-8 bytes (exceeds 255-byte filesystem limit) long_name = 'س' * 128 + '.md' assert len(long_name) == 131 assert len(long_name.encode('utf-8')) == 259 # Prepare with no title: default title is NFC normalized stem prepared = prepare_file(file_path, None, settings, filename=long_name) assert prepared['filename'] == long_name assert prepared['title'] == 'س' * 128 assert len(prepared['title']) == 128 # Replay payload hash matches replay_hash = replay_payload_hash(file_path, None, len(content), filename=long_name) assert replay_hash == prepared['payload_hash'] # Replay with changed title produces different hash changed_title_hash = replay_payload_hash(file_path, 'Other', len(content), filename=long_name) assert changed_title_hash != prepared['payload_hash'] # Replay with changed size produces conflict with pytest.raises(IntakeError) as exc: replay_payload_hash(file_path, None, len(content) + 1, filename=long_name) assert exc.value.code == 'IDEMPOTENCY_CONFLICT' def test_temporary_file_cleanup_on_upload(settings): with tempfile.TemporaryDirectory() as tmp_dir: tmp_path = Path(tmp_dir) # 1. Success cleans spool async def run_success(): req = UploadRequest(multipart([('file', b'test', 'test.md')])) async with receive_upload(req, settings) as (path, filename, title): assert path.exists() parent = path.parent assert not parent.exists() asyncio.run(run_success()) # 2. Rejection cleans spool async def run_rejection(): req = UploadRequest(multipart([('file', b'too large', 'test.md')])) with pytest.raises(IntakeError): async with receive_upload(req, settings.model_copy(update={'max_original_bytes': 3})): pass asyncio.run(run_rejection()) def test_documented_proxy_configurations(monkeypatch): # Config 1: Vite proxy configuration # Vite proxy preserves browser Host ('localhost:5173') and Origin ('http://localhost:5173') voice_vite = VoiceSettings( trusted_hosts=('localhost:5173', '127.0.0.1:5173'), trusted_origins=('http://localhost:5173', 'http://127.0.0.1:5173'), cookie_secure=False, ) monkeypatch.setattr('app.main.config', voice_vite) async def run_vite(): transport = httpx.ASGITransport(app=app) async with httpx.AsyncClient(transport=transport, base_url='http://localhost:5173') as client: res = await client.get('/health/live', headers={'Host': 'localhost:5173'}) assert res.status_code == 200 # Untrusted host through Vite proxy res_bad = await client.get('/health/live', headers={'Host': 'untrusted.com'}) assert res_bad.status_code == 403 assert res_bad.json()['error']['code'] == 'FORBIDDEN' asyncio.run(run_vite()) # Config 2: Direct-run / Docker Compose mapping configuration (port 8080) voice_direct = VoiceSettings( trusted_hosts=('localhost:8080', '127.0.0.1:8080'), trusted_origins=('http://localhost:8080', 'http://127.0.0.1:8080'), cookie_secure=False, ) monkeypatch.setattr('app.main.config', voice_direct) async def run_direct(): transport = httpx.ASGITransport(app=app) async with httpx.AsyncClient(transport=transport, base_url='http://localhost:8080') as client: res = await client.get('/health/live', headers={'Host': 'localhost:8080'}) assert res.status_code == 200 res_bad = await client.get('/health/live', headers={'Host': 'evil.invalid'}) assert res_bad.status_code == 403 assert res_bad.json()['error']['code'] == 'FORBIDDEN' asyncio.run(run_direct()) def test_blocked_selection_keeps_event_loop_responsive(auth_overrides, monkeypatch): from threading import Event from app.api.v1 import knowledge entered, release = Event(), Event() def stalled(*args): entered.set() assert release.wait(3) return {'revision': 2} monkeypatch.setattr(knowledge, 'selection_replace', stalled) async def run(): async with httpx.AsyncClient(transport=httpx.ASGITransport(app=app), base_url='http://localhost:8000') as client: task = asyncio.create_task(client.patch('/api/v1/knowledge-selection', json={'expected_revision': 1, 'document_ids': []})) try: assert await asyncio.to_thread(entered.wait, 1) # This coroutine runs while the selection worker still waits. assert not task.done() assert (await client.get('/health/live')).status_code == 200 finally: release.set() assert (await task).status_code == 200 asyncio.run(run()) @pytest.mark.parametrize('exception, status, code', [ (ValueError('SERVICE_BUSY'), 429, 'RATE_LIMITED'), (TimeoutError(), 503, 'DEPENDENCY_UNAVAILABLE'), ]) def test_selection_blocking_safe_errors(auth_overrides, monkeypatch, exception, status, code): from app.api.v1 import knowledge async def fail(*args): raise exception monkeypatch.setattr(knowledge, 'blocking', fail) async def run(): async with httpx.AsyncClient(transport=httpx.ASGITransport(app=app), base_url='http://localhost:8000') as client: response = await client.patch('/api/v1/knowledge-selection', json={'expected_revision': 1, 'document_ids': []}) assert response.status_code == status assert response.json()['error']['code'] == code asyncio.run(run()) @pytest.mark.parametrize('ensure_ascii', [False, True]) def test_decision_budget_covers_multibyte_and_escaped_identifiers(ensure_ascii): ids = tuple(str(i).zfill(5) + '😀"\\' * 165 for i in range(10000)) decision = ReviewDecision(evidence_sha256='a'*64, decision='approve', checked=('factual_authority',), note='😀'*2000, excluded_group_ids=ids) raw = json.dumps(decision.model_dump(mode='json'), ensure_ascii=ensure_ascii).encode() assert 2 * 1024 * 1024 < len(raw) <= MAX_DECISION_BYTES class Request: headers = {} async def stream(self): for offset in range(0, len(raw), 65536): yield raw[offset:offset+65536] assert asyncio.run(receive_json(Request(), ReviewDecision, MAX_DECISION_BYTES)) == decision def test_json_capacity_checked_before_buffer_extension(monkeypatch): extended = [] class Buffer(bytearray): def extend(self, chunk): extended.append(len(chunk)) super().extend(chunk) monkeypatch.setattr(dependencies, 'bytearray', Buffer, raising=False) class Request: headers = {} async def stream(self): yield b' ' * 8 yield b' ' * 9 from fastapi import HTTPException with pytest.raises(HTTPException) as exc: asyncio.run(receive_json(Request(), ReviewDecision, 16)) assert exc.value.status_code == 413 and extended == [8] def test_csrf_rejection_consumes_no_decision_body(test_admin): app.state.ready = True app.dependency_overrides[dependencies.require_admin] = lambda: test_admin app.dependency_overrides[get_document_services] = lambda: MagicMock() def reject(): raise dependencies.error('CSRF_INVALID') app.dependency_overrides[dependencies.require_csrf] = reject consumed = [] async def body(): consumed.append(True) yield b'{}' async def run(): async with httpx.AsyncClient(transport=httpx.ASGITransport(app=app), base_url='http://localhost:8000') as client: result = await client.post(f'/api/v1/documents/{uuid4()}/extraction-review/decisions', content=body(), headers={'Idempotency-Key': str(uuid4())}) assert result.status_code == 403 and consumed == [] try: asyncio.run(run()) finally: app.dependency_overrides.clear()