"""ASGI regressions exercised through real TCP connections and the C parser."""
import asyncio
from contextlib import asynccontextmanager
import pytest
import mrhttp
from tests.common import contains, eq
@asynccontextmanager
async def running(app, **options):
server = mrhttp.ASGIServer(app, lifespan=options.pop('lifespan', 'off'),
timeout_graceful_shutdown=0.2, **options)
listener = await server.start_server(port=0)
port = listener.sockets[0].getsockname()[1]
try:
yield server, port
finally:
await server.shutdown()
async def connect(port):
return await asyncio.open_connection('127.0.0.1', port)
async def response(reader, head=False):
raw = await asyncio.wait_for(reader.readuntil(b'\r\n\r\n'), 2)
lines = raw.split(b'\r\n')
status = int(lines[0].split()[1])
headers = {}
for line in lines[1:-2]:
name, value = line.split(b':', 1)
headers.setdefault(name.lower(), []).append(value.strip())
body = b''
if not head and status not in (204, 304):
if headers.get(b'transfer-encoding') == [b'chunked']:
while True:
size = int(await asyncio.wait_for(reader.readline(), 2), 16)
if not size:
assert await reader.readexactly(2) == b'\r\n'
break
body += await reader.readexactly(size)
assert await reader.readexactly(2) == b'\r\n'
elif b'content-length' in headers:
body = await asyncio.wait_for(reader.readexactly(int(headers[b'content-length'][0])), 2)
else:
body = await asyncio.wait_for(reader.read(), 2)
return status, headers, body
async def request_body(receive):
parts = []
while True:
message = await receive()
assert message['type'] == 'http.request'
parts.append(message.get('body', b''))
if not message.get('more_body', False):
return b''.join(parts)
async def reply(send, body=b'ok', status=200, headers=()):
await send({'type': 'http.response.start', 'status': status, 'headers': list(headers)})
await send({'type': 'http.response.body', 'body': body})
@pytest.mark.parametrize('header,encoded', [
(b'Content-Length: 6', b'abcdef'),
(b'content-length: 6', b'abcdef'),
(b'cOnTeNt-LeNgTh: 6', b'abcdef'),
(b'Transfer-Encoding: chunked', b'3;foo=bar\r\nabc\r\n3\r\ndef\r\n0\r\nX-Trailer: yes\r\n\r\n'),
(b'transfer-encoding: chunked', b'3\r\nabc\r\n3\r\ndef\r\n0\r\n\r\n'),
])
def test_fragmented_request_framing(header, encoded):
async def scenario():
async def app(scope, receive, send):
await reply(send, await request_body(receive))
async with running(app) as (_, port):
reader, writer = await connect(port)
data = b'POST /echo HTTP/1.1\r\nHost: localhost\r\n' + header + b'\r\n\r\n' + encoded
try:
for byte in data:
writer.write(bytes([byte]))
await writer.drain()
await asyncio.sleep(0.001)
assert (await response(reader))[2] == b'abcdef'
finally:
writer.close()
await writer.wait_closed()
asyncio.run(scenario())
def test_pipeline_over_50_preserves_request_headers_and_bytes():
async def scenario():
async def app(scope, receive, send):
await asyncio.sleep(0)
body = scope['raw_path'] + b'|' + dict(scope['headers'])[b'x-id']
await reply(send, body)
async with running(app) as (_, port):
reader, writer = await connect(port)
try:
writer.write(b''.join(
b'GET /%d HTTP/1.1\r\nHost: localhost\r\nX-Id: %d\r\n\r\n' % (i, i)
for i in range(100)))
await writer.drain()
for i in range(100):
assert (await response(reader))[2] == b'/%d|%d' % (i, i)
finally:
writer.close()
await writer.wait_closed()
asyncio.run(scenario())
def test_receive_waits_then_reports_response_completion():
async def scenario():
observed = asyncio.Event()
async def app(scope, receive, send):
assert (await receive())['more_body'] is False
waiting = asyncio.create_task(receive())
await asyncio.sleep(0.01)
assert not waiting.done()
await reply(send)
assert await waiting == {'type': 'http.disconnect'}
observed.set()
async with running(app) as (_, port):
reader, writer = await connect(port)
try:
writer.write(b'GET / HTTP/1.1\r\nHost: localhost\r\n\r\n')
await writer.drain()
assert (await response(reader))[2] == b'ok'
await asyncio.wait_for(observed.wait(), 1)
finally:
writer.close()
await writer.wait_closed()
asyncio.run(scenario())
def test_streaming_flushes_before_application_returns():
async def scenario():
finish = asyncio.Event()
async def app(scope, receive, send):
await send({'type': 'http.response.start', 'status': 200})
await send({'type': 'http.response.body', 'body': b'first', 'more_body': True})
await finish.wait()
await send({'type': 'http.response.body', 'body': b'last'})
async with running(app) as (_, port):
reader, writer = await connect(port)
try:
writer.write(b'GET / HTTP/1.1\r\nHost: localhost\r\n\r\n')
await writer.drain()
headers = await asyncio.wait_for(reader.readuntil(b'\r\n\r\n'), 1)
assert b'transfer-encoding: chunked' in headers
assert await asyncio.wait_for(reader.readexactly(10), 1) == b'5\r\nfirst\r\n'
finish.set()
assert await asyncio.wait_for(reader.readexactly(14), 1) == b'4\r\nlast\r\n0\r\n\r\n'
finally:
finish.set()
writer.close()
await writer.wait_closed()
asyncio.run(scenario())
@pytest.mark.parametrize('extra,body', [
(b'Content-Length: 1\r\nTransfer-Encoding: chunked\r\n', b'0\r\n\r\n'),
(b'Content-Length: 1\r\nContent-Length: 2\r\n', b'xx'),
(b'Content-Length: 2junk\r\n', b'xx'),
(b'Content-Length: -1\r\n', b''),
(b'Content-Length: 99999999999999999999999999999\r\n', b''),
(b'Host: duplicate\r\n', b''),
(b'Bad Header: value\r\n', b''),
(b'Transfer-Encoding: gzip, chunked\r\n', b''),
(b'Transfer-Encoding: chunked\r\n', b'ffffffffffffffffffffffffffffffff\r\n'),
])
def test_rejects_ambiguous_or_malformed_requests(extra, body):
async def scenario():
calls = []
async def app(scope, receive, send):
calls.append(scope)
await reply(send)
async with running(app) as (_, port):
reader, writer = await connect(port)
try:
writer.write(b'POST / HTTP/1.1\r\nHost: localhost\r\n' + extra + b'\r\n' + body)
await writer.drain()
assert (await response(reader))[0] == 400
assert await asyncio.wait_for(reader.read(), 1) == b''
assert not calls
finally:
writer.close()
await writer.wait_closed()
asyncio.run(scenario())
@pytest.mark.parametrize('wire', [
b'POST / HTTP/1.1\r\nHost: localhost\r\nContent-Length: 33\r\n\r\n',
b'POST / HTTP/1.1\r\nHost: localhost\r\nTransfer-Encoding: chunked\r\n\r\n21\r\n',
b'GET / HTTP/1.1\r\nHost: localhost\r\nX-Large: ' + b'x'*1100 + b'\r\n\r\n',
])
def test_request_resource_limits(wire):
async def scenario():
async def app(scope, receive, send):
await reply(send)
async with running(app, max_body_size=32, max_header_size=1024) as (_, port):
reader, writer = await connect(port)
try:
writer.write(wire)
await writer.drain()
assert (await response(reader))[0] == 400
finally:
writer.close()
await writer.wait_closed()
asyncio.run(scenario())
def test_assertion_helpers_raise_on_mismatch():
with pytest.raises(AssertionError):
eq(200, 500)
with pytest.raises(AssertionError):
contains('body', 'missing')
@pytest.mark.parametrize('method,status,headers', [
(b'HEAD', 200, [(b'content-length', b'9')]),
(b'GET', 204, [(b'content-length', b'9')]),
(b'GET', 304, [(b'content-length', b'9')]),
])
def test_bodyless_responses_do_not_corrupt_next_response(method, status, headers):
async def scenario():
async def app(scope, receive, send):
if scope['path'] == '/first':
await reply(send, b'discarded', status, headers)
else:
await reply(send, b'next')
async with running(app) as (_, port):
reader, writer = await connect(port)
try:
writer.write(method + b' /first HTTP/1.1\r\nHost: localhost\r\n\r\n'
b'GET /next HTTP/1.1\r\nHost: localhost\r\n\r\n')
await writer.drain()
result = await response(reader, head=method == b'HEAD')
assert result[0] == status
if status == 204:
assert b'content-length' not in result[1]
assert (await response(reader))[2] == b'next'
finally:
writer.close()
await writer.wait_closed()
asyncio.run(scenario())
@pytest.mark.parametrize('headers,body', [
([(b'content-length', b'1')], b'too long'),
([(b'content-length', b'10')], b'short'),
([(b'content-length', b'1'), (b'content-length', b'1')], b'x'),
([(b'bad name', b'value')], b'x'),
([(b'x-test', b'value\r\ninjected: yes')], b'x'),
])
def test_invalid_application_response_returns_500_and_closes(headers, body):
async def scenario():
async def app(scope, receive, send):
await reply(send, body, headers=headers)
async with running(app) as (_, port):
reader, writer = await connect(port)
try:
writer.write(b'GET / HTTP/1.1\r\nHost: localhost\r\n\r\n')
await writer.drain()
assert (await response(reader))[0] == 500
assert await asyncio.wait_for(reader.read(), 1) == b''
finally:
writer.close()
await writer.wait_closed()
asyncio.run(scenario())
def test_client_disconnect_reaches_receive_and_releases_application():
async def scenario():
listening = asyncio.Event()
finished = asyncio.Event()
async def app(scope, receive, send):
await receive()
listening.set()
assert await receive() == {'type': 'http.disconnect'}
finished.set()
async with running(app) as (_, port):
_, writer = await connect(port)
writer.write(b'GET / HTTP/1.1\r\nHost: localhost\r\n\r\n')
await writer.drain()
await asyncio.wait_for(listening.wait(), 1)
writer.close()
await writer.wait_closed()
await asyncio.wait_for(finished.wait(), 1)
asyncio.run(scenario())
def test_lifespan_state_and_shutdown_follow_inflight_requests():
async def scenario():
finish = asyncio.Event()
started = asyncio.Event()
events = []
resource = object()
async def app(scope, receive, send):
if scope['type'] == 'lifespan':
assert await receive() == {'type': 'lifespan.startup'}
scope['state']['resource'] = resource
await send({'type': 'lifespan.startup.complete'})
assert await receive() == {'type': 'lifespan.shutdown'}
events.append('shutdown')
await send({'type': 'lifespan.shutdown.complete'})
else:
assert scope['state']['resource'] is resource
scope['state']['local'] = True
started.set()
await finish.wait()
events.append('response')
await reply(send)
async with running(app, lifespan='on') as (server, port):
reader, writer = await connect(port)
try:
writer.write(b'GET / HTTP/1.1\r\nHost: localhost\r\n\r\n')
await writer.drain()
await asyncio.wait_for(started.wait(), 1)
shutdown = asyncio.create_task(server.shutdown())
await asyncio.sleep(0.01)
assert not events
finish.set()
assert (await response(reader))[2] == b'ok'
await asyncio.wait_for(shutdown, 1)
assert events == ['response', 'shutdown']
assert 'local' not in server._asgi_state
finally:
finish.set()
writer.close()
await writer.wait_closed()
asyncio.run(scenario())
@pytest.mark.parametrize('mode', ['auto', 'on'])
def test_unsupported_lifespan_is_detected_without_waiting_for_timeout(mode):
async def scenario():
async def app(scope, receive, send):
if scope['type'] == 'lifespan':
raise NotImplementedError('no lifespan')
await reply(send)
server = mrhttp.ASGIServer(app, lifespan=mode)
try:
if mode == 'on':
with pytest.raises(NotImplementedError):
await asyncio.wait_for(server.start_server(port=0), 1)
else:
listener = await asyncio.wait_for(server.start_server(port=0), 1)
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()
assert (await response(reader))[2] == b'ok'
finally:
writer.close()
await writer.wait_closed()
finally:
await server.shutdown()
asyncio.run(scenario())
def test_expect_continue_allows_client_to_send_body():
async def scenario():
async def app(scope, receive, send):
await reply(send, (await receive())['body'])
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: 3\r\nExpect: 100-continue\r\n\r\n')
await writer.drain()
assert await asyncio.wait_for(reader.readuntil(b'\r\n\r\n'), 1) == b'HTTP/1.1 100 Continue\r\n\r\n'
writer.write(b'abc')
await writer.drain()
assert (await response(reader))[2] == b'abc'
finally:
writer.close()
await writer.wait_closed()
asyncio.run(scenario())
def test_incomplete_request_deadline_closes_slow_client():
async def scenario():
async def app(scope, receive, send):
await reply(send)
async with running(app, timeout_request=0.05) as (_, port):
reader, writer = await connect(port)
try:
writer.write(b'GET / HTTP/1.1\r\nHost:')
await writer.drain()
assert await asyncio.wait_for(reader.read(), 1) == b''
finally:
writer.close()
await writer.wait_closed()
asyncio.run(scenario())
def test_slow_reader_applies_backpressure_and_disconnect_releases_sender():
async def scenario():
sent = asyncio.Event()
released = asyncio.Event()
async def app(scope, receive, send):
try:
await send({'type': 'http.response.start', 'status': 200})
for _ in range(64):
await send({'type': 'http.response.body', 'body': b'x' * 1024*1024, 'more_body': True})
sent.set()
await send({'type': 'http.response.body'})
finally:
released.set()
async with running(app) as (_, port):
reader, writer = await asyncio.open_connection('127.0.0.1', port, limit=1024)
try:
writer.write(b'GET / HTTP/1.1\r\nHost: localhost\r\n\r\n')
await writer.drain()
await asyncio.wait_for(reader.readuntil(b'\r\n\r\n'), 1)
await asyncio.sleep(0.05)
assert not sent.is_set(), 'send must block when the client stops reading'
writer.transport.abort()
await asyncio.wait_for(released.wait(), 1)
finally:
writer.close()
await writer.wait_closed()
asyncio.run(scenario())
def test_error_after_streaming_closes_without_second_response():
async def scenario():
async def app(scope, receive, send):
await send({'type': 'http.response.start', 'status': 200})
await send({'type': 'http.response.body', 'body': b'partial', 'more_body': True})
raise RuntimeError('late failure')
async with running(app) as (_, port):
reader, writer = await connect(port)
try:
writer.write(b'GET / HTTP/1.1\r\nHost: localhost\r\n\r\n')
await writer.drain()
data = await asyncio.wait_for(reader.read(), 1)
assert data.startswith(b'HTTP/1.1 200')
assert data.count(b'HTTP/1.1') == 1
assert b'partial' in data
assert not data.endswith(b'0\r\n\r\n')
finally:
writer.close()
await writer.wait_closed()
asyncio.run(scenario())
def test_connection_admission_limit_preserves_existing_client():
async def scenario():
async def app(scope, receive, send):
await reply(send)
async with running(app, max_connections=1) as (_, port):
reader, writer = await connect(port)
second_reader, second_writer = await connect(port)
try:
assert await asyncio.wait_for(second_reader.read(), 1) == b''
writer.write(b'GET / HTTP/1.1\r\nHost: localhost\r\n\r\n')
await writer.drain()
assert (await response(reader))[2] == b'ok'
finally:
writer.close()
second_writer.close()
await asyncio.gather(writer.wait_closed(), second_writer.wait_closed())
asyncio.run(scenario())
def test_pipeline_capacity_is_bounded_without_worker_crash():
async def scenario():
async def app(scope, receive, send):
await reply(send)
async with running(app) as (_, port):
reader, writer = await connect(port)
try:
writer.write(b'GET / HTTP/1.1\r\nHost: localhost\r\n\r\n' * 1100)
await writer.drain()
await asyncio.wait_for(reader.read(), 2)
finally:
writer.close()
await writer.wait_closed()
# The same worker must remain usable after rejecting the connection.
reader, writer = await connect(port)
try:
writer.write(b'GET / HTTP/1.1\r\nHost: localhost\r\n\r\n')
await writer.drain()
assert (await response(reader))[2] == b'ok'
finally:
writer.close()
await writer.wait_closed()
asyncio.run(scenario())
def test_encoded_path_and_duplicate_headers_are_preserved():
async def scenario():
async def app(scope, receive, send):
assert scope['path'] == '/café/%'
assert scope['raw_path'] == b'/caf%C3%A9/%'
assert scope['query_string'] == b'x=%2F'
assert [v for n, v in scope['headers'] if n == b'cookie'] == [b'a=1', b'b=2']
await reply(send)
async with running(app) as (_, port):
reader, writer = await connect(port)
try:
writer.write(b'GET /caf%C3%A9/%?x=%2F HTTP/1.1\r\nHost: localhost\r\nCookie: a=1\r\nCookie: b=2\r\n\r\n')
await writer.drain()
assert (await response(reader))[2] == b'ok'
finally:
writer.close()
await writer.wait_closed()
asyncio.run(scenario())