Files
agent-safe-middleware/tests/test_runtime.py
T
starrrLight d1f5f69454 fix(运行时): 将插件路径匹配移到宿主
新增宿主侧精确路径匹配和插件级 match.paths 配置。\n按请求路径固定插件会话链,移除 Lua 插件内的路径判断与 bypass 状态,并迁移现有插件配置和测试。
2026-10-15 15:49:05 +08:00

369 lines
12 KiB
Python

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_host_selects_plugins_once_by_exact_path(tmp_path):
first = tmp_path / "first.lua"
second = tmp_path / "second.lua"
first.write_text(
"return {on_request=function(ctx,r) r.body=r.body..' first'; return {action='replace',value=r} end}",
encoding="utf-8",
)
second.write_text(
"return {on_request=function(ctx,r) r.body=r.body..' second'; return {action='replace',value=r} end}",
encoding="utf-8",
)
settings = Settings(
upstream="http://agent:8000",
plugins=[
PluginConfig(id="first", file=first, match={"paths": ["/first"]}),
PluginConfig(id="second", file=second, match={"paths": ["/second"]}),
],
)
manager = PluginManager(settings)
first_session = await manager.open(path="/first")
try:
assert await first_session.apply("on_request", {"body": "x"}) == [{"body": "x first"}]
finally:
await first_session.aclose()
second_session = await manager.open(path="/second?ignored=true")
try:
assert await second_session.apply("on_request", {"body": "x"}) == [{"body": "x"}]
finally:
await second_session.aclose()
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()