feat(backend): deliver Phase 3 document and voice integration
Add authenticated upload, review, retry and knowledge-selection HTTP flows with bounded JSON processing and frozen OCR policy. Preserve Gemini/OpenAI provider selection and fenced lifecycle semantics; retain FAQ preambles and uncertain vision candidates, and expose opt-in uncalibrated voice transport diagnostics. Include frontend integration examples, aligned contracts and deterministic regressions. Validation: 1767 provider-free tests passed; all 404 PostgreSQL scenarios have passing evidence across the documented runs.
This commit is contained in:
@@ -0,0 +1,35 @@
|
||||
"""Execute the delivered HTTP helper; multipart boundaries stay browser-owned."""
|
||||
from pathlib import Path
|
||||
import shutil
|
||||
import subprocess
|
||||
|
||||
|
||||
def test_executable_document_http_handoff():
|
||||
node = shutil.which('node')
|
||||
assert node, 'Node is required for the executable frontend handoff check'
|
||||
source = Path('examples/document-client.js').read_text()
|
||||
script = '''
|
||||
import assert from 'node:assert/strict';
|
||||
const {DocumentClient} = await import('data:text/javascript;base64,' + Buffer.from(SOURCE).toString('base64'));
|
||||
const calls = [];
|
||||
globalThis.fetch = async (path, options) => {calls.push({path, options}); return {ok:true,json:async()=>({status:'queued'})};};
|
||||
const client = new DocumentClient({csrf:'session-csrf'});
|
||||
const file = new File(['original'], 'source.md');
|
||||
await client.upload(file, 'Source', 'stable-upload-key');
|
||||
assert.equal(calls[0].options.body.get('file').name, 'source.md');
|
||||
assert.equal(calls[0].options.headers['Content-Type'], undefined);
|
||||
assert.equal(calls[0].options.headers['Idempotency-Key'], 'stable-upload-key');
|
||||
assert.equal(calls[0].options.headers['X-CSRF-Token'], 'session-csrf');
|
||||
assert.equal(calls[0].options.credentials, 'same-origin');
|
||||
await client.retry('document-id', 'retry-key');
|
||||
assert.equal(calls[1].options.body, undefined);
|
||||
await client.replace(3, ['document-id']);
|
||||
assert.deepEqual(JSON.parse(calls[2].options.body), {expected_revision:3,document_ids:['document-id']});
|
||||
await client.review('document-id', 'digest');
|
||||
assert.equal(calls[3].path, '/api/v1/documents/document-id/extraction-review?cursor=digest');
|
||||
globalThis.fetch = async () => ({ok:false,status:409,json:async()=>({error:{code:'REVISION_CONFLICT',request_id:'correlation',details:{}}})});
|
||||
await assert.rejects(client.replace(1, []), {message:'REVISION_CONFLICT',requestID:'correlation'});
|
||||
'''
|
||||
import json
|
||||
result = subprocess.run([node, '--input-type=module', '-e', 'const SOURCE = ' + json.dumps(source) + ';\n' + script], capture_output=True, text=True, timeout=10)
|
||||
assert result.returncode == 0, result.stderr
|
||||
@@ -144,7 +144,7 @@ def test_operator_uses_configured_gemini_with_actual_runtime_tool(settings,monke
|
||||
await self.inbound.put({'serverContent':{'outputTranscription':{'text':'fixture answer'},'turnComplete':True}})
|
||||
wire=Scripted()
|
||||
async def connection(*args):return wire
|
||||
monkeypatch.setattr('app.infrastructure.gemini_live.connect_gemini',connection)
|
||||
monkeypatch.setattr('app.infrastructure.voice_provider.connect_gemini',connection)
|
||||
config=VoiceSettings(_env_file=None,gemini_api_key='fake-only',gemini_model='configured-model')
|
||||
service=canonical_service(settings,monkeypatch,[row()])
|
||||
assert asyncio.run(voice_smoke.run(service,runner,uuid4(),config,'q',3,4))==0
|
||||
|
||||
@@ -45,7 +45,7 @@ def test_complete_ordered_native_conversion_and_prompt(profile, monkeypatch):
|
||||
assert body["generationConfig"]["responseMimeType"] == "application/json"
|
||||
|
||||
|
||||
@pytest.mark.parametrize("change", ["alias", "missing_model", "truncated", "empty", "incomplete", "warnings", "unreadable", "wrong_page", "wrong_method", "wrong_block_model"])
|
||||
@pytest.mark.parametrize("change", ["alias", "missing_model", "truncated", "empty", "wrong_page", "wrong_method", "wrong_block_model"])
|
||||
def test_invalid_native_response_fails_safely(profile, monkeypatch, change):
|
||||
value = native(profile)
|
||||
if change == "alias":
|
||||
|
||||
@@ -0,0 +1,131 @@
|
||||
"""Deterministic source/review and uncalibrated admission regressions."""
|
||||
import hashlib
|
||||
import json
|
||||
from uuid import uuid4
|
||||
import pytest
|
||||
from app.modules.documents.extraction import PageBlockExtractor, ReviewRequired
|
||||
from app.modules.documents.chunking import factual_review_blocks
|
||||
from app.modules.documents.review import prepare_chunks, FactualReviewRequired
|
||||
from tests.unit.test_phase5_repairs import factual
|
||||
from tests.unit.test_gemini_vision import native, run
|
||||
from tests.support.formats import docx_bytes, image_bytes
|
||||
from tests.support.extraction import FakeVision
|
||||
|
||||
@pytest.mark.parametrize('heading', ['', '# Benefits\n'])
|
||||
def test_initial_context_is_shared_and_requires_independent_factual_approval(settings, heading):
|
||||
content = 'Benefits title\nOnly permanent employees; except contractors.\n' + heading
|
||||
content += ''.join(f'Question: allowance {i}?\nAnswer: {i}% unless excluded.\n' for i in range(100))
|
||||
raw, profile, envelope, state = factual(content, settings)
|
||||
assert ''.join(b.text for b in envelope.blocks).encode() == raw
|
||||
assert factual_review_blocks(envelope) == envelope.blocks
|
||||
with pytest.raises(FactualReviewRequired):
|
||||
prepare_chunks(envelope, profile, {}, 'a'*64)
|
||||
chunks = prepare_chunks(envelope, profile, state, 'a'*64)
|
||||
assert len(chunks) == 100
|
||||
for i, chunk in enumerate(chunks):
|
||||
assert 'Benefits title' in chunk.text and 'except contractors' in chunk.text
|
||||
assert f'allowance {i}?' in chunk.text and f'{i}% unless excluded' in chunk.text
|
||||
assert envelope.blocks[0].source_locator in chunk.section
|
||||
|
||||
|
||||
def test_unstyled_word_title_preserves_all_pairs(settings):
|
||||
paragraphs = ['Unstyled FAQ title', 'Question: rate?', 'Answer: 5%.', 'Question: leave?', 'Answer: 10 days.']
|
||||
xml = '<w:document xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main"><w:body>'
|
||||
xml += ''.join('<w:p><w:r><w:t>'+p+'</w:t></w:r></w:p>' for p in paragraphs)
|
||||
content = docx_bytes(document=(xml+'</w:body></w:document>').encode())
|
||||
envelope = PageBlockExtractor().extract_for_review(document_id=uuid4(), title='FAQ',
|
||||
original_sha256=hashlib.sha256(content).hexdigest(), content=content,
|
||||
mime_type='application/vnd.openxmlformats-officedocument.wordprocessingml.document',
|
||||
processing_profile=settings.processing_profile())
|
||||
units = factual_review_blocks(envelope)
|
||||
assert units == envelope.blocks and len([b for b in units if b.block_type == 'question']) == 2
|
||||
|
||||
|
||||
@pytest.mark.parametrize('provider', ['gemini', 'openrouter'])
|
||||
@pytest.mark.parametrize('diagnostic', ['incomplete', 'warning', 'region'])
|
||||
def test_native_recognition_diagnostics_preserve_candidate_and_force_review(settings, monkeypatch, provider, diagnostic):
|
||||
profile = settings.model_copy(update={'ocr_review_required': False, 'vision_provider': provider,
|
||||
'vision_endpoint': 'https://example.invalid/v1beta', 'vision_model': 'fixture-flash'}).processing_profile()
|
||||
payload = native(profile)
|
||||
transcript = json.loads(payload['candidates'][0]['content']['parts'][0]['text'])
|
||||
if diagnostic == 'incomplete': transcript['complete'] = False
|
||||
if diagnostic == 'warning': transcript['warnings'] = ['Uncertain order']
|
||||
if diagnostic == 'region': transcript['blocks'][1]['warnings'] = ['unreadable margin']
|
||||
text = json.dumps(transcript)
|
||||
if provider == 'gemini':
|
||||
payload['candidates'][0]['content']['parts'][0]['text'] = text
|
||||
blocks = run(profile, payload, monkeypatch)
|
||||
else:
|
||||
from io import BytesIO
|
||||
from app.infrastructure.openrouter_vision import OpenRouterVision
|
||||
class Opener:
|
||||
def open(self, request, *, timeout):
|
||||
return BytesIO(json.dumps({'choices':[{'message':{'content':text}}]}).encode())
|
||||
monkeypatch.setattr('app.infrastructure.openrouter_vision.build_opener', lambda *a: Opener())
|
||||
blocks = OpenRouterVision(endpoint='https://example.invalid/v1beta',model='fixture-flash',
|
||||
api_key='fixture-only', timeout_seconds=60).transcribe(image_bytes(), page=None, section='image', processing_profile=profile)
|
||||
assert [b.text for b in blocks] == [b['text'] for b in transcript['blocks']]
|
||||
assert any(b.warnings for b in blocks)
|
||||
class RetainedVision:
|
||||
def transcribe(self, *args, **kw): return blocks
|
||||
raw = image_bytes('PNG')
|
||||
with pytest.raises(ReviewRequired) as pending:
|
||||
PageBlockExtractor(RetainedVision()).extract_for_review(document_id=uuid4(),title='Image',
|
||||
original_sha256=hashlib.sha256(raw).hexdigest(),content=raw,mime_type='image/png', processing_profile=profile)
|
||||
assert tuple(pending.value.blocks) == blocks
|
||||
|
||||
|
||||
def test_pending_calibration_is_opt_in_transport_policy(settings, monkeypatch, tmp_path):
|
||||
from app.api.v1 import live
|
||||
from app.modules.voice.configuration import VoiceSettings
|
||||
monkeypatch.setattr(live, 'IngestionSettings', lambda: settings.model_copy(update={'embedding_api_key': 'fixture'}))
|
||||
report = tmp_path/'pending.json'; report.write_text(json.dumps({'status':'pending','cutoff':None}))
|
||||
config = VoiceSettings(_env_file=None,gemini_api_key='fixture',search_calibration_report=report)
|
||||
with pytest.raises(ValueError, match='CALIBRATION_REQUIRED'): live.capability(config)
|
||||
assert live.capability(config.model_copy(update={'voice_transport_testing':True})) is None
|
||||
assert live.search_profile(None, settings)['calibration_status'] == 'uncalibrated'
|
||||
assert 'distance' not in live.search_profile(None, settings)
|
||||
|
||||
@pytest.mark.parametrize('testing',[False,True])
|
||||
def test_search_dependency_pending_report_keeps_calibration_gate(settings,monkeypatch,tmp_path,testing):
|
||||
from app.api.v1 import dependencies as d
|
||||
from app.modules.voice.configuration import VoiceSettings
|
||||
from app.modules.knowledge.evidence import SearchExecution
|
||||
from fastapi import HTTPException
|
||||
report=tmp_path/'pending.json'; report.write_text(json.dumps({'status':'pending','cutoff':None}))
|
||||
config=VoiceSettings(_env_file=None,search_calibration_report=report,voice_transport_testing=testing)
|
||||
monkeypatch.setattr(d,'VoiceSettings',lambda:config)
|
||||
monkeypatch.setattr(d,'IngestionSettings',lambda:settings)
|
||||
monkeypatch.setattr(d,'_SEARCH_SERVICE',None)
|
||||
constructions=[]
|
||||
def provider(profile):
|
||||
constructions.append(profile)
|
||||
return object(),None
|
||||
monkeypatch.setattr('app.worker.factories',lambda settings:(None,provider))
|
||||
if not testing:
|
||||
with pytest.raises(HTTPException) as error: d.get_search_service(object())
|
||||
assert error.value.status_code==503 and constructions==[]
|
||||
else:
|
||||
service=d.get_search_service(object())
|
||||
assert service.cutoff is None and len(constructions)==1
|
||||
result=service.search(SearchExecution(uuid4()),'source question')
|
||||
assert result['sources']==[] and result['error']['code']=='CALIBRATION_REQUIRED'
|
||||
|
||||
|
||||
@pytest.mark.parametrize('failure',['invalid_json','empty','truncated','unreadable_text'])
|
||||
def test_openrouter_fatal_output_stays_fatal(settings,monkeypatch,failure):
|
||||
from io import BytesIO
|
||||
from app.infrastructure.openrouter_vision import OpenRouterVision
|
||||
from app.modules.documents.extraction import ExtractionError
|
||||
profile=settings.model_copy(update={'vision_provider':'openrouter','vision_endpoint':'https://example.invalid/v1beta','vision_model':'fixture-flash'}).processing_profile()
|
||||
blocks=FakeVision().transcribe(b'',page=None,section='image',processing_profile=profile)
|
||||
transcript={'complete':True,'warnings':[],'blocks':[b.model_dump(mode='json') for b in blocks]}
|
||||
if failure=='empty': transcript['blocks']=[]
|
||||
if failure=='unreadable_text': transcript['blocks'][1]['text']='\ufffd'
|
||||
content='broken json' if failure=='invalid_json' else json.dumps(transcript)
|
||||
value={'choices':[{'finish_reason':'length' if failure=='truncated' else 'stop','message':{'content':content}}]}
|
||||
class Opener:
|
||||
def open(self,request,*,timeout): return BytesIO(json.dumps(value).encode())
|
||||
monkeypatch.setattr('app.infrastructure.openrouter_vision.build_opener',lambda *a:Opener())
|
||||
with pytest.raises(ExtractionError):
|
||||
OpenRouterVision(endpoint='https://example.invalid/v1beta',model='fixture-flash',api_key='fixture',timeout_seconds=60).transcribe(image_bytes(),page=None,section='image',processing_profile=profile)
|
||||
@@ -0,0 +1,177 @@
|
||||
"""Actual escaped JSON/GIL isolation, admission and resource ownership."""
|
||||
import asyncio
|
||||
import json
|
||||
from pathlib import Path
|
||||
from threading import BoundedSemaphore, Event
|
||||
import time
|
||||
|
||||
import pytest
|
||||
from fastapi import HTTPException
|
||||
from app.api.v1 import dependencies as deps
|
||||
from app.infrastructure import json_processing as processing
|
||||
from app.modules.documents.review import ReviewDecision
|
||||
|
||||
|
||||
def decision_bytes(count):
|
||||
groups = tuple(str(i).zfill(5) + '😀' * 495 for i in range(count))
|
||||
payload = dict(evidence_sha256='a'*64, decision='approve', checked=['factual_authority'],
|
||||
note='😀'*2000, excluded_group_ids=groups)
|
||||
return json.dumps(payload, ensure_ascii=True, separators=(',', ':')).encode(), groups
|
||||
|
||||
|
||||
class Request:
|
||||
headers = {}
|
||||
def __init__(self, raw):
|
||||
self.raw = raw
|
||||
async def stream(self):
|
||||
for start in range(0, len(self.raw), processing.INLINE_BYTES):
|
||||
yield self.raw[start:start + processing.INLINE_BYTES]
|
||||
await asyncio.sleep(0)
|
||||
|
||||
|
||||
@pytest.mark.parametrize('count', [4499, 10000])
|
||||
def test_real_large_escaped_json_keeps_concurrent_loop_active(count):
|
||||
raw, groups = decision_bytes(count)
|
||||
assert 26_000_000 < len(raw) < deps.MAX_DECISION_BYTES
|
||||
async def run():
|
||||
gaps, done = [], asyncio.Event()
|
||||
async def heartbeat():
|
||||
previous = time.monotonic()
|
||||
while not done.is_set():
|
||||
await asyncio.sleep(.01)
|
||||
now = time.monotonic()
|
||||
gaps.append(now - previous)
|
||||
previous = now
|
||||
tick = asyncio.create_task(heartbeat())
|
||||
await asyncio.sleep(0)
|
||||
start = time.monotonic()
|
||||
try:
|
||||
result = await deps.receive_json(Request(raw), ReviewDecision, deps.MAX_DECISION_BYTES)
|
||||
assert result.excluded_group_ids == groups
|
||||
assert result.note == '😀'*2000
|
||||
assert result.model_fields_set == {'evidence_sha256', 'decision', 'checked', 'note', 'excluded_group_ids'}
|
||||
await asyncio.sleep(.01)
|
||||
finally:
|
||||
done.set()
|
||||
await tick
|
||||
print(f'JSON_RESPONSIVENESS bytes={len(raw)} elapsed_ms={(time.monotonic()-start)*1000:.2f} '
|
||||
f'ticks={len(gaps)} max_gap_ms={max(gaps)*1000:.2f}')
|
||||
# Actual decode/loads/validation + result transfer, not a sleeping mock.
|
||||
# The old 187/561 ms stalls exceed this bound; all processing is covered.
|
||||
assert len(gaps) >= 5
|
||||
assert max(gaps) < .1
|
||||
asyncio.run(run())
|
||||
|
||||
|
||||
@pytest.mark.parametrize('stop', ['cancel', 'timeout'])
|
||||
def test_admission_retained_until_cancelled_disk_work_and_spool_release(monkeypatch, stop):
|
||||
slots = BoundedSemaphore(1)
|
||||
monkeypatch.setattr(deps, 'JSON_SLOTS', slots)
|
||||
entered, release = Event(), Event()
|
||||
paths = []
|
||||
original = deps.owned_io
|
||||
async def disk(function, *args):
|
||||
if function.__name__ == 'write' and not entered.is_set():
|
||||
paths.append(Path(function.__self__.name).parent)
|
||||
def blocked():
|
||||
entered.set()
|
||||
assert release.wait(3)
|
||||
return function(*args)
|
||||
return await original(blocked)
|
||||
return await original(function, *args)
|
||||
monkeypatch.setattr(deps, 'owned_io', disk)
|
||||
raw, _ = decision_bytes(100)
|
||||
async def run():
|
||||
task = asyncio.create_task(deps.receive_json(Request(raw), ReviewDecision, deps.MAX_DECISION_BYTES,
|
||||
timeout_seconds=.05 if stop == 'timeout' else 3))
|
||||
try:
|
||||
assert await asyncio.to_thread(entered.wait, 1)
|
||||
if stop == 'cancel':
|
||||
task.cancel()
|
||||
with pytest.raises(asyncio.CancelledError): await task
|
||||
else:
|
||||
with pytest.raises(HTTPException) as exc: await task
|
||||
assert exc.value.status_code == 503
|
||||
with pytest.raises(HTTPException) as exc:
|
||||
await deps.receive_json(Request(b'{}'), ReviewDecision, deps.MAX_DECISION_BYTES)
|
||||
assert exc.value.status_code == 429 and paths[0].exists()
|
||||
finally:
|
||||
release.set()
|
||||
async with asyncio.timeout(2):
|
||||
while not slots.acquire(blocking=False): await asyncio.sleep(.001)
|
||||
slots.release()
|
||||
assert not paths[0].exists()
|
||||
asyncio.run(run())
|
||||
|
||||
|
||||
def test_cancel_during_child_creation_reaps_child_before_releasing_admission(monkeypatch):
|
||||
slots = BoundedSemaphore(1)
|
||||
monkeypatch.setattr(deps, 'JSON_SLOTS', slots)
|
||||
original = processing.asyncio.create_subprocess_exec
|
||||
children = []
|
||||
async def run():
|
||||
entered, release = asyncio.Event(), asyncio.Event()
|
||||
async def spawn(*args, **kwargs):
|
||||
child = await original(*args, **kwargs)
|
||||
children.append(child)
|
||||
entered.set()
|
||||
await release.wait()
|
||||
return child
|
||||
monkeypatch.setattr(processing.asyncio, 'create_subprocess_exec', spawn)
|
||||
raw, _ = decision_bytes(100)
|
||||
task = asyncio.create_task(deps.receive_json(Request(raw), ReviewDecision, deps.MAX_DECISION_BYTES))
|
||||
await asyncio.wait_for(entered.wait(), 2)
|
||||
task.cancel()
|
||||
with pytest.raises(asyncio.CancelledError): await task
|
||||
await asyncio.sleep(0)
|
||||
assert not slots.acquire(blocking=False)
|
||||
release.set()
|
||||
async with asyncio.timeout(2):
|
||||
while not slots.acquire(blocking=False): await asyncio.sleep(.001)
|
||||
slots.release()
|
||||
assert children[0].returncode is not None
|
||||
asyncio.run(run())
|
||||
|
||||
|
||||
@pytest.mark.parametrize('raw', [b'{"bad":' + b' '*70000, b'\xff'*70000,
|
||||
b'{"note":"' + b'x'*70000 + b'"}'],
|
||||
ids=["malformed-json", "invalid-utf8", "invalid-dto"])
|
||||
def test_large_malformed_or_invalid_dto_is_safe(raw):
|
||||
with pytest.raises(HTTPException) as exc:
|
||||
asyncio.run(deps.receive_json(Request(raw), ReviewDecision, deps.MAX_DECISION_BYTES))
|
||||
assert exc.value.status_code == 422 and exc.value.detail['code'] == 'VALIDATION_ERROR'
|
||||
|
||||
|
||||
def test_cancelled_decision_keeps_normalized_dto_admitted_until_transaction_finishes(monkeypatch):
|
||||
from app.api.v1 import documents
|
||||
from fastapi import Response
|
||||
from types import SimpleNamespace
|
||||
from uuid import uuid4
|
||||
slots = BoundedSemaphore(1)
|
||||
monkeypatch.setattr(documents, '_DECISION_SLOTS', slots)
|
||||
entered, release, finished = Event(), Event(), Event()
|
||||
def commit(*args, **kwargs):
|
||||
entered.set()
|
||||
assert release.wait(3)
|
||||
finished.set()
|
||||
return {'decision': 'approve'}
|
||||
services = SimpleNamespace(review=SimpleNamespace(decide=commit))
|
||||
user = SimpleNamespace(id=uuid4(), organization_id=uuid4())
|
||||
raw, _ = decision_bytes(1)
|
||||
async def call():
|
||||
return await documents.decide(uuid4(), Request(raw), Response(), user, services, uuid4(), None)
|
||||
async def run():
|
||||
task = asyncio.create_task(call())
|
||||
try:
|
||||
assert await asyncio.to_thread(entered.wait, 1)
|
||||
task.cancel()
|
||||
with pytest.raises(asyncio.CancelledError): await task
|
||||
with pytest.raises(HTTPException) as exc: await call()
|
||||
assert exc.value.status_code == 429 and not finished.is_set()
|
||||
finally:
|
||||
release.set()
|
||||
assert await asyncio.to_thread(finished.wait, 1)
|
||||
async with asyncio.timeout(1):
|
||||
while not slots.acquire(blocking=False): await asyncio.sleep(.001)
|
||||
slots.release()
|
||||
asyncio.run(run())
|
||||
@@ -0,0 +1,92 @@
|
||||
"""Frozen OCR admission: automatic validation, legacy policy and non-OCR gates."""
|
||||
import hashlib
|
||||
from uuid import uuid4
|
||||
import pytest
|
||||
from app.modules.documents.extraction import PageBlockExtractor, ReviewRequired, ExtractionError
|
||||
from app.modules.documents.worker import validate_source
|
||||
from app.modules.documents.extraction_artifacts import ocr_review_required
|
||||
from app.modules.documents.review import prepare_chunks, FactualReviewRequired
|
||||
from tests.support.extraction import FakeVision, pdf_bytes
|
||||
from tests.support.formats import image_bytes
|
||||
|
||||
|
||||
def profile(settings, required):
|
||||
value = settings.model_copy(update={'ocr_review_required': required}).processing_profile()
|
||||
value['extraction']['vision'] = dict(provider='gemini', endpoint='https://test.invalid', model='fixture-flash', timeout_seconds=5)
|
||||
return value
|
||||
|
||||
|
||||
@pytest.mark.parametrize('kind', ['png', 'jpeg', 'scan'])
|
||||
@pytest.mark.parametrize('required', [True, False, None])
|
||||
def test_ocr_gate_and_worker_source_validation(settings, kind, required):
|
||||
frozen = profile(settings, required is not False)
|
||||
if required is None:
|
||||
frozen['extraction'].pop('ocr_review_required')
|
||||
content = image_bytes('JPEG' if kind == 'jpeg' else 'PNG')
|
||||
mime = 'image/jpeg' if kind == 'jpeg' else 'image/png'
|
||||
if kind == 'scan':
|
||||
content = pdf_bytes([[('image', content, 10, 20)]])
|
||||
mime = 'application/pdf'
|
||||
doc = dict(id=uuid4(), title='OCR', file_sha256=hashlib.sha256(content).hexdigest(), processing_profile=frozen, mime_type=mime)
|
||||
kwargs = dict(document_id=doc['id'], title=doc['title'], original_sha256=doc['file_sha256'], content=content, mime_type=mime, processing_profile=frozen)
|
||||
if required is not False:
|
||||
with pytest.raises(ReviewRequired):
|
||||
PageBlockExtractor(FakeVision()).extract_for_review(**kwargs)
|
||||
else:
|
||||
envelope = PageBlockExtractor(FakeVision()).extract_for_review(**kwargs)
|
||||
assert envelope.quality_decision == 'passed' and not envelope.review_annotations
|
||||
validate_source(envelope, doc, content)
|
||||
legacy = dict(frozen, extraction={k: v for k, v in frozen['extraction'].items() if k != 'ocr_review_required'})
|
||||
with pytest.raises(ExtractionError):
|
||||
validate_source(envelope, dict(doc, processing_profile=legacy), content)
|
||||
|
||||
|
||||
@pytest.mark.parametrize('warning', ['Uncertain order', 'unreadable region', 'ناخوانا'])
|
||||
def test_disabling_supervisor_preserves_quality_failures(settings, warning):
|
||||
frozen = profile(settings, False)
|
||||
content = image_bytes('PNG')
|
||||
with pytest.raises(ReviewRequired):
|
||||
PageBlockExtractor(FakeVision(warnings=(warning,))).extract_for_review(document_id=uuid4(), title='OCR',
|
||||
original_sha256=hashlib.sha256(content).hexdigest(), content=content, mime_type='image/png', processing_profile=frozen)
|
||||
|
||||
|
||||
@pytest.mark.parametrize('text,model', [('', 'fixture-flash'), ('\ufffd', 'fixture-flash'), ('[TODO]', 'fixture-flash'), ('Evidence', 'wrong-model')])
|
||||
def test_automatic_validation_is_not_waived(settings, text, model):
|
||||
content = image_bytes('PNG')
|
||||
with pytest.raises(ValueError):
|
||||
PageBlockExtractor(FakeVision(text=text, actual_model=model)).extract_for_review(document_id=uuid4(), title='OCR',
|
||||
original_sha256=hashlib.sha256(content).hexdigest(), content=content, mime_type='image/png', processing_profile=profile(settings, False))
|
||||
|
||||
|
||||
def test_direct_pdf_still_needs_review(settings):
|
||||
content = pdf_bytes([[('text', 'Article 1: fee is 5%', 10, 20)]])
|
||||
with pytest.raises(ReviewRequired):
|
||||
PageBlockExtractor().extract_for_review(document_id=uuid4(), title='PDF', original_sha256=hashlib.sha256(content).hexdigest(),
|
||||
content=content, mime_type='application/pdf', processing_profile=profile(settings, False))
|
||||
|
||||
|
||||
def test_factual_approval_independent(settings):
|
||||
frozen = profile(settings, False)
|
||||
content = b'Question: fee?\nAnswer: 5%\n'
|
||||
envelope = PageBlockExtractor().extract_for_review(document_id=uuid4(), title='FAQ', original_sha256=hashlib.sha256(content).hexdigest(),
|
||||
content=content, mime_type='text/markdown', processing_profile=frozen)
|
||||
with pytest.raises(FactualReviewRequired):
|
||||
prepare_chunks(envelope, frozen, {}, 'a' * 64)
|
||||
|
||||
|
||||
@pytest.mark.parametrize('bad', [None, 'false', 0, 1, []])
|
||||
def test_invalid_snapshot_fails_closed(settings, bad):
|
||||
frozen = profile(settings, False); frozen['extraction']['ocr_review_required'] = bad
|
||||
with pytest.raises(ValueError):
|
||||
ocr_review_required(frozen)
|
||||
|
||||
|
||||
def test_setting_defaults_and_enqueue_snapshot(settings, monkeypatch):
|
||||
assert settings.ocr_review_required is True
|
||||
monkeypatch.setenv('INGEST_OCR_REVIEW_REQUIRED', 'false')
|
||||
values = settings.model_dump(); values.pop('ocr_review_required')
|
||||
configured = type(settings)(_env_file=None, **values)
|
||||
frozen = configured.processing_profile()
|
||||
monkeypatch.setenv('INGEST_OCR_REVIEW_REQUIRED', 'true')
|
||||
assert ocr_review_required(frozen) is False
|
||||
assert type(settings)(_env_file=None, **values).ocr_review_required is True
|
||||
@@ -19,7 +19,7 @@ def test_gemini_configuration_requires_no_openai_voice_key(monkeypatch):
|
||||
assert config.provider=='gemini' and config.profile()['model']=='intended-profile'
|
||||
assert 'fixture' not in repr(config)
|
||||
|
||||
@pytest.mark.parametrize('changes', [{'provider':'openai'},{'trusted_origins':['http://evil/path']},
|
||||
@pytest.mark.parametrize('changes', [{'provider':'unknown'},{'trusted_origins':['http://evil/path']},
|
||||
{'trusted_hosts':['*']},{'gemini_proxy':'https://user:secret@proxy'},
|
||||
{'trusted_origins':['https://prod.example'],'cookie_secure':False},{'live_session_seconds':0}])
|
||||
def test_invalid_configuration_fails_before_remote_setup(changes):
|
||||
|
||||
@@ -0,0 +1,157 @@
|
||||
"""Selected-provider construction, authority truthfulness and continuous idle admission."""
|
||||
import asyncio
|
||||
from types import SimpleNamespace
|
||||
from uuid import uuid4
|
||||
import pytest
|
||||
from sqlalchemy.exc import OperationalError
|
||||
from app.modules.voice.configuration import VoiceSettings
|
||||
from app.infrastructure import voice_provider
|
||||
from app.infrastructure.gemini_live import GeminiLiveAdapter
|
||||
from app.infrastructure.realtime import RealtimeAdapter
|
||||
from app.modules.voice.runtime import VoiceRuntime
|
||||
from app.modules.voice.settings import RuntimeSettings
|
||||
from tests.unit.test_gemini_live import FakeGoogleTransport, make, cleanup
|
||||
from tests.unit.test_realtime_phase1 import runner, persisted, until
|
||||
|
||||
@pytest.mark.parametrize('provider,adapter,rate', [('gemini',GeminiLiveAdapter,16000),('openai',RealtimeAdapter,24000)])
|
||||
def test_selected_credentials_factory_profile_and_native_audio(provider,adapter,rate,monkeypatch):
|
||||
config=VoiceSettings(_env_file=None,provider=provider,**{('gemini_api_key' if provider=='gemini' else 'openai_realtime_api_key'):'fake-only'})
|
||||
config.require_voice()
|
||||
with pytest.raises(ValueError,match='LIVE_PROVIDER_UNAVAILABLE'):
|
||||
VoiceSettings(_env_file=None,provider=provider).require_voice()
|
||||
wire=FakeGoogleTransport();seen=[]
|
||||
async def connect(*args):seen.append(args);return wire
|
||||
monkeypatch.setattr(voice_provider,'connect_'+provider,connect)
|
||||
async def scenario():
|
||||
selected=await voice_provider.create_adapter(config,RuntimeSettings())
|
||||
assert isinstance(selected,adapter)
|
||||
assert seen[0][:3]==('fake-only',config.selected_model,config.selected_proxy)
|
||||
assert config.profile()['input_sample_rate']==rate
|
||||
setup=selected.setup()
|
||||
if provider=='openai':
|
||||
assert setup['session']['audio']['input']['format']['rate']==24000
|
||||
await selected.send({'type':'input_audio_buffer.append','audio':'AAAA'})
|
||||
assert wire.sent[-1]['audio']=='AAAA'
|
||||
await selected.send({'type':'conversation.item.truncate','item_id':'private','content_index':0,'audio_end_ms':5})
|
||||
assert wire.sent[-1]['audio_end_ms']==5
|
||||
await selected.close();assert wire.closed==1
|
||||
asyncio.run(scenario())
|
||||
|
||||
def test_provider_alias_priority_conflicts_and_embedding_independence(monkeypatch,tmp_path):
|
||||
monkeypatch.setenv('PROVIDER','gemini');monkeypatch.setenv('VOICE_PROVIDER','gemini')
|
||||
monkeypatch.setenv('OPENAI_API_KEY','embedding-only')
|
||||
assert VoiceSettings(_env_file=None).provider=='gemini'
|
||||
assert VoiceSettings(_env_file=None,provider='openai').provider=='openai'
|
||||
monkeypatch.setenv('VOICE_PROVIDER','openai')
|
||||
with pytest.raises(ValueError,match='Conflicting'):VoiceSettings(_env_file=None)
|
||||
monkeypatch.delenv('PROVIDER')
|
||||
assert not VoiceSettings(_env_file=None).openai_realtime_api_key.get_secret_value()
|
||||
env=tmp_path/'.env';env.write_text('PROVIDER=gemini\n')
|
||||
with pytest.raises(ValueError,match='Conflicting'):VoiceSettings(_env_file=env)
|
||||
monkeypatch.delenv('VOICE_PROVIDER');assert VoiceSettings(_env_file=env).provider=='gemini'
|
||||
with pytest.raises(ValueError,match='Conflicting'):
|
||||
VoiceSettings(_env_file=None,VOICE_PROVIDER='openai',provider='gemini')
|
||||
|
||||
@pytest.mark.parametrize('exc,code',[(ValueError('SERVICE_BUSY'),'SEARCH_SATURATED'),
|
||||
(TimeoutError(),'SEARCH_TIMEOUT'),(OperationalError('select',{},Exception('private')),'DEPENDENCY_UNAVAILABLE'),
|
||||
(ValueError('SESSION_EXPIRED'),'CONTEXT_REVOKED'),(ValueError('SESSION_REVOKED'),'CONTEXT_REVOKED'),
|
||||
(ValueError('LIVE_SESSION_EXPIRED'),'CONTEXT_REVOKED'),
|
||||
(ValueError('ACCOUNT_DISABLED'),'CONTEXT_REVOKED'),
|
||||
(RuntimeError('private'),'DEPENDENCY_UNAVAILABLE')])
|
||||
def test_runtime_authority_failure_truthful_and_fail_closed(runner,exc,code):
|
||||
async def scenario():
|
||||
wire=FakeGoogleTransport();out=[]
|
||||
async def check(_):raise exc
|
||||
async def emit(e):out.append(e)
|
||||
r=VoiceRuntime(RealtimeAdapter(wire),SimpleNamespace(engine=None),runner,uuid4(),emit,authority_check=check)
|
||||
await r.start()
|
||||
assert not r.usable and r.failure==code and not wire.sent
|
||||
await r.close()
|
||||
assert all(not isinstance(e,bytes) for e in out)
|
||||
asyncio.run(scenario())
|
||||
|
||||
def test_actual_authority_check_deadline(runner):
|
||||
async def scenario():
|
||||
wire=FakeGoogleTransport()
|
||||
async def check(_):await asyncio.Event().wait()
|
||||
async def emit(_):pass
|
||||
limits=RuntimeSettings(_env_file=None,authority_timeout_seconds=.01)
|
||||
r=VoiceRuntime(RealtimeAdapter(wire,settings=limits),SimpleNamespace(engine=None),runner,uuid4(),emit,authority_check=check,settings=limits)
|
||||
await r.start();assert r.failure=='SEARCH_TIMEOUT';await r.close()
|
||||
asyncio.run(scenario())
|
||||
|
||||
def test_ten_seconds_continuous_uncommitted_silence_keeps_frozen_bound(runner,persisted):
|
||||
async def scenario():
|
||||
r,adapter,wire,out,receive=await make(SimpleNamespace(engine=None),runner,persisted)
|
||||
try:
|
||||
for _ in range(100):
|
||||
await r.input_audio(bytes(4800))
|
||||
await until(lambda:r.input_transport_count==0 or not r.usable)
|
||||
assert r.usable,r.failure
|
||||
assert r.input_dispatched_total==480000
|
||||
await r.input_audio(bytes(2))
|
||||
assert r.failure=='LIVE_BUFFER_OVERFLOW'
|
||||
assert not any('toolResponse' in m for m in wire.sent)
|
||||
finally:await cleanup(r,receive)
|
||||
asyncio.run(scenario())
|
||||
|
||||
|
||||
def test_selected_openai_actual_runtime_tool_audio_continuation_and_truncation(settings,monkeypatch,runner,persisted):
|
||||
from tests.unit.test_realtime_phase1 import input_turn,response,call,done,delta,commands
|
||||
from tests.unit.test_search_phase2 import service,row
|
||||
search=service(settings,monkeypatch,[row()]);wire=FakeGoogleTransport();out=[]
|
||||
async def connect(*_):return wire
|
||||
monkeypatch.setattr(voice_provider,'connect_openai',connect)
|
||||
async def scenario():
|
||||
config=VoiceSettings(_env_file=None,provider='openai',openai_realtime_api_key='fake-only')
|
||||
adapter=await voice_provider.create_adapter(config,RuntimeSettings())
|
||||
async def emit(e):out.append(e)
|
||||
async def authority(execution):return execution.capture(dict(id=execution.user_id,organization_id='fixture',role='user'),1)
|
||||
r=VoiceRuntime(adapter,search,runner,uuid4(),emit,authority_check=authority)
|
||||
try:
|
||||
await r.start();await until(lambda:commands(wire,'session.update'))
|
||||
assert not r.ready
|
||||
await r.handle({'type':'session.updated','session':adapter.setup()['session']});await until(lambda:r.ready)
|
||||
await input_turn(r);await response(r,wire)
|
||||
await r.handle(call());await done(r)
|
||||
await until(lambda:len(commands(wire,'response.create'))==2)
|
||||
result=commands(wire,'conversation.item.create')[0]['item']
|
||||
import json
|
||||
assert json.loads(result['output'])['status']=='ok'
|
||||
await response(r,wire,'r2');await r.handle(delta(960,response_id='r2',item_id='a2'))
|
||||
await until(lambda:any(isinstance(e,bytes) for e in out))
|
||||
started=next(e for e in out if isinstance(e,dict) and e['type']=='audio_started')
|
||||
await r.client_control(__import__('json').dumps(dict(type='playback_progress',audio_ref=started['audio_ref'],played_ms=5)).encode())
|
||||
await input_turn(r,item='u2',start=200)
|
||||
await until(lambda:commands(wire,'response.cancel'))
|
||||
await done(r,'r2',status='cancelled')
|
||||
await until(lambda:commands(wire,'conversation.item.truncate'))
|
||||
assert commands(wire,'conversation.item.truncate')[0]['audio_end_ms']==5
|
||||
assert r.usable,r.failure
|
||||
finally:await r.close()
|
||||
assert wire.closed==1
|
||||
asyncio.run(scenario())
|
||||
|
||||
@pytest.mark.parametrize('phase',['release','output'])
|
||||
@pytest.mark.parametrize('exc,code',[(ValueError('SERVICE_BUSY'),'SEARCH_SATURATED'),
|
||||
(TimeoutError(),'SEARCH_TIMEOUT'),(OperationalError('select',{},Exception('private')),'DEPENDENCY_UNAVAILABLE'),
|
||||
(ValueError('CONTEXT_REVOKED'),'CONTEXT_REVOKED')])
|
||||
def test_authority_failure_suppresses_response_release_and_output(phase,exc,code,runner,persisted):
|
||||
from tests.unit.test_realtime_phase1 import make as openai_make,input_turn,response,delta,commands
|
||||
async def scenario():
|
||||
r,wire,out=await openai_make(SimpleNamespace(engine=None),runner,persisted)
|
||||
try:
|
||||
async def unavailable(_):raise exc
|
||||
if phase=='release':
|
||||
r.authority_check=unavailable
|
||||
await input_turn(r)
|
||||
else:
|
||||
await input_turn(r);await response(r,wire)
|
||||
r.authority_check=unavailable
|
||||
await r.handle(delta(960))
|
||||
await asyncio.wait_for(r.failure_signal.wait(),2)
|
||||
assert r.failure==code
|
||||
assert not any(isinstance(e,bytes) or (isinstance(e,dict) and e.get('type') in ('transcript','sources','audio_started')) for e in out)
|
||||
if phase=='release':assert not commands(wire,'response.create')
|
||||
finally:await r.close()
|
||||
asyncio.run(scenario())
|
||||
@@ -154,9 +154,11 @@ def test_rejected_direct_reading_order_falls_back_without_guessing(profile):
|
||||
|
||||
|
||||
@pytest.mark.parametrize("warning", ["unreadable region/right/2", "ناخوانا: گروه 2"])
|
||||
def test_image_unreadable_regions_fail_before_chunks(profile, warning):
|
||||
with pytest.raises(ExtractionError, match="unreadable"):
|
||||
def test_image_region_warnings_retain_candidate_without_chunks(profile, warning):
|
||||
with pytest.raises(ReviewRequired) as pending:
|
||||
extract(image_bytes(), profile, "image/jpeg", vision=FakeVision(warnings=(warning,)))
|
||||
assert any(warning in b.warnings for b in pending.value.blocks)
|
||||
assert all(b.text.strip() for b in pending.value.blocks)
|
||||
|
||||
|
||||
def test_infographic_parent_children_and_order(profile):
|
||||
|
||||
@@ -0,0 +1,42 @@
|
||||
"""Framework preparation must precede live admission and tool deadlines."""
|
||||
import asyncio
|
||||
from threading import get_ident
|
||||
from types import SimpleNamespace
|
||||
|
||||
from app.main import lifespan
|
||||
from app.api.v1 import dependencies
|
||||
|
||||
|
||||
def test_framework_prepared_off_loop_before_reconciliation_and_readiness(monkeypatch):
|
||||
app = SimpleNamespace(state=SimpleNamespace(ready=False))
|
||||
order = []
|
||||
loop_thread = get_ident()
|
||||
prepare = dependencies.prepare_search_tools
|
||||
def framework():
|
||||
assert not app.state.ready and get_ident() != loop_thread
|
||||
prepare()
|
||||
order.append('framework')
|
||||
def reconcile():
|
||||
assert order == ['framework'] and not app.state.ready
|
||||
order.append('reconcile')
|
||||
monkeypatch.setattr(dependencies, 'prepare_search_tools', framework)
|
||||
monkeypatch.setattr(dependencies, 'get_engine', lambda: SimpleNamespace(dispose=lambda: order.append('dispose')))
|
||||
monkeypatch.setattr(dependencies, 'get_lifecycle_service', lambda engine: SimpleNamespace(reconcile_startup=reconcile))
|
||||
monkeypatch.setattr(dependencies, '_TOOL_RUNNER', None)
|
||||
async def run():
|
||||
async with lifespan(app):
|
||||
assert order == ['framework', 'reconcile'] and app.state.ready
|
||||
assert not app.state.ready and order[-1] == 'dispose'
|
||||
asyncio.run(run())
|
||||
|
||||
|
||||
def test_document_only_installation_keeps_framework_optional(monkeypatch):
|
||||
import builtins
|
||||
from app.modules.knowledge.langchain_tool import prepare_search_tools
|
||||
original = builtins.__import__
|
||||
def optional(name, *args, **kwargs):
|
||||
if name == 'langchain_core.tools':
|
||||
raise ModuleNotFoundError(name='langchain_core')
|
||||
return original(name, *args, **kwargs)
|
||||
monkeypatch.setattr(builtins, '__import__', optional)
|
||||
assert prepare_search_tools() is None
|
||||
@@ -0,0 +1,459 @@
|
||||
"""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()
|
||||
@@ -78,7 +78,6 @@ def test_excluded_pairs_and_exclusive_context_are_absent(settings):
|
||||
|
||||
|
||||
@pytest.mark.parametrize("content", [
|
||||
"These answers apply only to permanent employees.\nQuestion: fee?\nAnswer: 5%.\n",
|
||||
"## Eligibility\nQuestion: fee?\nAnswer: 5%.\n## Exceptions\nContractors are not eligible.\n",
|
||||
"Question: fee?\nAnswer: 5%.\nArticle 2\nOnly permanent employees.\nQuestion: leave?\nAnswer: 10.\n",
|
||||
])
|
||||
@@ -157,8 +156,7 @@ def test_resume_keeps_note_once_as_bounded_metadata(settings, note):
|
||||
decision["note"] = "x" * 2001
|
||||
with pytest.raises(ValueError):
|
||||
PageBlockExtractor(vision).extract_for_review(retained=lambda _: (body, decision), **kwargs)
|
||||
body["blocks"][0]["warnings"] = ["unreadable source region"]
|
||||
body["blocks"][0]["text"] = "\ufffd"
|
||||
decision["note"] = note
|
||||
broken = PageBlockExtractor(vision).extract_for_review(retained=lambda _: (body, decision), **kwargs)
|
||||
with pytest.raises(ExtractionError, match="Unreadable"):
|
||||
validate_source(broken, dict(title="review", mime_type="image/png", processing_profile=profile), raw)
|
||||
PageBlockExtractor(vision).extract_for_review(retained=lambda _: (body, decision), **kwargs)
|
||||
|
||||
@@ -33,6 +33,8 @@ class Transport:
|
||||
|
||||
@pytest.fixture
|
||||
def runner():
|
||||
# Match API startup: framework imports precede voice/tool deadlines.
|
||||
boundary.prepare_search_tools()
|
||||
value = boundary.SearchToolRunner(running=2, waiting=2, timeout=2)
|
||||
yield value
|
||||
value.close()
|
||||
@@ -711,7 +713,7 @@ def test_new_speech_during_normal_tail_cleanup_preserves_completion(runner, pers
|
||||
@pytest.mark.parametrize("rows,status", [([row()], "ok"), ([], "no_evidence")])
|
||||
def test_operator_harness_actual_fake_transport_tool_correlation(
|
||||
settings, monkeypatch, runner, persisted, capsys, rows, status):
|
||||
from pydantic import SecretStr
|
||||
from app.modules.voice.configuration import VoiceSettings
|
||||
from app import voice_smoke
|
||||
from app.modules.voice import runtime as runtime_module
|
||||
service = canonical_service(settings, monkeypatch, rows)
|
||||
@@ -742,11 +744,10 @@ def test_operator_harness_actual_fake_transport_tool_correlation(
|
||||
response_id=rid, item_id="a_" + rid, output_index=0, content_index=0, transcript="Provider-supplied fixture answer")))
|
||||
await self.incoming.put(canonical_json(terminal(rid, output=output)))
|
||||
transport = Scripted()
|
||||
async def connection(config, limits):
|
||||
return RealtimeAdapter(transport, settings=limits)
|
||||
monkeypatch.setattr(voice_smoke, "create_adapter", connection)
|
||||
config = SimpleNamespace(openai_api_key=SecretStr("fixture-not-a-key"),
|
||||
openai_realtime_model="gpt-realtime-mini", openai_proxy=None)
|
||||
async def connection(*args):
|
||||
return transport
|
||||
monkeypatch.setattr("app.infrastructure.voice_provider.connect_openai", connection)
|
||||
config = VoiceSettings(_env_file=None, provider="openai", openai_realtime_api_key="fake-only")
|
||||
assert asyncio.run(voice_smoke.run(service, runner, uuid4(), config, "q", 3, 4)) == 0
|
||||
logs = [json.loads(line) for line in capsys.readouterr().out.splitlines()]
|
||||
correlation = next(e for e in logs if e["type"] == "smoke_correlation")
|
||||
|
||||
@@ -0,0 +1,129 @@
|
||||
"""Actual parser callbacks and ASGI receive admission, including cancellation cleanup."""
|
||||
import asyncio
|
||||
from pathlib import Path
|
||||
import tempfile
|
||||
from types import SimpleNamespace
|
||||
import pytest
|
||||
from app.api.v1.uploads import receive_upload
|
||||
from app.modules.documents.errors import IntakeError
|
||||
|
||||
|
||||
def multipart(parts, end=True):
|
||||
body = b''
|
||||
for name, value, filename in parts:
|
||||
disposition = f'Content-Disposition: form-data; name="{name}"'
|
||||
if filename is not None:
|
||||
disposition += f'; filename="{filename}"'
|
||||
body += b'--boundary\r\n' + disposition.encode() + b'\r\n\r\n' + value + b'\r\n'
|
||||
return body + (b'--boundary--\r\n' if end else b'')
|
||||
|
||||
|
||||
class Request:
|
||||
headers = {'content-type': 'multipart/form-data; boundary=boundary'}
|
||||
def __init__(self, body, size=7, cancel=False):
|
||||
self.body, self.size, self.cancel = body, size, cancel
|
||||
async def stream(self):
|
||||
for index in range(0, len(self.body), self.size):
|
||||
yield self.body[index:index + self.size]
|
||||
if self.cancel:
|
||||
raise asyncio.CancelledError()
|
||||
|
||||
|
||||
def test_streamed_upload_and_cleanup(settings):
|
||||
async def run():
|
||||
request = Request(multipart([('title', 'سند'.encode(), None), ('file', b'content', 'source.md')]))
|
||||
async with receive_upload(request, settings) as (path, filename, title):
|
||||
assert title == 'سند' and filename == 'source.md' and path.name == 'payload' and path.read_bytes() == b'content'
|
||||
parent = path.parent
|
||||
assert not parent.exists()
|
||||
asyncio.run(run())
|
||||
|
||||
|
||||
def test_unicode_filename_exceeding_filesystem_limit(settings):
|
||||
async def run():
|
||||
name = 'س' * 128 + '.md'
|
||||
assert len(name.encode('utf-8')) > 255 # Exceeds Linux NAME_MAX (255 bytes)
|
||||
assert len(name) <= 255 # Within display character length limit
|
||||
request = Request(multipart([('file', b'# content', name)]))
|
||||
async with receive_upload(request, settings) as (path, filename, title):
|
||||
assert filename == name and path.name == 'payload' and path.read_bytes() == b'# content'
|
||||
assert title is None
|
||||
parent = path.parent
|
||||
assert not parent.exists()
|
||||
asyncio.run(run())
|
||||
|
||||
|
||||
def test_display_filename_character_boundary(settings):
|
||||
async def run():
|
||||
# Exactly 255 display characters
|
||||
name_255 = 'س' * 252 + '.md'
|
||||
assert len(name_255) == 255
|
||||
async with receive_upload(Request(multipart([('file', b'# ok', name_255)])), settings) as (path, filename, title):
|
||||
assert filename == name_255 and path.name == 'payload'
|
||||
|
||||
# 256 display characters exceeds limit
|
||||
name_256 = 'س' * 253 + '.md'
|
||||
assert len(name_256) == 256
|
||||
with pytest.raises(IntakeError) as exc:
|
||||
async with receive_upload(Request(multipart([('file', b'# fail', name_256)])), settings):
|
||||
pytest.fail('256-char filename accepted')
|
||||
assert exc.value.code == 'INVALID_FILE'
|
||||
asyncio.run(run())
|
||||
|
||||
|
||||
@pytest.mark.parametrize('parts,end,code', [
|
||||
([('file', b'x' * 21, 'a.md')], True, 'FILE_TOO_LARGE'),
|
||||
([('title', b'x' * 801, None), ('file', b'a', 'a.md')], True, 'INVALID_FILE'),
|
||||
([('file', b'a', 'a.md'), ('file', b'b', 'b.md')], True, 'INVALID_FILE'),
|
||||
([('file', b'a', '../a.md')], True, 'INVALID_FILE'),
|
||||
([('scope', b'forged', None)], True, 'INVALID_FILE'),
|
||||
([('file', b'a', 'a.md')], False, 'INVALID_FILE'),
|
||||
([('title', b'a', None)], True, 'INVALID_FILE'),
|
||||
([('file', b'a', 'a.md'), ('title', b'a', None), ('other', b'a', None)], True, 'INVALID_FILE'),
|
||||
])
|
||||
def test_rejection_cleans_spool(settings, monkeypatch, tmp_path, parts, end, code):
|
||||
monkeypatch.setattr(tempfile, 'tempdir', str(tmp_path))
|
||||
async def run():
|
||||
with pytest.raises(IntakeError) as exc:
|
||||
async with receive_upload(Request(multipart(parts, end)), settings.model_copy(update={'max_original_bytes': 20})):
|
||||
pytest.fail('Rejected upload reached intake')
|
||||
assert exc.value.code == code
|
||||
assert not list(tmp_path.iterdir())
|
||||
asyncio.run(run())
|
||||
|
||||
|
||||
def test_disconnect_cleans_spool(settings, monkeypatch, tmp_path):
|
||||
monkeypatch.setattr(tempfile, 'tempdir', str(tmp_path))
|
||||
async def run():
|
||||
with pytest.raises(asyncio.CancelledError):
|
||||
async with receive_upload(Request(multipart([('file', b'x', 'a.md')]), cancel=True), settings):
|
||||
pytest.fail('Cancelled upload reached intake')
|
||||
assert not list(tmp_path.iterdir())
|
||||
asyncio.run(run())
|
||||
|
||||
|
||||
def test_aggregate_bytes_rejected_before_parser(settings):
|
||||
async def run():
|
||||
with pytest.raises(IntakeError) as exc:
|
||||
async with receive_upload(Request(b'x' * 20000, size=20000), settings.model_copy(update={'max_original_bytes': 20})):
|
||||
pytest.fail('Oversized request admitted')
|
||||
assert exc.value.code == 'FILE_TOO_LARGE'
|
||||
asyncio.run(run())
|
||||
|
||||
|
||||
def test_stalled_receive_releases_spool_and_capacity(settings, monkeypatch, tmp_path):
|
||||
monkeypatch.setattr(tempfile, 'tempdir', str(tmp_path))
|
||||
monkeypatch.setattr('app.api.v1.uploads.UPLOAD_RECEIVE_SECONDS', .01)
|
||||
class Stalled(Request):
|
||||
async def stream(self):
|
||||
yield b'--boundary\r\n'
|
||||
await asyncio.Event().wait()
|
||||
async def run():
|
||||
with pytest.raises(IntakeError) as exc:
|
||||
async with receive_upload(Stalled(b''), settings):
|
||||
pytest.fail('Stalled body admitted')
|
||||
assert exc.value.code == 'DEPENDENCY_UNAVAILABLE' and not list(tmp_path.iterdir())
|
||||
async with receive_upload(Request(multipart([('file', b'x', 'a.md')])), settings):
|
||||
pass
|
||||
assert not list(tmp_path.iterdir())
|
||||
asyncio.run(run())
|
||||
@@ -41,3 +41,10 @@ def test_delivered_voice_client_async_ownership_errors_logout_and_close():
|
||||
if not node:pytest.fail('Node is required to exercise VoiceClient')
|
||||
result=subprocess.run([node,str(ROOT/'tests/support/voice_client_harness.mjs'),'unit'],capture_output=True,text=True,timeout=20)
|
||||
assert result.returncode==0,result.stdout+result.stderr
|
||||
|
||||
|
||||
def test_delivered_playback_bounds_and_creation_replay():
|
||||
node=shutil.which('node')
|
||||
if not node:pytest.fail('Node is required to exercise the delivered example')
|
||||
result=subprocess.run([node,str(ROOT/'tests/support/voice_phase2_repairs.mjs')],capture_output=True,text=True,timeout=20)
|
||||
assert result.returncode==0,result.stdout+result.stderr
|
||||
|
||||
@@ -0,0 +1,371 @@
|
||||
"""Real loopback transport: pre-payload rejection, fragments, compression and backlog."""
|
||||
import asyncio
|
||||
import base64
|
||||
import os
|
||||
import struct
|
||||
import pytest
|
||||
import uvicorn
|
||||
from websockets.asyncio.client import connect
|
||||
from websockets.exceptions import ConnectionClosed
|
||||
from app.modules.voice.runtime import RuntimeSettings
|
||||
from app.server import server_config
|
||||
|
||||
async def serve(scenario, settings=None):
|
||||
delivered=[]; gate=asyncio.Event();gate.set()
|
||||
async def app(scope,receive,send):
|
||||
assert scope['type']=='websocket'
|
||||
await receive();await send({'type':'websocket.accept'})
|
||||
while True:
|
||||
await gate.wait()
|
||||
message=await receive()
|
||||
if message['type']=='websocket.disconnect':return
|
||||
delivered.append(message)
|
||||
await send({'type':'websocket.send','text':'accepted'})
|
||||
server=uvicorn.Server(server_config(app,port=0,lifespan='off',log_level='error',settings=settings))
|
||||
task=asyncio.create_task(server.serve())
|
||||
try:
|
||||
async with asyncio.timeout(3):
|
||||
while not server.started:await asyncio.sleep(.001)
|
||||
port=server.servers[0].sockets[0].getsockname()[1]
|
||||
await scenario(port,delivered,gate,server)
|
||||
finally:
|
||||
gate.set();server.should_exit=True
|
||||
await asyncio.wait_for(task,5)
|
||||
|
||||
@pytest.mark.parametrize('binary', [False,True])
|
||||
def test_valid_and_fragmented_message_boundaries(binary):
|
||||
async def scenario(port,delivered,gate,server):
|
||||
async with connect(f'ws://127.0.0.1:{port}',compression=None,proxy=None) as ws:
|
||||
value=bytes(9600) if binary else 'é'*2048
|
||||
await ws.send(value);assert await ws.recv()=='accepted'
|
||||
await ws.send([value[:len(value)//2],value[len(value)//2:]])
|
||||
assert await ws.recv()=='accepted';assert len(delivered)==2
|
||||
assert delivered[-1]['bytes' if binary else 'text']==value
|
||||
asyncio.run(serve(scenario))
|
||||
|
||||
@pytest.mark.parametrize('binary,fragmented',[(False,False),(True,False),(False,True),(True,True)])
|
||||
def test_oversized_messages_are_never_delivered(binary,fragmented):
|
||||
async def scenario(port,delivered,gate,server):
|
||||
async with connect(f'ws://127.0.0.1:{port}',compression=None,proxy=None) as ws:
|
||||
value=bytes(9602) if binary else 'é'*2049
|
||||
await ws.send([value[:len(value)//2],value[len(value)//2:]] if fragmented else value)
|
||||
with pytest.raises(ConnectionClosed) as exc:await ws.recv()
|
||||
assert exc.value.rcvd.code==1009 and not delivered
|
||||
asyncio.run(serve(scenario))
|
||||
|
||||
@pytest.mark.parametrize('opcode,size,code',[(2,9601,1009),(1,4097,1009),(0x42,100,1002)])
|
||||
def test_header_only_rejection_precedes_payload_allocation(opcode,size,code):
|
||||
async def scenario(port,delivered,gate,server):
|
||||
reader,writer=await asyncio.open_connection('127.0.0.1',port)
|
||||
try:
|
||||
key=base64.b64encode(os.urandom(16)).decode()
|
||||
writer.write((f'GET / HTTP/1.1\r\nHost: 127.0.0.1:{port}\r\nUpgrade: websocket\r\nConnection: Upgrade\r\nSec-WebSocket-Key: {key}\r\nSec-WebSocket-Version: 13\r\nSec-WebSocket-Extensions: permessage-deflate\r\n\r\n').encode());await writer.drain()
|
||||
response=await reader.readuntil(b'\r\n\r\n')
|
||||
assert b'101 Switching Protocols' in response
|
||||
assert b'sec-websocket-extensions' not in response.lower()
|
||||
# No mask or payload is sent: rejection must occur from declared length/RSV alone.
|
||||
writer.write(bytes([0x80|opcode,0x80|126])+struct.pack('!H',size));await writer.drain()
|
||||
head=await asyncio.wait_for(reader.readexactly(2),1)
|
||||
assert head[0]==0x88
|
||||
payload=await reader.readexactly(head[1]&127)
|
||||
assert struct.unpack('!H',payload[:2])[0]==code and not delivered
|
||||
finally:writer.close();await writer.wait_closed()
|
||||
asyncio.run(serve(scenario))
|
||||
|
||||
def test_installed_backend_queue_is_bounded_and_compression_not_negotiated():
|
||||
async def scenario(port,delivered,gate,server):
|
||||
async with connect(f'ws://127.0.0.1:{port}',compression='deflate',proxy=None) as ws:
|
||||
assert not ws.protocol.extensions
|
||||
await ws.send(b'first');await ws.recv()
|
||||
gate.clear()
|
||||
# One ASGI receive may already be waiting; the remainder must backpressure.
|
||||
for _ in range(30):await ws.send(bytes(9600))
|
||||
await asyncio.sleep(.05)
|
||||
protocol=next(iter(server.server_state.connections))
|
||||
assert protocol.max_queue==8 and len(protocol.messages)<=8
|
||||
assert protocol.max_size==9600 and not protocol.extensions
|
||||
gate.set()
|
||||
for _ in range(30):assert await asyncio.wait_for(ws.recv(),2)=='accepted'
|
||||
assert len(delivered)==31
|
||||
asyncio.run(serve(scenario))
|
||||
|
||||
def test_bounded_fragment_reassembly_long_empty_and_tiny_sequences():
|
||||
async def scenario(port, delivered, gate, server):
|
||||
async with connect(f'ws://127.0.0.1:{port}', compression=None, proxy=None) as ws:
|
||||
# 20,001 empty continuation frames reassembled without unbounded metadata growth
|
||||
empty_chunks = [b''] * 20001
|
||||
await ws.send(empty_chunks)
|
||||
assert await ws.recv() == 'accepted'
|
||||
assert delivered[-1]['bytes'] == b''
|
||||
conn = next(iter(server.server_state.connections))
|
||||
assert conn.assembling_scratch is None
|
||||
|
||||
# Tiny fragment sequence exact boundary: 96 fragments of 100 bytes = 9600 bytes binary
|
||||
binary_chunks = [b'x' * 100] * 96
|
||||
await ws.send(binary_chunks)
|
||||
assert await ws.recv() == 'accepted'
|
||||
assert delivered[-1]['bytes'] == b'x' * 9600
|
||||
assert conn.assembling_scratch is None
|
||||
|
||||
# Tiny fragment sequence exact boundary: 64 fragments of 64 bytes = 4096 bytes UTF-8
|
||||
text_chunks = ['a' * 64] * 64
|
||||
await ws.send(text_chunks)
|
||||
assert await ws.recv() == 'accepted'
|
||||
assert delivered[-1]['text'] == 'a' * 4096
|
||||
assert conn.assembling_scratch is None
|
||||
asyncio.run(serve(scenario))
|
||||
|
||||
def test_interleaved_protocol_controls_during_fragmentation():
|
||||
async def scenario(port, delivered, gate, server):
|
||||
reader, writer = await asyncio.open_connection('127.0.0.1', port)
|
||||
try:
|
||||
key = base64.b64encode(os.urandom(16)).decode()
|
||||
writer.write((f'GET / HTTP/1.1\r\nHost: 127.0.0.1:{port}\r\nUpgrade: websocket\r\nConnection: Upgrade\r\nSec-WebSocket-Key: {key}\r\nSec-WebSocket-Version: 13\r\n\r\n').encode())
|
||||
await writer.drain()
|
||||
assert b'101 Switching Protocols' in await reader.readuntil(b'\r\n\r\n')
|
||||
|
||||
# Send fragment 1 (opcode 2, fin=0, data=b'first ')
|
||||
writer.write(bytes([0x02, 0x80 | 6, 0, 0, 0, 0]) + b'first ')
|
||||
await writer.drain()
|
||||
await asyncio.sleep(0.01)
|
||||
conn = next(iter(server.server_state.connections))
|
||||
assert conn.assembling_scratch == bytearray(b'first ')
|
||||
|
||||
# Client sends Ping control frame (opcode 9)
|
||||
writer.write(bytes([0x89, 0x80 | 4, 0, 0, 0, 0]) + b'ping')
|
||||
await writer.drain()
|
||||
|
||||
# Client receives Pong control frame (opcode 10)
|
||||
head = await asyncio.wait_for(reader.readexactly(2), 2)
|
||||
assert head[0] == 0x8A
|
||||
pong_len = head[1] & 127
|
||||
assert await reader.readexactly(pong_len) == b'ping'
|
||||
|
||||
# Send fragment 2 (opcode 0, fin=1, data=b'second')
|
||||
writer.write(bytes([0x80, 0x80 | 6, 0, 0, 0, 0]) + b'second')
|
||||
await writer.drain()
|
||||
|
||||
head = await asyncio.wait_for(reader.readexactly(2), 2)
|
||||
assert head[0] == 0x81
|
||||
reply = await reader.readexactly(head[1] & 127)
|
||||
assert reply == b'accepted'
|
||||
assert delivered[-1]['bytes'] == b'first second'
|
||||
assert conn.assembling_scratch is None
|
||||
finally:
|
||||
writer.close()
|
||||
await writer.wait_closed()
|
||||
asyncio.run(serve(scenario))
|
||||
|
||||
def test_malformed_fragmentation_sequences_and_resource_cleanup():
|
||||
async def scenario(port, delivered, gate, server):
|
||||
# 1. Unexpected continuation (opcode 0 without starting frame) -> 1002
|
||||
reader, writer = await asyncio.open_connection('127.0.0.1', port)
|
||||
try:
|
||||
key = base64.b64encode(os.urandom(16)).decode()
|
||||
writer.write((f'GET / HTTP/1.1\r\nHost: 127.0.0.1:{port}\r\nUpgrade: websocket\r\nConnection: Upgrade\r\nSec-WebSocket-Key: {key}\r\nSec-WebSocket-Version: 13\r\n\r\n').encode())
|
||||
await writer.drain()
|
||||
await reader.readuntil(b'\r\n\r\n')
|
||||
writer.write(bytes([0x80, 0x80 | 4, 0, 0, 0, 0]) + b'cont')
|
||||
await writer.drain()
|
||||
head = await asyncio.wait_for(reader.readexactly(2), 2)
|
||||
assert head[0] == 0x88
|
||||
payload = await reader.readexactly(head[1] & 127)
|
||||
assert struct.unpack('!H', payload[:2])[0] == 1002 and not delivered
|
||||
finally:
|
||||
writer.close()
|
||||
await writer.wait_closed()
|
||||
|
||||
# 2. Interleaved data frame during fragmentation -> 1002
|
||||
reader, writer = await asyncio.open_connection('127.0.0.1', port)
|
||||
try:
|
||||
key = base64.b64encode(os.urandom(16)).decode()
|
||||
writer.write((f'GET / HTTP/1.1\r\nHost: 127.0.0.1:{port}\r\nUpgrade: websocket\r\nConnection: Upgrade\r\nSec-WebSocket-Key: {key}\r\nSec-WebSocket-Version: 13\r\n\r\n').encode())
|
||||
await writer.drain()
|
||||
await reader.readuntil(b'\r\n\r\n')
|
||||
writer.write(bytes([0x02, 0x80 | 4, 0, 0, 0, 0]) + b'part')
|
||||
await writer.drain()
|
||||
await asyncio.sleep(0.01)
|
||||
writer.write(bytes([0x81, 0x80 | 4, 0, 0, 0, 0]) + b'text')
|
||||
await writer.drain()
|
||||
head = await asyncio.wait_for(reader.readexactly(2), 2)
|
||||
assert head[0] == 0x88
|
||||
payload = await reader.readexactly(head[1] & 127)
|
||||
assert struct.unpack('!H', payload[:2])[0] == 1002
|
||||
finally:
|
||||
writer.close()
|
||||
await writer.wait_closed()
|
||||
|
||||
# 3. Unfinished message: client disconnect releases scratch resources
|
||||
reader, writer = await asyncio.open_connection('127.0.0.1', port)
|
||||
try:
|
||||
key = base64.b64encode(os.urandom(16)).decode()
|
||||
writer.write((f'GET / HTTP/1.1\r\nHost: 127.0.0.1:{port}\r\nUpgrade: websocket\r\nConnection: Upgrade\r\nSec-WebSocket-Key: {key}\r\nSec-WebSocket-Version: 13\r\n\r\n').encode())
|
||||
await writer.drain()
|
||||
await reader.readuntil(b'\r\n\r\n')
|
||||
writer.write(bytes([0x02, 0x80 | 4, 0, 0, 0, 0]) + b'frag')
|
||||
await writer.drain()
|
||||
await asyncio.sleep(0.01)
|
||||
conn = next(iter(server.server_state.connections))
|
||||
assert conn.assembling_scratch is not None
|
||||
finally:
|
||||
writer.close()
|
||||
await writer.wait_closed()
|
||||
await asyncio.sleep(0.05)
|
||||
assert conn.assembling_scratch is None
|
||||
asyncio.run(serve(scenario))
|
||||
|
||||
def test_lower_trusted_runtime_limits_and_prepayload_rejection():
|
||||
settings = RuntimeSettings(
|
||||
max_binary_message_bytes=1200,
|
||||
max_client_control_bytes=500,
|
||||
output_credit_window_bytes=1200,
|
||||
max_queued_audio_bytes=2400,
|
||||
max_queued_audio_messages=10,
|
||||
)
|
||||
async def scenario(port, delivered, gate, server):
|
||||
# 1. Header-only pre-payload rejection on lowered binary limit (1201 > 1200) and text limit (501 > 500)
|
||||
for opcode, size in [(2, 1201), (1, 501)]:
|
||||
reader, writer = await asyncio.open_connection('127.0.0.1', port)
|
||||
try:
|
||||
key = base64.b64encode(os.urandom(16)).decode()
|
||||
writer.write((f'GET / HTTP/1.1\r\nHost: 127.0.0.1:{port}\r\nUpgrade: websocket\r\nConnection: Upgrade\r\nSec-WebSocket-Key: {key}\r\nSec-WebSocket-Version: 13\r\n\r\n').encode())
|
||||
await writer.drain()
|
||||
await reader.readuntil(b'\r\n\r\n')
|
||||
# Header only: no mask, no payload
|
||||
writer.write(bytes([0x80 | opcode, 0x80 | 126]) + struct.pack('!H', size))
|
||||
await writer.drain()
|
||||
head = await asyncio.wait_for(reader.readexactly(2), 2)
|
||||
assert head[0] == 0x88
|
||||
payload = await reader.readexactly(head[1] & 127)
|
||||
assert struct.unpack('!H', payload[:2])[0] == 1009 and not delivered
|
||||
finally:
|
||||
writer.close()
|
||||
await writer.wait_closed()
|
||||
|
||||
# 2. Exact lower limits (1200 binary and 500 text) are accepted
|
||||
async with connect(f'ws://127.0.0.1:{port}', compression=None, proxy=None) as ws:
|
||||
await ws.send(bytes(1200))
|
||||
assert await ws.recv() == 'accepted'
|
||||
assert len(delivered[-1]['bytes']) == 1200
|
||||
await ws.send('c' * 500)
|
||||
assert await ws.recv() == 'accepted'
|
||||
assert delivered[-1]['text'] == 'c' * 500
|
||||
asyncio.run(serve(scenario, settings=settings))
|
||||
|
||||
def test_small_message_budgets_one_and_two_deadlock_free():
|
||||
# Message budget of 1
|
||||
settings_1 = RuntimeSettings(
|
||||
max_binary_message_bytes=1200,
|
||||
max_client_control_bytes=500,
|
||||
output_credit_window_bytes=1200,
|
||||
max_queued_audio_bytes=2400,
|
||||
max_queued_audio_messages=1,
|
||||
)
|
||||
async def scenario_1(port, delivered, gate, server):
|
||||
async with connect(f'ws://127.0.0.1:{port}', compression=None, proxy=None) as ws:
|
||||
conn = next(iter(server.server_state.connections))
|
||||
assert conn.max_queued_audio_messages == 1
|
||||
assert conn.max_queue == 1
|
||||
|
||||
await ws.send(b'm1')
|
||||
assert await ws.recv() == 'accepted'
|
||||
|
||||
gate.clear()
|
||||
await ws.send(b'm2')
|
||||
await asyncio.sleep(0.02)
|
||||
assert conn.in_flight_message == b'm2'
|
||||
|
||||
await ws.send(b'm3')
|
||||
await asyncio.sleep(0.05)
|
||||
assert len(conn.messages) == 0
|
||||
|
||||
gate.set()
|
||||
assert await asyncio.wait_for(ws.recv(), 2.0) == 'accepted'
|
||||
assert await asyncio.wait_for(ws.recv(), 2.0) == 'accepted'
|
||||
assert len(delivered) == 3
|
||||
asyncio.run(serve(scenario_1, settings=settings_1))
|
||||
|
||||
# Message budget of 2 and audio byte capacity bound
|
||||
settings_2 = RuntimeSettings(
|
||||
max_binary_message_bytes=1200,
|
||||
max_client_control_bytes=500,
|
||||
output_credit_window_bytes=1200,
|
||||
max_queued_audio_bytes=2400,
|
||||
max_queued_audio_messages=2,
|
||||
)
|
||||
async def scenario_2(port, delivered, gate, server):
|
||||
async with connect(f'ws://127.0.0.1:{port}', compression=None, proxy=None) as ws:
|
||||
conn = next(iter(server.server_state.connections))
|
||||
assert conn.max_queued_audio_messages == 2
|
||||
|
||||
await ws.send(b'm1')
|
||||
assert await ws.recv() == 'accepted'
|
||||
|
||||
gate.clear()
|
||||
await ws.send(b'm2')
|
||||
await asyncio.sleep(0.02)
|
||||
assert conn.in_flight_message == b'm2'
|
||||
|
||||
await ws.send(b'm3')
|
||||
await asyncio.sleep(0.02)
|
||||
assert len(conn.messages) == 1
|
||||
|
||||
# m4 exceeds total message capacity (1 in-flight + 1 queued = 2)
|
||||
await ws.send(b'm4')
|
||||
await asyncio.sleep(0.05)
|
||||
assert len(conn.messages) == 1
|
||||
|
||||
gate.set()
|
||||
assert await asyncio.wait_for(ws.recv(), 2.0) == 'accepted'
|
||||
assert await asyncio.wait_for(ws.recv(), 2.0) == 'accepted'
|
||||
assert await asyncio.wait_for(ws.recv(), 2.0) == 'accepted'
|
||||
assert len(delivered) == 4
|
||||
asyncio.run(serve(scenario_2, settings=settings_2))
|
||||
|
||||
|
||||
def test_capacity_failure_terminates_receive_with_nonresponsive_peer():
|
||||
"""Protocol failure cancels the capacity waiter without another cancellation."""
|
||||
async def scenario(port, delivered, gate, server):
|
||||
reader, writer = await asyncio.open_connection('127.0.0.1', port)
|
||||
try:
|
||||
key = base64.b64encode(os.urandom(16)).decode()
|
||||
writer.write((f'GET / HTTP/1.1\r\nHost: 127.0.0.1:{port}\r\nUpgrade: websocket\r\nConnection: Upgrade\r\nSec-WebSocket-Key: {key}\r\nSec-WebSocket-Version: 13\r\n\r\n').encode())
|
||||
await writer.drain(); await reader.readuntil(b'\r\n\r\n')
|
||||
gate.clear()
|
||||
# ASGI retains one delivered message; queued messages fill the rest.
|
||||
writer.write((b'\x82\x81\x00\x00\x00\x00x') * 30)
|
||||
await writer.drain()
|
||||
conn = next(iter(server.server_state.connections))
|
||||
async with asyncio.timeout(1):
|
||||
while conn.has_capacity(): await asyncio.sleep(.001)
|
||||
assert not conn.transfer_data_task.done()
|
||||
conn.close_timeout = .05
|
||||
conn.fail_connection(1008)
|
||||
# Shield ensures the assertion's timeout cannot perform a second cancel.
|
||||
with pytest.raises(asyncio.CancelledError):
|
||||
await asyncio.wait_for(asyncio.shield(conn.transfer_data_task), .3)
|
||||
await asyncio.wait_for(asyncio.shield(conn.close_connection_task), 1)
|
||||
assert conn.transport.is_closing()
|
||||
assert conn.assembling_scratch is None and conn.in_flight_message is None
|
||||
finally:
|
||||
writer.close(); await writer.wait_closed()
|
||||
asyncio.run(serve(scenario, settings=RuntimeSettings(max_queued_audio_messages=1)))
|
||||
|
||||
|
||||
@pytest.mark.parametrize('fragmented', [False, True])
|
||||
def test_invalid_utf8_retains_standard_1007_rejection(fragmented):
|
||||
async def scenario(port, delivered, gate, server):
|
||||
reader, writer = await asyncio.open_connection('127.0.0.1', port)
|
||||
try:
|
||||
key = base64.b64encode(os.urandom(16)).decode()
|
||||
writer.write((f'GET / HTTP/1.1\r\nHost: 127.0.0.1:{port}\r\nUpgrade: websocket\r\nConnection: Upgrade\r\nSec-WebSocket-Key: {key}\r\nSec-WebSocket-Version: 13\r\n\r\n').encode())
|
||||
await writer.drain(); await reader.readuntil(b'\r\n\r\n')
|
||||
wire = b'\x01\x81\0\0\0\0\xc3\x80\x81\0\0\0\0\x28' if fragmented else b'\x81\x82\0\0\0\0\xc3\x28'
|
||||
writer.write(wire); await writer.drain()
|
||||
header = await asyncio.wait_for(reader.readexactly(2), 1)
|
||||
payload = await reader.readexactly(header[1] & 127)
|
||||
assert header[0] == 0x88 and struct.unpack('!H', payload[:2])[0] == 1007
|
||||
assert not delivered
|
||||
finally:
|
||||
writer.close(); await writer.wait_closed()
|
||||
asyncio.run(serve(scenario))
|
||||
Reference in New Issue
Block a user