The proxy read only the first request per client connection and then tunneled all subsequent bytes to that first request's upstream. Browsers reuse HTTP/1.1 connections to the proxy across hosts, so any later request was forwarded raw to the first upstream server, which answered with its default vhost — pages showed wrong content (e.g. a Caddy listing from another host under http://192.168.0.1/) until refresh. Plain HTTP now runs a keep-alive loop with a routing decision, fresh upstream connection and correct response framing (Content-Length, chunked, 1xx, HEAD, 204/304, EOF) per request. CONNECT is unchanged.
187 lines
8.5 KiB
Python
187 lines
8.5 KiB
Python
import os
|
||
import asyncio
|
||
import tempfile
|
||
from pathlib import Path
|
||
os.environ["PAC_ROUTER_DB"] = str(Path(tempfile.mkdtemp()) / "test.db")
|
||
from fastapi.testclient import TestClient
|
||
from app.main import app
|
||
from app.proxy import request_target, start_proxy
|
||
|
||
client = TestClient(app)
|
||
|
||
def test_pac_and_rules():
|
||
assert 'return "DIRECT"' in client.get('/proxy.pac').text
|
||
assert client.post('/api/rules', json={'domain':'*.example.com','route':'PROXY','enabled':True}).status_code == 201
|
||
assert client.post('/api/rules', json={'domain':'example.com','route':'DIRECT','enabled':True}).status_code == 201
|
||
assert client.get('/api/test',params={'host':'sub.example.com'}).json()['route']=='PROXY'
|
||
assert client.get('/api/test',params={'host':'example.com'}).json()['route']=='DIRECT'
|
||
assert client.get('/api/test',params={'host':'notexample.com'}).json()['route']=='DIRECT'
|
||
assert 'dnsDomainIs(host, ".example.com")' in client.get('/proxy.pac').text
|
||
|
||
def test_validation_and_security():
|
||
assert client.post('/api/rules',json={'domain':'evil.com"); alert(1)//','route':'PROXY'}).status_code==422
|
||
assert client.post('/api/rules',json={'domain':'*.example.com','route':'PROXY'}).status_code==409
|
||
assert client.put('/api/settings',json={'proxy_host':'127.0.0.1','proxy_port':99999,'default_route':'DIRECT'}).status_code==422
|
||
assert client.post('/api/rules',headers={'Origin':'https://evil.example'},json={'domain':'safe.example','route':'DIRECT'}).status_code==403
|
||
|
||
def test_import_export():
|
||
data=client.get('/api/export').json()
|
||
assert data['version']==1
|
||
assert client.post('/api/import',json=data).status_code==200
|
||
|
||
def test_proxy_request_parsing():
|
||
method, host, port, forwarded = request_target(b'GET http://example.com:8080/a?q=1 HTTP/1.1\r\nHost: example.com:8080\r\n\r\n')
|
||
assert (method, host, port) == ('GET', 'example.com', 8080)
|
||
assert forwarded.startswith(b'GET /a?q=1 HTTP/1.1\r\n')
|
||
method, host, port, _ = request_target(b'CONNECT Example.com:443 HTTP/1.1\r\nHost: Example.com:443\r\n\r\n')
|
||
assert (method, host, port) == ('CONNECT', 'example.com', 443)
|
||
|
||
def test_direct_routing_proxy():
|
||
async def scenario():
|
||
async def target(reader, writer):
|
||
request = await reader.readuntil(b'\r\n\r\n')
|
||
assert request.startswith(b'GET /hello HTTP/1.1\r\n')
|
||
writer.write(b'HTTP/1.1 200 OK\r\nContent-Length: 2\r\nConnection: close\r\n\r\nOK')
|
||
await writer.drain()
|
||
writer.close()
|
||
|
||
target_server = await asyncio.start_server(target, '127.0.0.1', 0)
|
||
target_port = target_server.sockets[0].getsockname()[1]
|
||
proxy_server = await start_proxy(
|
||
'127.0.0.1', 0,
|
||
lambda host: {'route': 'DIRECT'},
|
||
lambda: {'proxy_host': '127.0.0.1', 'proxy_port': 1},
|
||
)
|
||
proxy_port = proxy_server.sockets[0].getsockname()[1]
|
||
try:
|
||
reader, writer = await asyncio.open_connection('127.0.0.1', proxy_port)
|
||
writer.write(f'GET http://127.0.0.1:{target_port}/hello HTTP/1.1\r\nHost: 127.0.0.1:{target_port}\r\nConnection: close\r\n\r\n'.encode())
|
||
await writer.drain()
|
||
response = await reader.read()
|
||
assert response.endswith(b'\r\n\r\nOK')
|
||
writer.close()
|
||
await writer.wait_closed()
|
||
finally:
|
||
proxy_server.close()
|
||
target_server.close()
|
||
await proxy_server.wait_closed()
|
||
await target_server.wait_closed()
|
||
|
||
asyncio.run(scenario())
|
||
|
||
def test_proxy_shutdown_closes_pending_clients():
|
||
async def scenario():
|
||
async def hanging_target(reader, writer):
|
||
try:
|
||
await reader.read()
|
||
finally:
|
||
writer.close()
|
||
await writer.wait_closed()
|
||
|
||
target_server = await asyncio.start_server(hanging_target, '127.0.0.1', 0)
|
||
target_port = target_server.sockets[0].getsockname()[1]
|
||
proxy_server = await start_proxy(
|
||
'127.0.0.1', 0,
|
||
lambda host: {'route': 'DIRECT'},
|
||
lambda: {'proxy_host': '127.0.0.1', 'proxy_port': 1},
|
||
)
|
||
proxy_port = proxy_server.sockets[0].getsockname()[1]
|
||
reader, writer = await asyncio.open_connection('127.0.0.1', proxy_port)
|
||
writer.write(f'CONNECT 127.0.0.1:{target_port} HTTP/1.1\r\nHost: 127.0.0.1:{target_port}\r\n\r\n'.encode())
|
||
await writer.drain()
|
||
assert (await reader.readuntil(b'\r\n\r\n')).startswith(b'HTTP/1.1 200')
|
||
assert proxy_server.client_tasks
|
||
|
||
proxy_server.close()
|
||
await asyncio.wait_for(proxy_server.wait_closed(), timeout=3)
|
||
assert not proxy_server.client_tasks
|
||
assert await reader.read() == b''
|
||
writer.close()
|
||
await writer.wait_closed()
|
||
target_server.close()
|
||
await target_server.wait_closed()
|
||
|
||
asyncio.run(scenario())
|
||
|
||
|
||
def test_keep_alive_connection_routes_every_request():
|
||
async def scenario():
|
||
seen_a, seen_b = [], []
|
||
|
||
async def target_a(reader, writer):
|
||
while head := await read_head(reader):
|
||
seen_a.append(head.split(b"\r\n", 1)[0])
|
||
length = content_length(head)
|
||
body = await reader.readexactly(length) if length else b""
|
||
writer.write(b"HTTP/1.1 200 OK\r\nContent-Length: 5\r\n\r\nfromA" if not body else
|
||
b"HTTP/1.1 200 OK\r\nContent-Length: 5\r\n\r\npostA")
|
||
await writer.drain()
|
||
|
||
async def target_b(reader, writer):
|
||
while head := await read_head(reader):
|
||
seen_b.append(head.split(b"\r\n", 1)[0])
|
||
length = content_length(head)
|
||
body = await reader.readexactly(length) if length else b""
|
||
writer.write(b"HTTP/1.1 200 OK\r\nContent-Length: 5\r\n\r\nfromB" if not body else
|
||
b"HTTP/1.1 200 OK\r\nContent-Length: 5\r\n\r\npostB")
|
||
await writer.drain()
|
||
|
||
async def read_head(reader):
|
||
try:
|
||
return await reader.readuntil(b"\r\n\r\n")
|
||
except asyncio.IncompleteReadError:
|
||
return None
|
||
|
||
def content_length(head):
|
||
for line in head.split(b"\r\n"):
|
||
if line.lower().startswith(b"content-length:"):
|
||
return int(line.split(b":", 1)[1].strip())
|
||
return 0
|
||
|
||
server_a = await asyncio.start_server(target_a, '127.0.0.1', 0)
|
||
server_b = await asyncio.start_server(target_b, '127.0.0.1', 0)
|
||
port_a = server_a.sockets[0].getsockname()[1]
|
||
port_b = server_b.sockets[0].getsockname()[1]
|
||
proxy_server = await start_proxy(
|
||
'127.0.0.1', 0,
|
||
lambda host: {'route': 'DIRECT'},
|
||
lambda: {'proxy_host': '127.0.0.1', 'proxy_port': 1},
|
||
)
|
||
proxy_port = proxy_server.sockets[0].getsockname()[1]
|
||
try:
|
||
reader, writer = await asyncio.open_connection('127.0.0.1', proxy_port)
|
||
|
||
async def request(raw):
|
||
writer.write(raw)
|
||
await writer.drain()
|
||
head = await reader.readuntil(b'\r\n\r\n')
|
||
length = content_length(head)
|
||
return head, await reader.readexactly(length) if length else b''
|
||
|
||
_, body = await request(f'GET http://127.0.0.1:{port_a}/first HTTP/1.1\r\nHost: 127.0.0.1:{port_a}\r\n\r\n'.encode())
|
||
assert body == b'fromA'
|
||
# Второй запрос по ТОМУ ЖЕ соединению — на другой хост (регрессия:
|
||
# раньше он улетал в апстрим первого запроса).
|
||
_, body = await request(f'GET http://127.0.0.1:{port_b}/second HTTP/1.1\r\nHost: 127.0.0.1:{port_b}\r\n\r\n'.encode())
|
||
assert body == b'fromB'
|
||
# Третий — POST с телом, снова первый хост.
|
||
_, body = await request(
|
||
f'POST http://127.0.0.1:{port_a}/third HTTP/1.1\r\nHost: 127.0.0.1:{port_a}\r\nContent-Length: 4\r\n\r\nDATA'.encode()
|
||
)
|
||
assert body == b'postA'
|
||
|
||
writer.close()
|
||
await writer.wait_closed()
|
||
await asyncio.sleep(0.1)
|
||
assert seen_a == [b'GET /first HTTP/1.1', b'POST /third HTTP/1.1']
|
||
assert seen_b == [b'GET /second HTTP/1.1']
|
||
finally:
|
||
proxy_server.close()
|
||
server_a.close()
|
||
server_b.close()
|
||
await proxy_server.wait_closed()
|
||
await server_a.wait_closed()
|
||
await server_b.wait_closed()
|
||
|
||
asyncio.run(scenario())
|