"""Production contracts at real socket and framework boundaries."""
import asyncio
import json
import logging
import os
import socket
import pytest
from wsproto import WSConnection, events
from wsproto.connection import ConnectionType
import mrhttp
from tests.test_asgi_regressions import running, connect, response, reply, request_body
def test_dispatch_and_partial_body_arrive_before_upload_finishes():
async def scenario():
dispatched, partial = asyncio.Event(), asyncio.Event()
async def app(scope, receive, send):
dispatched.set()
first = await receive()
assert first == {'type': 'http.request', 'body': b'abc', 'more_body': True}
partial.set()
await reply(send, first['body'] + await request_body(receive))
async with running(app) as (_, port):
reader, writer = await connect(port)
try:
writer.write(b'POST / HTTP/1.1\r\nHost: localhost\r\nContent-Length: 6\r\n\r\n')
await writer.drain()
await asyncio.wait_for(dispatched.wait(), 1)
writer.write(b'abc')
await writer.drain()
await asyncio.wait_for(partial.wait(), 1)
writer.write(b'def')
await writer.drain()
assert (await response(reader))[2] == b'abcdef'
finally:
writer.close()
await writer.wait_closed()
asyncio.run(scenario())
def test_early_rejection_does_not_read_upload_or_send_continue():
async def scenario():
async def app(scope, receive, send):
await reply(send, b'denied', 403)
async with running(app) as (_, port):
reader, writer = await connect(port)
try:
writer.write(b'POST / HTTP/1.1\r\nHost: localhost\r\nContent-Length: 1000000\r\nExpect: 100-continue\r\n\r\n')
await writer.drain()
result = await response(reader)
assert result[0] == 403
assert result[1][b'connection'] == [b'close']
assert await asyncio.wait_for(reader.read(), 1) == b''
finally:
writer.close()
await writer.wait_closed()
asyncio.run(scenario())
def test_slow_upload_consumer_applies_read_backpressure_and_resumes_losslessly():
async def scenario():
started, consume, uploaded = asyncio.Event(), asyncio.Event(), asyncio.Event()
size = 8 * 1024 * 1024
async def app(scope, receive, send):
started.set()
await consume.wait()
body = await request_body(receive)
assert body == b'x' * size
await reply(send, str(len(body)).encode())
async with running(app, read_buffer_size=32768) as (_, port):
reader, writer = await connect(port)
async def upload():
writer.write(b'x' * size)
await writer.drain()
uploaded.set()
try:
writer.write(b'POST / HTTP/1.1\r\nHost: localhost\r\nContent-Length: %d\r\n\r\n' % size)
await writer.drain()
await asyncio.wait_for(started.wait(), 1)
task = asyncio.create_task(upload())
await asyncio.sleep(0.1)
assert not uploaded.is_set(), 'the producer must block while the application is not consuming'
consume.set()
await asyncio.wait_for(task, 3)
assert (await response(reader))[2] == str(size).encode()
finally:
consume.set()
writer.close()
await writer.wait_closed()
asyncio.run(scenario())
@pytest.mark.parametrize('trusted,expected', [('127.0.0.0/8', '203.0.113.7'), ('192.0.2.0/24', '127.0.0.1')])
def test_proxy_metadata_is_applied_only_from_trusted_peers(trusted, expected):
async def scenario():
async def app(scope, receive, send):
await reply(send, json.dumps([scope['client'][0], scope['scheme']]).encode())
async with running(app, proxy_headers=True, forwarded_allow_ips=trusted) as (_, port):
reader, writer = await connect(port)
try:
writer.write(b'GET / HTTP/1.1\r\nHost: localhost\r\nX-Forwarded-For: 203.0.113.7, 127.0.0.2\r\nX-Forwarded-Proto: https\r\n\r\n')
await writer.drain()
assert json.loads((await response(reader))[2]) == [expected, 'https' if expected == '203.0.113.7' else 'http']
finally:
writer.close()
await writer.wait_closed()
asyncio.run(scenario())
def test_json_access_log_request_id_health_and_metrics(caplog):
caplog.set_level(logging.INFO, logger='mrhttp.access')
async def scenario():
calls = []
async def app(scope, receive, send):
calls.append(scope['path'])
await reply(send, b'created', 201)
async with running(app, access_log=True, access_log_format='json', metrics_path='/metrics', health_check_path='/healthz') as (_, port):
reader, writer = await connect(port)
try:
writer.write(b'GET /created HTTP/1.1\r\nHost: localhost\r\nX-Request-Id: test-123\r\n\r\n')
await writer.drain()
result = await response(reader)
assert result[1][b'x-request-id'] == [b'test-123']
writer.write(b'GET /healthz HTTP/1.1\r\nHost: localhost\r\n\r\n')
await writer.drain()
assert (await response(reader))[2] == b'ok'
writer.write(b'GET /metrics HTTP/1.1\r\nHost: localhost\r\n\r\n')
await writer.drain()
metrics = (await response(reader))[2]
assert b'mrhttp_http_requests_total{status="201"} 1' in metrics
assert b'mrhttp_response_body_bytes_total 9' in metrics
assert b'mrhttp_request_duration_seconds_count 2' in metrics
assert calls == ['/created']
finally:
writer.close()
await writer.wait_closed()
asyncio.run(scenario())
records = [json.loads(record.message) for record in caplog.records if record.name == 'mrhttp.access']
assert any(record['request_id'] == 'test-123' and record['status'] == 201 and record['bytes_sent'] == 7 for record in records)
@pytest.mark.parametrize('binding', ['unix', 'ipv6', 'fd'])
def test_deployment_socket_binding(binding, tmp_path):
async def scenario():
async def app(scope, receive, send):
await reply(send, json.dumps(scope['server']).encode())
server = mrhttp.ASGIServer(app, lifespan='off')
inherited = None
path = str(tmp_path / 'server.sock')
try:
if binding == 'unix':
await server.start_server(uds=path)
reader, writer = await asyncio.open_unix_connection(path)
elif binding == 'ipv6':
if not socket.has_ipv6:
pytest.skip('IPv6 unavailable')
try:
listener = await server.start_server('::1', 0)
except OSError as exc:
if exc.errno in (97, 99):
pytest.skip('IPv6 loopback unavailable')
raise
reader, writer = await asyncio.open_connection('::1', listener.sockets[0].getsockname()[1])
else:
inherited = socket.socket()
inherited.bind(('127.0.0.1', 0))
inherited.listen()
listener = await server.start_server(fd=inherited.fileno())
reader, writer = await connect(listener.sockets[0].getsockname()[1])
try:
writer.write(b'GET / HTTP/1.1\r\nHost: localhost\r\n\r\n')
await writer.drain()
address = json.loads((await response(reader))[2])
assert address[0] == (path if binding == 'unix' else '::1' if binding == 'ipv6' else '127.0.0.1')
finally:
writer.close()
await writer.wait_closed()
await server.shutdown()
if binding == 'unix':
assert not os.path.exists(path)
if inherited:
assert inherited.getsockname()[1] > 0
finally:
await server.shutdown()
if inherited:
inherited.close()
asyncio.run(scenario())
async def ws_open(port, subprotocols=(), extensions=()):
reader, writer = await connect(port)
client = WSConnection(ConnectionType.CLIENT)
writer.write(client.send(events.Request(host='localhost', target='/ws', subprotocols=list(subprotocols), extensions=list(extensions))))
await writer.drain()
client.receive_data(await asyncio.wait_for(reader.readuntil(b'\r\n\r\n'), 1))
accepted = list(client.events())
assert len(accepted) == 1 and isinstance(accepted[0], events.AcceptConnection)
return client, reader, writer, accepted[0]
async def ws_event(client, reader, kind):
while True:
for event in client.events():
if isinstance(event, kind):
return event
data = await asyncio.wait_for(reader.read(65536), 2)
assert data, 'WebSocket closed before expected event'
client.receive_data(data)
def test_websocket_asgi_messages_subprotocol_fragmentation_ping_and_close():
async def scenario():
disconnected = asyncio.Event()
async def app(scope, receive, send):
assert scope['type'] == 'websocket'
assert scope['subprotocols'] == ['chat']
assert await receive() == {'type': 'websocket.connect'}
await send({'type': 'websocket.accept', 'subprotocol': 'chat'})
assert await receive() == {'type': 'websocket.receive', 'text': 'hello'}
await send({'type': 'websocket.send', 'text': 'HELLO'})
assert await receive() == {'type': 'websocket.receive', 'bytes': b'\x00\xff'}
await send({'type': 'websocket.send', 'bytes': b'\x00\xff'})
close = await receive()
assert close == {'type': 'websocket.disconnect', 'code': 1000, 'reason': 'done'}
disconnected.set()
async with running(app) as (_, port):
client, reader, writer, accepted = await ws_open(port, ['chat'])
try:
assert accepted.subprotocol == 'chat'
writer.write(client.send(events.TextMessage(data='hel', message_finished=False)))
writer.write(client.send(events.TextMessage(data='lo')))
await writer.drain()
assert (await ws_event(client, reader, events.TextMessage)).data == 'HELLO'
writer.write(client.send(events.Ping(payload=b'probe')))
await writer.drain()
assert (await ws_event(client, reader, events.Pong)).payload == b'probe'
writer.write(client.send(events.BytesMessage(data=b'\x00\xff')))
await writer.drain()
assert (await ws_event(client, reader, events.BytesMessage)).data == b'\x00\xff'
writer.write(client.send(events.CloseConnection(code=1000, reason='done')))
await writer.drain()
assert (await ws_event(client, reader, events.CloseConnection)).code == 1000
await asyncio.wait_for(disconnected.wait(), 1)
finally:
writer.close()
await writer.wait_closed()
asyncio.run(scenario())
@pytest.mark.parametrize('attack,code', [('oversize', 1009), ('unmasked', 1002)])
def test_websocket_limits_and_invalid_frames_close_safely(attack, code):
async def scenario():
async def app(scope, receive, send):
await receive()
await send({'type': 'websocket.accept'})
while (await receive())['type'] != 'websocket.disconnect':
pass
async with running(app, ws_max_size=8) as (_, port):
client, reader, writer, _ = await ws_open(port)
try:
data = client.send(events.BytesMessage(data=b'x' * 9)) if attack == 'oversize' else b'\x81\x01x'
writer.write(data)
await writer.drain()
assert (await ws_event(client, reader, events.CloseConnection)).code == code
finally:
writer.close()
await writer.wait_closed()
asyncio.run(scenario())
def test_websocket_handshake_can_be_denied():
async def scenario():
async def app(scope, receive, send):
assert await receive() == {'type': 'websocket.connect'}
await send({'type': 'websocket.close'})
async with running(app) as (_, port):
reader, writer = await connect(port)
client = WSConnection(ConnectionType.CLIENT)
try:
writer.write(client.send(events.Request(host='localhost', target='/ws')))
await writer.drain()
assert (await response(reader))[0] == 403
finally:
writer.close()
await writer.wait_closed()
asyncio.run(scenario())
def test_websocket_queue_resumes_without_losing_messages():
async def scenario():
consume = asyncio.Event()
async def app(scope, receive, send):
await receive()
await send({'type': 'websocket.accept'})
await consume.wait()
for i in range(40):
assert (await receive())['text'] == str(i)
await send({'type': 'websocket.send', 'text': 'all received'})
await send({'type': 'websocket.close'})
async with running(app, ws_max_queue=1) as (_, port):
client, reader, writer, _ = await ws_open(port)
try:
writer.write(b''.join(client.send(events.TextMessage(data=str(i))) for i in range(40)))
await writer.drain()
await asyncio.sleep(0.01)
consume.set()
assert (await ws_event(client, reader, events.TextMessage)).data == 'all received'
finally:
consume.set()
writer.close()
await writer.wait_closed()
asyncio.run(scenario())
def test_websocket_ping_timeout_closes_unresponsive_peer():
async def scenario():
async def app(scope, receive, send):
await receive()
await send({'type': 'websocket.accept'})
assert (await receive())['type'] == 'websocket.disconnect'
async with running(app, ws_ping_interval=0.02, ws_ping_timeout=0.03) as (_, port):
client, reader, writer, _ = await ws_open(port)
try:
assert isinstance(await ws_event(client, reader, events.Ping), events.Ping)
assert (await ws_event(client, reader, events.CloseConnection)).code == 1011
finally:
writer.close()
await writer.wait_closed()
asyncio.run(scenario())
@pytest.mark.parametrize('header', [b'invalid', b'not-base64', b'AAAAAAAAAAAAAAAAAAAA'])
def test_invalid_websocket_keys_are_rejected(header):
async def scenario():
calls = []
async def app(scope, receive, send):
calls.append(scope)
async with running(app) as (_, port):
reader, writer = await connect(port)
try:
writer.write(b'GET /ws HTTP/1.1\r\nHost: localhost\r\nUpgrade: websocket\r\nConnection: Upgrade\r\nSec-WebSocket-Version: 13\r\nSec-WebSocket-Key: ' + header + b'\r\n\r\n')
await writer.drain()
assert (await response(reader))[0] == 400
assert not calls
finally:
writer.close()
await writer.wait_closed()
asyncio.run(scenario())
def test_websocket_message_preceding_close_is_delivered_before_disconnect():
async def scenario():
done = asyncio.Event()
async def app(scope, receive, send):
await receive()
await send({'type': 'websocket.accept'})
assert await receive() == {'type': 'websocket.receive', 'text': 'last message'}
assert (await receive())['type'] == 'websocket.disconnect'
done.set()
async with running(app) as (_, port):
client, reader, writer, _ = await ws_open(port)
try:
writer.write(client.send(events.TextMessage(data='last message')) + client.send(events.CloseConnection(code=1000)))
await writer.drain()
await ws_event(client, reader, events.CloseConnection)
await asyncio.wait_for(done.wait(), 1)
finally:
writer.close()
await writer.wait_closed()
asyncio.run(scenario())
def test_fastapi_websocket_json_roundtrip():
from fastapi import FastAPI, WebSocket
async def scenario():
app = FastAPI()
@app.websocket('/ws')
async def endpoint(websocket: WebSocket):
await websocket.accept()
message = await websocket.receive_json()
await websocket.send_json({'answer': message['number'] + 1})
await websocket.close()
async with running(app) as (_, port):
client, reader, writer, _ = await ws_open(port)
try:
writer.write(client.send(events.TextMessage(data='{"number":41}')))
await writer.drain()
assert json.loads((await ws_event(client, reader, events.TextMessage)).data) == {'answer': 42}
finally:
writer.close()
await writer.wait_closed()
asyncio.run(scenario())