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.
372 lines
18 KiB
Python
372 lines
18 KiB
Python
"""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))
|