feat(中间层): 实现 Lua 插件驱动的安全代理
新增固定上游的 HTTP/SSE 转发、Lua 插件生命周期和请求级进程隔离。 实现逐插件域名与内网白名单、DNS 地址固定、超时取消和受控错误收尾。 提供三个 Lua 示例插件、配置与开发文档、Docker 和 APISIX 部署示例。 通过 65 项测试及静态检查,验证真实 TCP 流式转发、取消、资源限制和 Windows 命令行启动。
This commit is contained in:
commit
d0bb045134
28 files changed
+2764
No files matched your search
@@ -0,0 +1,45 @@
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
from pydantic import ValidationError
|
||||
|
||||
from middleware.config import NetworkRule, Settings, load_settings
|
||||
|
||||
|
||||
def test_configuration_and_paths():
|
||||
settings = load_settings(Path(__file__).parents[1] / "config.yaml")
|
||||
assert settings.plugins[0].file.is_absolute()
|
||||
assert settings.limits.max_sessions == 4
|
||||
|
||||
|
||||
def test_duplicate_ids_and_missing_file(tmp_path):
|
||||
path = tmp_path / "config.yaml"
|
||||
path.write_text(
|
||||
"upstream: http://agent:8000\nplugins:\n - id: x\n file: absent.lua\n", encoding="utf-8"
|
||||
)
|
||||
with pytest.raises(ValueError):
|
||||
load_settings(path)
|
||||
with pytest.raises(ValidationError):
|
||||
Settings(
|
||||
upstream="http://agent",
|
||||
plugins=[
|
||||
{"id": "x", "file": "a.lua"},
|
||||
{"id": "x", "file": "b.lua"},
|
||||
],
|
||||
)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("domain", ["*", "bad/example.com", "foo..com", "127.0.0.1", "*.com*"])
|
||||
def test_bad_domains(domain):
|
||||
with pytest.raises(ValueError):
|
||||
NetworkRule(domain=domain)
|
||||
|
||||
|
||||
def test_wildcard_and_idna():
|
||||
rule = NetworkRule(domain="*.EXAMPLE.com.")
|
||||
assert rule.matches("a.example.com", "https", 443)
|
||||
assert rule.matches("a.b.example.com", "https", 443)
|
||||
assert not rule.matches("example.com", "https", 443)
|
||||
assert not rule.matches("badexample.com", "https", 443)
|
||||
assert not rule.matches("a.example.com", "http", 443)
|
||||
assert NetworkRule(domain="例子.测试").domain == "xn--fsqu00a.xn--0zwm56d"
|
||||
@@ -0,0 +1,95 @@
|
||||
"""Native TCP client → Uvicorn middleware → mock agent, including SSE cancellation."""
|
||||
|
||||
import asyncio
|
||||
from contextlib import asynccontextmanager
|
||||
|
||||
import httpx
|
||||
import uvicorn
|
||||
from aiohttp import web
|
||||
from test_proxy import frame, settings_for, upstream_server
|
||||
|
||||
from middleware.proxy import create_app
|
||||
from middleware.sse import encode_sse
|
||||
|
||||
|
||||
@asynccontextmanager
|
||||
async def running_service(app):
|
||||
server = uvicorn.Server(
|
||||
uvicorn.Config(
|
||||
app,
|
||||
host="127.0.0.1",
|
||||
port=0,
|
||||
log_level="critical",
|
||||
access_log=False,
|
||||
)
|
||||
)
|
||||
task = asyncio.create_task(server.serve())
|
||||
try:
|
||||
async with asyncio.timeout(10):
|
||||
while not server.started:
|
||||
if task.done():
|
||||
await task
|
||||
raise RuntimeError("server exited before startup")
|
||||
await asyncio.sleep(0.01)
|
||||
port = server.servers[0].sockets[0].getsockname()[1]
|
||||
yield f"http://127.0.0.1:{port}"
|
||||
finally:
|
||||
server.should_exit = True
|
||||
await asyncio.wait_for(task, 10)
|
||||
|
||||
|
||||
async def test_real_tcp_stream_overload_and_disconnect(tmp_path):
|
||||
release = asyncio.Event()
|
||||
agent_cancelled = asyncio.Event()
|
||||
|
||||
async def handler(request):
|
||||
message = (await request.json())["message"]
|
||||
response = web.StreamResponse(headers={"Content-Type": "text/event-stream"})
|
||||
await response.prepare(request)
|
||||
await response.write(encode_sse(frame("run_started", 1, {}), 1024))
|
||||
if message == "stream":
|
||||
await release.wait()
|
||||
await response.write(encode_sse(frame("text_delta", 2, {"content": "中文"}), 1024))
|
||||
await response.write(encode_sse(frame("run_completed", 3, {"status": "success"}), 1024))
|
||||
else:
|
||||
try:
|
||||
for _ in range(100):
|
||||
await asyncio.sleep(0.02)
|
||||
await response.write(b": heartbeat\n\n")
|
||||
except (ConnectionError, asyncio.CancelledError):
|
||||
agent_cancelled.set()
|
||||
return response
|
||||
|
||||
async with upstream_server(handler) as upstream:
|
||||
app = create_app(settings_for(tmp_path, upstream, max_sessions=1))
|
||||
async with running_service(app) as url, httpx.AsyncClient(base_url=url) as client:
|
||||
assert (await client.get("/readyz")).status_code == 200
|
||||
async with client.stream(
|
||||
"POST", "/chat/stream", json={"message": "stream"}
|
||||
) as response:
|
||||
lines = response.aiter_lines()
|
||||
first_event = []
|
||||
async with asyncio.timeout(3):
|
||||
async for line in lines:
|
||||
first_event.append(line)
|
||||
if not line:
|
||||
break
|
||||
assert "event: run_started" in first_event
|
||||
# First frame reached the client while the agent's remaining output is blocked.
|
||||
assert not release.is_set()
|
||||
assert (
|
||||
await client.post("/chat/stream", json={"message": "overload"})
|
||||
).status_code == 503
|
||||
release.set()
|
||||
remainder = "\n".join([line async for line in lines])
|
||||
assert "中文" in remainder and "event: run_completed" in remainder
|
||||
async with client.stream(
|
||||
"POST", "/chat/stream", json={"message": "disconnect"}
|
||||
) as response:
|
||||
async for line in response.aiter_lines():
|
||||
if line == "event: run_started":
|
||||
break
|
||||
await asyncio.wait_for(agent_cancelled.wait(), 3)
|
||||
async with asyncio.timeout(3):
|
||||
while app.state.manager.sessions:
|
||||
await asyncio.sleep(0.01)
|
||||
@@ -0,0 +1,238 @@
|
||||
import asyncio
|
||||
import socket
|
||||
|
||||
import pytest
|
||||
|
||||
from middleware.config import NetworkPolicy, NetworkRule
|
||||
from middleware.errors import LimitExceeded, NetworkDenied
|
||||
from middleware.network import NetworkBroker, PolicyResolver, address_allowed, approved_url
|
||||
|
||||
|
||||
def policy(**kwargs):
|
||||
return NetworkPolicy(allow=[NetworkRule(domain="*.example.com", **kwargs)])
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"url",
|
||||
[
|
||||
"https://example.com/",
|
||||
"https://badexample.com/",
|
||||
"http://a.example.com/",
|
||||
"https://a.example.com:444/",
|
||||
"https://user:pw@a.example.com/",
|
||||
"https://127.0.0.1/",
|
||||
"https://[::1]/",
|
||||
"https://2130706433/",
|
||||
"https://a.example.com.evil.test/",
|
||||
"file:///etc/passwd",
|
||||
"https://a.example.com\n/",
|
||||
],
|
||||
)
|
||||
def test_urls_denied(url):
|
||||
with pytest.raises(NetworkDenied):
|
||||
approved_url(url, policy())
|
||||
|
||||
|
||||
def test_exact_domain_and_case():
|
||||
url, _ = approved_url("https://A.Example.com./check", policy())
|
||||
assert url.host == "a.example.com"
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"address",
|
||||
[
|
||||
"127.0.0.1",
|
||||
"::1",
|
||||
"169.254.169.254",
|
||||
"100.100.100.200",
|
||||
"fd00:ec2::254",
|
||||
"224.0.0.1",
|
||||
"0.0.0.0",
|
||||
"::ffff:127.0.0.1",
|
||||
"240.1.1.1",
|
||||
"::",
|
||||
],
|
||||
)
|
||||
def test_permanent_denials_even_with_cidrs(address):
|
||||
rules = [NetworkRule(domain="a.example.com", cidrs=["0.0.0.0/0", "::/0"])]
|
||||
assert not address_allowed(address, rules)
|
||||
|
||||
|
||||
def test_private_network_must_be_explicit():
|
||||
rules = [NetworkRule(domain="a.example.com", cidrs=["10.20.0.0/16"])]
|
||||
assert address_allowed("8.8.8.8", rules)
|
||||
assert address_allowed("10.20.1.2", rules)
|
||||
assert not address_allowed("10.21.1.2", rules)
|
||||
assert not address_allowed("10.20.1.2", [NetworkRule(domain="a.example.com")])
|
||||
|
||||
|
||||
async def test_resolver_rejects_mixed_answers_and_pins_numeric_addresses(monkeypatch):
|
||||
loop = asyncio.get_running_loop()
|
||||
calls = []
|
||||
|
||||
async def lookup(host, port, **kwargs):
|
||||
calls.append(host)
|
||||
return [(socket.AF_INET, socket.SOCK_STREAM, 6, "", ("8.8.8.8", port))]
|
||||
|
||||
monkeypatch.setattr(loop, "getaddrinfo", lookup)
|
||||
resolver = PolicyResolver("a.example.com", policy().allow)
|
||||
addresses = await resolver.resolve("a.example.com", 443)
|
||||
assert calls == ["a.example.com"]
|
||||
assert addresses[0]["host"] == "8.8.8.8"
|
||||
assert addresses[0]["hostname"] == "a.example.com"
|
||||
assert addresses[0]["flags"] == socket.AI_NUMERICHOST
|
||||
|
||||
async def mixed(host, port, **kwargs):
|
||||
return [
|
||||
(socket.AF_INET, socket.SOCK_STREAM, 6, "", (ip, port))
|
||||
for ip in ["8.8.8.8", "127.0.0.1"]
|
||||
]
|
||||
|
||||
monkeypatch.setattr(loop, "getaddrinfo", mixed)
|
||||
with pytest.raises(NetworkDenied):
|
||||
await resolver.resolve("a.example.com", 443)
|
||||
with pytest.raises(NetworkDenied):
|
||||
await resolver.resolve("b.example.com", 443)
|
||||
|
||||
|
||||
async def test_broker_disables_proxy_redirect_and_cookies(monkeypatch):
|
||||
import middleware.network as module
|
||||
|
||||
seen = {}
|
||||
|
||||
class Content:
|
||||
async def iter_chunked(self, size):
|
||||
yield b"{}"
|
||||
|
||||
class Response:
|
||||
status = 302
|
||||
headers = {"Location": "http://127.0.0.1/admin"}
|
||||
content = Content()
|
||||
|
||||
async def __aenter__(self):
|
||||
return self
|
||||
|
||||
async def __aexit__(self, *args):
|
||||
pass
|
||||
|
||||
class Client:
|
||||
def __init__(self, **kwargs):
|
||||
seen.update(kwargs)
|
||||
|
||||
async def __aenter__(self):
|
||||
return self
|
||||
|
||||
async def __aexit__(self, *args):
|
||||
await seen["connector"].close()
|
||||
|
||||
def request(self, method, url, **kwargs):
|
||||
seen["request"] = kwargs
|
||||
return Response()
|
||||
|
||||
monkeypatch.setenv("HTTPS_PROXY", "http://127.0.0.1:3128")
|
||||
monkeypatch.setattr(module.aiohttp, "ClientSession", Client)
|
||||
result = await NetworkBroker().request(
|
||||
policy(),
|
||||
{
|
||||
"url": "https://a.example.com/",
|
||||
"headers": {"Host": "other", "X-Test": "ok"},
|
||||
},
|
||||
100,
|
||||
)
|
||||
assert result["status"] == 302
|
||||
assert seen["trust_env"] is False
|
||||
assert seen["request"]["allow_redirects"] is False
|
||||
assert seen["request"]["headers"] == {"X-Test": "ok"}
|
||||
assert isinstance(seen["connector"]._resolver, PolicyResolver)
|
||||
assert seen["connector"]._use_dns_cache is False
|
||||
assert seen["connector"]._ssl is True
|
||||
with pytest.raises(LimitExceeded):
|
||||
await NetworkBroker().request(policy(), {"url": "https://a.example.com", "body": "xx"}, 1)
|
||||
|
||||
|
||||
async def test_broker_response_cap_and_timeout(monkeypatch):
|
||||
import middleware.network as module
|
||||
|
||||
class Content:
|
||||
async def iter_chunked(self, size):
|
||||
yield b"too-large"
|
||||
|
||||
class Response:
|
||||
status = 200
|
||||
headers = {}
|
||||
content = Content()
|
||||
|
||||
async def __aenter__(self):
|
||||
return self
|
||||
|
||||
async def __aexit__(self, *args):
|
||||
pass
|
||||
|
||||
class Client:
|
||||
def __init__(self, **kwargs):
|
||||
self.connector = kwargs["connector"]
|
||||
|
||||
async def __aenter__(self):
|
||||
return self
|
||||
|
||||
async def __aexit__(self, *args):
|
||||
await self.connector.close()
|
||||
|
||||
def request(self, *args, **kwargs):
|
||||
return Response()
|
||||
|
||||
monkeypatch.setattr(module.aiohttp, "ClientSession", Client)
|
||||
restricted = policy().model_copy(update={"max_response_bytes": 3})
|
||||
with pytest.raises(LimitExceeded):
|
||||
await NetworkBroker().request(restricted, {"url": "https://a.example.com"}, 100)
|
||||
|
||||
|
||||
async def test_real_client_uses_pinned_address_without_second_dns_or_redirect(monkeypatch):
|
||||
# Test-only transport redirection lets a real aiohttp client use a local fake service
|
||||
# while observing the approved numeric address presented to the actual connector.
|
||||
import aiohttp
|
||||
from aiohttp import web
|
||||
|
||||
hits = []
|
||||
|
||||
async def handler(request):
|
||||
hits.append(request.headers["Host"])
|
||||
return web.Response(status=302, headers={"Location": "http://127.0.0.1/admin"})
|
||||
|
||||
app = web.Application()
|
||||
app.router.add_get("/", handler)
|
||||
runner = web.AppRunner(app)
|
||||
await runner.setup()
|
||||
site = web.TCPSite(runner, "127.0.0.1", 0)
|
||||
await site.start()
|
||||
port = site._server.sockets[0].getsockname()[1]
|
||||
lookups = []
|
||||
|
||||
async def rebinding_dns(host, requested_port, **kwargs):
|
||||
lookups.append(host)
|
||||
ip = "8.8.8.8" if len(lookups) == 1 else "127.0.0.1"
|
||||
return [(socket.AF_INET, socket.SOCK_STREAM, 6, "", (ip, requested_port))]
|
||||
|
||||
original = aiohttp.TCPConnector._wrap_create_connection
|
||||
|
||||
async def observed_connect(self, *args, addr_infos, **kwargs):
|
||||
assert addr_infos[0][4][0] == "8.8.8.8"
|
||||
assert kwargs["req"].url.host == "a.example.com"
|
||||
local = [(socket.AF_INET, socket.SOCK_STREAM, 6, "", ("127.0.0.1", port))]
|
||||
return await original(self, *args, addr_infos=local, **kwargs)
|
||||
|
||||
monkeypatch.setattr(asyncio.get_running_loop(), "getaddrinfo", rebinding_dns)
|
||||
monkeypatch.setattr(aiohttp.TCPConnector, "_wrap_create_connection", observed_connect)
|
||||
monkeypatch.setenv("HTTP_PROXY", "http://127.0.0.1:1")
|
||||
configured = NetworkPolicy(
|
||||
allow=[NetworkRule(domain="a.example.com", scheme="http", ports=[port])]
|
||||
)
|
||||
try:
|
||||
response = await NetworkBroker().request(
|
||||
configured, {"url": f"http://a.example.com:{port}/"}, 100
|
||||
)
|
||||
assert response["status"] == 302
|
||||
assert lookups == ["a.example.com"]
|
||||
assert hits == [f"a.example.com:{port}"]
|
||||
finally:
|
||||
await runner.cleanup()
|
||||
@@ -0,0 +1,323 @@
|
||||
import asyncio
|
||||
import json
|
||||
from contextlib import asynccontextmanager
|
||||
|
||||
import httpx
|
||||
import pytest
|
||||
from aiohttp import web
|
||||
|
||||
from middleware.config import Limits, PluginConfig, Settings
|
||||
from middleware.proxy import create_app
|
||||
from middleware.sse import decode_sse, encode_sse
|
||||
|
||||
|
||||
def frame(name, sequence, data):
|
||||
return {
|
||||
"event": name,
|
||||
"id": str(sequence),
|
||||
"has_data": True,
|
||||
"data": json.dumps(
|
||||
{
|
||||
"request_id": "00000000-0000-4000-8000-000000000000",
|
||||
"sequence": sequence,
|
||||
"timestamp": "2026-10-08T00:00:00+00:00",
|
||||
"data": data,
|
||||
},
|
||||
ensure_ascii=False,
|
||||
),
|
||||
}
|
||||
|
||||
|
||||
@asynccontextmanager
|
||||
async def upstream_server(handler):
|
||||
app = web.Application()
|
||||
app.router.add_post("/chat/stream", handler)
|
||||
runner = web.AppRunner(app)
|
||||
await runner.setup()
|
||||
site = web.TCPSite(runner, "127.0.0.1", 0)
|
||||
await site.start()
|
||||
port = site._server.sockets[0].getsockname()[1]
|
||||
try:
|
||||
yield f"http://127.0.0.1:{port}"
|
||||
finally:
|
||||
await runner.cleanup()
|
||||
|
||||
|
||||
def settings_for(tmp_path, upstream, source=None, **limits):
|
||||
plugins = []
|
||||
if source is not None:
|
||||
file = tmp_path / "test.lua"
|
||||
file.write_text(source, encoding="utf-8")
|
||||
plugins.append(PluginConfig(id="test", file=file))
|
||||
return Settings(upstream=upstream, plugins=plugins, limits=Limits(**limits))
|
||||
|
||||
|
||||
@asynccontextmanager
|
||||
async def client_for(settings):
|
||||
app = create_app(settings)
|
||||
async with app.router.lifespan_context(app):
|
||||
async with httpx.AsyncClient(
|
||||
transport=httpx.ASGITransport(app), base_url="http://middleware"
|
||||
) as client:
|
||||
yield client, app
|
||||
|
||||
|
||||
async def event_list(content):
|
||||
async def pieces():
|
||||
for byte in content:
|
||||
yield bytes([byte])
|
||||
|
||||
return [e async for e in decode_sse(pieces(), 262144)]
|
||||
|
||||
|
||||
async def test_passthrough_sse_and_health(tmp_path):
|
||||
expected = [
|
||||
frame("run_started", 1, {"conversation_id": "c"}),
|
||||
frame("text_delta", 2, {"content": "中文"}),
|
||||
frame("mcp_call_started", 3, {"server": "weather", "tool": "query"}),
|
||||
frame("mcp_call_finished", 4, {"status": "success"}),
|
||||
frame("run_completed", 5, {"status": "success"}),
|
||||
]
|
||||
received = []
|
||||
queries = []
|
||||
|
||||
async def handler(request):
|
||||
received.append(await request.json())
|
||||
queries.append(request.rel_url.raw_query_string)
|
||||
response = web.StreamResponse(headers={"Content-Type": "text/event-stream"})
|
||||
await response.prepare(request)
|
||||
for item in expected:
|
||||
# Exercise real upstream network chunking including split Chinese UTF-8.
|
||||
for byte in encode_sse(item, 262144):
|
||||
await response.write(bytes([byte]))
|
||||
await response.write_eof()
|
||||
return response
|
||||
|
||||
async with upstream_server(handler) as upstream:
|
||||
async with client_for(settings_for(tmp_path, upstream)) as (client, app):
|
||||
assert (await client.get("/healthz")).json() == {"status": "ok"}
|
||||
assert (await client.get("/readyz")).status_code == 200
|
||||
result = await client.post(
|
||||
"/chat/stream?token=a%2Fb&x=a+b", json={"message": "你好", "conversation_id": "c"}
|
||||
)
|
||||
assert result.status_code == 200
|
||||
events = await event_list(result.content)
|
||||
assert [e["event"] for e in events] == [e["event"] for e in expected]
|
||||
assert [json.loads(e["data"]) for e in events] == [
|
||||
json.loads(e["data"]) for e in expected
|
||||
]
|
||||
assert received == [{"message": "你好", "conversation_id": "c"}]
|
||||
assert queries == ["token=a%2Fb&x=a+b"]
|
||||
assert not app.state.manager.sessions
|
||||
|
||||
|
||||
async def test_block_request_never_reaches_agent(tmp_path):
|
||||
calls = []
|
||||
|
||||
async def handler(request):
|
||||
calls.append(1)
|
||||
return web.json_response({})
|
||||
|
||||
async with upstream_server(handler) as upstream:
|
||||
settings = settings_for(
|
||||
tmp_path, upstream, "return {on_request=function() return {action='block'} end}"
|
||||
)
|
||||
async with client_for(settings) as (client, app):
|
||||
assert (await client.post("/chat/stream", json={"message": "x"})).status_code == 403
|
||||
assert not calls
|
||||
assert not app.state.manager.sessions
|
||||
|
||||
|
||||
async def test_json_rewrite_and_non_stream_response(tmp_path):
|
||||
async def handler(request):
|
||||
data = await request.json()
|
||||
return web.json_response({"echo": data["message"]})
|
||||
|
||||
source = """
|
||||
return {on_request=function(ctx,r)
|
||||
local b=host.json.decode(r.body); b.message='rewritten'
|
||||
r.body=host.json.encode(b); return {action='replace',value=r}
|
||||
end,on_response=function(ctx,r)
|
||||
local b=host.json.decode(r.body); b.checked=true
|
||||
r.body=host.json.encode(b); return {action='replace',value=r}
|
||||
end}
|
||||
"""
|
||||
async with upstream_server(handler) as upstream:
|
||||
async with client_for(settings_for(tmp_path, upstream, source)) as (client, _):
|
||||
result = await client.post("/chat/stream", json={"message": "x"})
|
||||
assert result.json() == {"echo": "rewritten", "checked": True}
|
||||
|
||||
|
||||
@pytest.mark.parametrize("hook", ["on_event", "on_end"])
|
||||
async def test_stream_failure_has_run_error_without_success(tmp_path, hook, caplog):
|
||||
async def handler(request):
|
||||
return web.Response(
|
||||
body=b"".join(
|
||||
encode_sse(e, 1024)
|
||||
for e in [
|
||||
frame("run_started", 1, {}),
|
||||
frame("text_delta", 2, {"content": "secret"}),
|
||||
frame("run_completed", 3, {"status": "success"}),
|
||||
]
|
||||
),
|
||||
content_type="text/event-stream",
|
||||
)
|
||||
|
||||
source = (
|
||||
"return {on_event=function(ctx,e) if e.event=='text_delta' then error('private-key') end end}"
|
||||
if hook == "on_event"
|
||||
else "return {on_end=function() error('private-key') end}"
|
||||
)
|
||||
async with upstream_server(handler) as upstream:
|
||||
async with client_for(settings_for(tmp_path, upstream, source)) as (client, app):
|
||||
result = await client.post("/chat/stream", json={"message": "x"})
|
||||
events = await event_list(result.content)
|
||||
assert events[-1]["event"] == "run_error"
|
||||
assert not any(e["event"] == "run_completed" for e in events)
|
||||
payload = json.loads(events[-1]["data"])
|
||||
assert payload["timestamp"]
|
||||
assert payload["request_id"] == "00000000-0000-4000-8000-000000000000"
|
||||
assert payload["data"] == {"error_type": "MiddlewareFailure"}
|
||||
assert "private-key" not in result.text + caplog.text
|
||||
assert not app.state.manager.sessions
|
||||
|
||||
|
||||
async def test_stream_size_failure_and_request_limit(tmp_path):
|
||||
async def handler(request):
|
||||
return web.Response(
|
||||
body=b"data: " + b"x" * 1000 + b"\n\n", content_type="text/event-stream"
|
||||
)
|
||||
|
||||
async with upstream_server(handler) as upstream:
|
||||
settings = settings_for(tmp_path, upstream, max_sse_frame_bytes=500, max_request_bytes=100)
|
||||
async with client_for(settings) as (client, _):
|
||||
result = await client.post("/chat/stream", content=b"x" * 101)
|
||||
assert result.status_code == 413
|
||||
result = await client.post("/chat/stream", json={"message": "x"})
|
||||
assert (await event_list(result.content))[-1]["event"] == "run_error"
|
||||
|
||||
|
||||
async def test_disconnect_before_first_chunk_releases_session(tmp_path):
|
||||
cancelled = asyncio.Event()
|
||||
|
||||
async def handler(request):
|
||||
response = web.StreamResponse(headers={"Content-Type": "text/event-stream"})
|
||||
await response.prepare(request)
|
||||
try:
|
||||
for _ in range(100):
|
||||
await asyncio.sleep(0.02)
|
||||
await response.write(b": heartbeat\n\n")
|
||||
except (ConnectionError, asyncio.CancelledError):
|
||||
cancelled.set()
|
||||
return response
|
||||
|
||||
async with upstream_server(handler) as upstream:
|
||||
app = create_app(settings_for(tmp_path, upstream))
|
||||
async with app.router.lifespan_context(app):
|
||||
queue = asyncio.Queue()
|
||||
await queue.put(
|
||||
{"type": "http.request", "body": b'{"message":"x"}', "more_body": False}
|
||||
)
|
||||
|
||||
async def send(message):
|
||||
if message["type"] == "http.response.start":
|
||||
await queue.put({"type": "http.disconnect"})
|
||||
|
||||
scope = {
|
||||
"type": "http",
|
||||
"asgi": {"version": "3.0", "spec_version": "2.4"},
|
||||
"http_version": "1.1",
|
||||
"method": "POST",
|
||||
"scheme": "http",
|
||||
"path": "/chat/stream",
|
||||
"raw_path": b"/chat/stream",
|
||||
"query_string": b"",
|
||||
"headers": [(b"content-type", b"application/json")],
|
||||
"server": ("middleware", 80),
|
||||
"client": ("client", 1),
|
||||
}
|
||||
await asyncio.wait_for(app(scope, queue.get, send), 5)
|
||||
assert not app.state.manager.sessions
|
||||
await asyncio.wait_for(cancelled.wait(), 2)
|
||||
|
||||
|
||||
async def test_blocked_stream_discards_frame_and_adapter_failure_closes(tmp_path):
|
||||
async def handler(request):
|
||||
return web.Response(
|
||||
body=b"".join(
|
||||
encode_sse(e, 1024)
|
||||
for e in [
|
||||
frame("run_started", 1, {}),
|
||||
frame("text_delta", 2, {"content": "DO-NOT-SEND"}),
|
||||
frame("run_completed", 3, {"status": "success"}),
|
||||
]
|
||||
),
|
||||
content_type="text/event-stream",
|
||||
)
|
||||
|
||||
source = "return {on_event=function(ctx,e) if e.event=='text_delta' then return {action='block'} end end}"
|
||||
async with upstream_server(handler) as upstream:
|
||||
async with client_for(settings_for(tmp_path, upstream, source)) as (client, app):
|
||||
result = await client.post("/chat/stream", json={"message": "x"})
|
||||
events = await event_list(result.content)
|
||||
assert events[-1]["event"] == "run_error"
|
||||
assert json.loads(events[-1]["data"])["data"]["error_type"] == "PolicyBlocked"
|
||||
assert "DO-NOT-SEND" not in result.text
|
||||
|
||||
async def broken_adapter(*args):
|
||||
raise RuntimeError("private adapter detail")
|
||||
|
||||
app.state.manager.error_event = broken_adapter
|
||||
result = await client.post("/chat/stream", json={"message": "x"})
|
||||
assert [e["event"] for e in await event_list(result.content)] == ["run_started"]
|
||||
assert "private adapter detail" not in result.text
|
||||
assert not app.state.manager.sessions
|
||||
|
||||
|
||||
async def test_plugin_failure_before_response_and_nonstream_limit(tmp_path):
|
||||
calls = []
|
||||
|
||||
async def handler(request):
|
||||
calls.append(1)
|
||||
return web.json_response({"long": "x" * 100})
|
||||
|
||||
async with upstream_server(handler) as upstream:
|
||||
source = "return {on_request=function() error('sensitive-input') end}"
|
||||
async with client_for(settings_for(tmp_path, upstream, source)) as (client, _):
|
||||
result = await client.post("/chat/stream", json={"message": "x"})
|
||||
assert result.status_code == 502
|
||||
assert not calls
|
||||
async with client_for(settings_for(tmp_path, upstream, max_response_bytes=10)) as (
|
||||
client,
|
||||
app,
|
||||
):
|
||||
result = await client.post("/chat/stream", json={"message": "x"})
|
||||
assert result.status_code == 502
|
||||
assert not app.state.manager.sessions
|
||||
|
||||
|
||||
async def test_stream_total_deadline_closes_upstream(tmp_path):
|
||||
closed = asyncio.Event()
|
||||
|
||||
async def handler(request):
|
||||
response = web.StreamResponse(headers={"Content-Type": "text/event-stream"})
|
||||
await response.prepare(request)
|
||||
await response.write(encode_sse(frame("run_started", 1, {}), 1024))
|
||||
try:
|
||||
while True:
|
||||
await asyncio.sleep(0.02)
|
||||
await response.write(b": heartbeat\n\n")
|
||||
except ConnectionError:
|
||||
closed.set()
|
||||
return response
|
||||
|
||||
async with upstream_server(handler) as upstream:
|
||||
async with client_for(settings_for(tmp_path, upstream, upstream_timeout_seconds=0.8)) as (
|
||||
client,
|
||||
app,
|
||||
):
|
||||
result = await client.post("/chat/stream", json={"message": "x"})
|
||||
events = await event_list(result.content)
|
||||
assert events[-1]["event"] == "run_error"
|
||||
assert not app.state.manager.sessions
|
||||
await asyncio.wait_for(closed.wait(), 2)
|
||||
@@ -0,0 +1,337 @@
|
||||
import asyncio
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
|
||||
from middleware.config import Limits, PluginConfig, Settings
|
||||
from middleware.errors import LimitExceeded, Overloaded, PluginFailure, PolicyBlocked
|
||||
from middleware.runtime import PluginManager
|
||||
|
||||
|
||||
def manager_for(tmp_path, sources, **limits):
|
||||
plugins = []
|
||||
for index, source in enumerate(sources):
|
||||
path = tmp_path / f"plugin{index}.lua"
|
||||
path.write_text(source, encoding="utf-8")
|
||||
plugins.append(PluginConfig(id=f"plugin{index}", file=path))
|
||||
return PluginManager(
|
||||
Settings(upstream="http://agent:8000", plugins=plugins, limits=Limits(**limits))
|
||||
)
|
||||
|
||||
|
||||
async def test_chain_isolation_json_and_disabled(tmp_path):
|
||||
manager = manager_for(
|
||||
tmp_path,
|
||||
[
|
||||
"""
|
||||
local count = 0
|
||||
return {on_request=function(ctx, r)
|
||||
count=count+1
|
||||
local body=host.json.decode(r.body)
|
||||
assert(body.empty == host.json.null)
|
||||
assert(#body.items == 0)
|
||||
body.count=count
|
||||
r.body=host.json.encode(body)
|
||||
return {action='replace', value=r}
|
||||
end}
|
||||
""",
|
||||
"""
|
||||
return {on_request=function(ctx,r)
|
||||
local body=host.json.decode(r.body)
|
||||
assert(body.count==1)
|
||||
body.ok=true
|
||||
r.body=host.json.encode(body)
|
||||
return {action='replace',value=r}
|
||||
end}
|
||||
""",
|
||||
],
|
||||
)
|
||||
for _ in range(2):
|
||||
session = await manager.open()
|
||||
try:
|
||||
result = await session.apply("on_request", {"body": '{"items":[],"empty":null}'})
|
||||
assert '"count":1' in result[0]["body"]
|
||||
assert '"items":[]' in result[0]["body"]
|
||||
finally:
|
||||
await session.aclose()
|
||||
assert not manager.sessions
|
||||
|
||||
|
||||
async def test_hold_flush_runs_downstream(tmp_path):
|
||||
manager = manager_for(
|
||||
tmp_path,
|
||||
[
|
||||
"""
|
||||
local stored={}
|
||||
return {
|
||||
on_event=function(ctx,e) stored[#stored+1]=e; return {action='hold'} end,
|
||||
on_end=function(ctx) return {action='replace',events=host.json.array(stored)} end,
|
||||
}
|
||||
""",
|
||||
"""
|
||||
return {on_event=function(ctx,e)
|
||||
e.data=e.data..' checked'
|
||||
return {action='replace',events={e}}
|
||||
end}
|
||||
""",
|
||||
],
|
||||
)
|
||||
session = await manager.open()
|
||||
try:
|
||||
assert await session.apply("on_event", {"data": "secret"}) == []
|
||||
assert await session.end() == [{"data": "secret checked"}]
|
||||
finally:
|
||||
await session.aclose()
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"source",
|
||||
[
|
||||
"return {on_request=function() return {action='block'} end}",
|
||||
"return {on_request=function() return {action='whatever'} end}",
|
||||
"return {on_request=function() error('secret credential') end}",
|
||||
],
|
||||
)
|
||||
async def test_block_bad_results_and_errors(tmp_path, source, caplog):
|
||||
manager = manager_for(tmp_path, [source])
|
||||
session = await manager.open()
|
||||
try:
|
||||
with pytest.raises((PolicyBlocked, PluginFailure)):
|
||||
await session.apply("on_request", {})
|
||||
finally:
|
||||
await session.aclose()
|
||||
assert "secret credential" not in caplog.text
|
||||
|
||||
|
||||
async def test_timeout_overload_and_recovery(tmp_path):
|
||||
manager = manager_for(
|
||||
tmp_path, ["return {on_request=function() while true do end end}"], max_sessions=1
|
||||
)
|
||||
session = await manager.open()
|
||||
with pytest.raises(Overloaded):
|
||||
await manager.open()
|
||||
manager.settings = manager.settings.model_copy(
|
||||
update={"limits": manager.settings.limits.model_copy(update={"hook_timeout_seconds": 0.15})}
|
||||
)
|
||||
try:
|
||||
with pytest.raises(PluginFailure):
|
||||
await session.apply("on_request", {})
|
||||
assert not session.process.is_alive()
|
||||
finally:
|
||||
await session.aclose()
|
||||
manager.settings = manager.settings.model_copy(update={"limits": Limits(max_sessions=1)})
|
||||
second = await manager.open()
|
||||
await second.aclose()
|
||||
|
||||
|
||||
async def test_cancel_kills_worker(tmp_path):
|
||||
manager = manager_for(tmp_path, ["return {on_request=function() while true do end end}"])
|
||||
session = await manager.open()
|
||||
task = asyncio.create_task(session.apply("on_request", {}))
|
||||
await asyncio.sleep(0.05)
|
||||
task.cancel()
|
||||
with pytest.raises(asyncio.CancelledError):
|
||||
await task
|
||||
await session.aclose()
|
||||
assert not session.process.is_alive()
|
||||
|
||||
|
||||
async def test_sandbox_and_python_callback_attributes(tmp_path):
|
||||
manager = manager_for(
|
||||
tmp_path,
|
||||
[
|
||||
"""
|
||||
return {on_request=function(ctx,r)
|
||||
assert(os==nil and io==nil and debug==nil and package==nil)
|
||||
assert(require==nil and load==nil and python==nil and print==nil)
|
||||
assert(not pcall(function() return host.json.encode.__globals__ end))
|
||||
assert(not pcall(function() return host.http.request.__self__ end))
|
||||
return {action='pass'}
|
||||
end}
|
||||
"""
|
||||
],
|
||||
)
|
||||
session = await manager.open()
|
||||
try:
|
||||
assert await session.apply("on_request", {"body": "x"}) == [{"body": "x"}]
|
||||
finally:
|
||||
await session.aclose()
|
||||
|
||||
|
||||
async def test_invalid_module_init_and_buffer(tmp_path):
|
||||
for source in (
|
||||
"return 3",
|
||||
"return {on_event=3}",
|
||||
"return {init=function() error('private') end}",
|
||||
):
|
||||
manager = manager_for(tmp_path, [source])
|
||||
with pytest.raises(PluginFailure):
|
||||
await manager.validate()
|
||||
assert not manager.sessions
|
||||
manager = manager_for(
|
||||
tmp_path,
|
||||
[
|
||||
"""
|
||||
local stored
|
||||
return {on_event=function(ctx,e) stored=string.rep('x',20000); return {action='hold'} end}
|
||||
"""
|
||||
],
|
||||
max_plugin_buffer_bytes=10000,
|
||||
)
|
||||
session = await manager.open()
|
||||
try:
|
||||
with pytest.raises((PluginFailure, LimitExceeded)):
|
||||
await session.apply("on_event", {"data": "x"})
|
||||
finally:
|
||||
await session.aclose()
|
||||
|
||||
|
||||
async def test_close_failure_does_not_skip_other_plugins(tmp_path, caplog):
|
||||
caplog.set_level("INFO", logger="middleware.audit")
|
||||
manager = manager_for(
|
||||
tmp_path,
|
||||
[
|
||||
"return {close=function() host.log.info('raw-secret') end}",
|
||||
"return {close=function() error('private') end}",
|
||||
],
|
||||
)
|
||||
session = await manager.open()
|
||||
await session.aclose()
|
||||
assert "plugin_log" in caplog.text
|
||||
assert "raw-secret" not in caplog.text
|
||||
|
||||
|
||||
async def test_example_redacts_cross_event_phone(tmp_path):
|
||||
source = (Path(__file__).parents[1] / "plugins/stream_redact.lua").read_text(encoding="utf-8")
|
||||
manager = manager_for(tmp_path, [source])
|
||||
session = await manager.open()
|
||||
try:
|
||||
for content in ["号码138", "1234", "5678"]:
|
||||
import json
|
||||
|
||||
assert (
|
||||
await session.apply(
|
||||
"on_event",
|
||||
{
|
||||
"event": "text_delta",
|
||||
"data": json.dumps({"data": {"content": content}}),
|
||||
},
|
||||
)
|
||||
== []
|
||||
)
|
||||
results = await session.end()
|
||||
text = "".join(json.loads(e["data"])["data"]["content"] for e in results)
|
||||
assert text == "号码***********"
|
||||
finally:
|
||||
await session.aclose()
|
||||
|
||||
|
||||
async def test_lua_memory_exhaustion_and_cyclic_return(tmp_path):
|
||||
for source in [
|
||||
"return {on_request=function() local x=string.rep('x',40000000); return {action='pass'} end}",
|
||||
"return {on_request=function() local x={}; x.self=x; return x end}",
|
||||
]:
|
||||
manager = manager_for(tmp_path, [source])
|
||||
session = await manager.open()
|
||||
try:
|
||||
with pytest.raises(PluginFailure):
|
||||
await session.apply("on_request", {})
|
||||
finally:
|
||||
await session.aclose()
|
||||
|
||||
|
||||
async def test_disabled_invalid_code_is_not_loaded(tmp_path):
|
||||
file = tmp_path / "disabled.lua"
|
||||
file.write_text("not valid lua", encoding="utf-8")
|
||||
manager = PluginManager(
|
||||
Settings(
|
||||
upstream="http://agent",
|
||||
plugins=[PluginConfig(id="off", file=file, enabled=False)],
|
||||
)
|
||||
)
|
||||
await manager.validate()
|
||||
assert not manager.sessions
|
||||
|
||||
|
||||
async def test_network_denial_and_cancellation_through_ipc(tmp_path):
|
||||
source = """
|
||||
return {on_request=function(ctx,r)
|
||||
host.http.request({url='https://a.example.com'})
|
||||
return {action='pass'}
|
||||
end}
|
||||
"""
|
||||
manager = manager_for(tmp_path, [source])
|
||||
session = await manager.open()
|
||||
try:
|
||||
with pytest.raises(PluginFailure):
|
||||
await session.apply("on_request", {})
|
||||
finally:
|
||||
await session.aclose()
|
||||
started, cancelled = asyncio.Event(), asyncio.Event()
|
||||
|
||||
class WaitingBroker:
|
||||
async def request(self, *args):
|
||||
started.set()
|
||||
try:
|
||||
await asyncio.Future()
|
||||
finally:
|
||||
cancelled.set()
|
||||
|
||||
manager.broker = WaitingBroker()
|
||||
session = await manager.open()
|
||||
task = asyncio.create_task(session.apply("on_request", {}))
|
||||
await asyncio.wait_for(started.wait(), 3)
|
||||
task.cancel()
|
||||
with pytest.raises(asyncio.CancelledError):
|
||||
await task
|
||||
await session.aclose()
|
||||
assert cancelled.is_set()
|
||||
assert not session.process.is_alive()
|
||||
|
||||
|
||||
async def test_network_example_uses_configuration_and_http_result(tmp_path):
|
||||
from middleware.config import NetworkPolicy, NetworkRule
|
||||
|
||||
source = Path(__file__).parents[1] / "plugins/network_review.lua"
|
||||
plugin = PluginConfig(
|
||||
id="review",
|
||||
file=source,
|
||||
config={"url": "https://review.example.com/check"},
|
||||
network=NetworkPolicy(allow=[NetworkRule(domain="review.example.com")]),
|
||||
)
|
||||
manager = PluginManager(Settings(upstream="http://agent", plugins=[plugin]))
|
||||
calls = []
|
||||
|
||||
class RecordingBroker:
|
||||
async def request(self, policy, request, maximum):
|
||||
calls.append(request)
|
||||
assert policy.allow[0].domain == "review.example.com"
|
||||
return {"status": 200, "headers": {}, "body": '{"allow":true}'}
|
||||
|
||||
manager.broker = RecordingBroker()
|
||||
session = await manager.open()
|
||||
try:
|
||||
original = {"body": '{"message":"test"}'}
|
||||
assert await session.apply("on_request", original) == [original]
|
||||
assert calls[0]["url"] == "https://review.example.com/check"
|
||||
assert calls[0]["body"] == original["body"]
|
||||
finally:
|
||||
await session.aclose()
|
||||
|
||||
|
||||
async def test_event_fanout_total_is_bounded(tmp_path):
|
||||
manager = manager_for(
|
||||
tmp_path,
|
||||
[
|
||||
"return {on_event=function(ctx,e) return {action='replace',events={e,e}} end}",
|
||||
"return {on_event=function(ctx,e) return {action='replace',events={e,e}} end}",
|
||||
],
|
||||
max_plugin_buffer_bytes=5000,
|
||||
)
|
||||
session = await manager.open()
|
||||
try:
|
||||
# Each plugin's individual result fits, but the second stage's accumulated fanout does not.
|
||||
with pytest.raises(LimitExceeded):
|
||||
await session.apply("on_event", {"data": "x" * 1300})
|
||||
finally:
|
||||
await session.aclose()
|
||||
@@ -0,0 +1,41 @@
|
||||
import pytest
|
||||
|
||||
from middleware.errors import LimitExceeded, PluginFailure
|
||||
from middleware.sse import decode_sse, encode_sse
|
||||
|
||||
|
||||
async def pieces(value, size=1):
|
||||
for i in range(0, len(value), size):
|
||||
yield value[i : i + size]
|
||||
|
||||
|
||||
async def test_split_unicode_crlf_multiline_comments():
|
||||
raw = "\ufeff: heartbeat\r\nevent: text_delta\r\nid: 1\r\ndata: 中文\r\ndata: second\r\nretry: 20\r\n\r\n".encode()
|
||||
events = [event async for event in decode_sse(pieces(raw), 1024)]
|
||||
assert events == [
|
||||
{
|
||||
"data": "中文\nsecond",
|
||||
"comments": [" heartbeat"],
|
||||
"event": "text_delta",
|
||||
"id": "1",
|
||||
"retry": 20,
|
||||
"has_data": True,
|
||||
}
|
||||
]
|
||||
assert [e async for e in decode_sse(pieces(encode_sse(events[0], 1024)), 1024)] == events
|
||||
|
||||
|
||||
async def test_heartbeat_and_incomplete_frame():
|
||||
events = [e async for e in decode_sse(pieces(b": ping\n\n"), 1024)]
|
||||
assert events[0]["has_data"] is False
|
||||
with pytest.raises(PluginFailure):
|
||||
_ = [e async for e in decode_sse(pieces(b"data: unfinished"), 1024)]
|
||||
|
||||
|
||||
async def test_frame_size_and_invalid_utf8():
|
||||
with pytest.raises(LimitExceeded):
|
||||
_ = [e async for e in decode_sse(pieces(b"data: " + b"x" * 100), 20)]
|
||||
with pytest.raises(UnicodeError):
|
||||
_ = [e async for e in decode_sse(pieces(b"data: \xff\n\n"), 100)]
|
||||
with pytest.raises(PluginFailure):
|
||||
encode_sse({"event": "evil\ndata: bad", "data": "x"}, 1024)
|
||||
Reference in new issue
Block a user