469 lines
16 KiB
Python
469 lines
16 KiB
Python
import asyncio
|
|
import json
|
|
|
|
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(path="/chat/stream")
|
|
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)
|
|
with pytest.raises(ValueError, match="path is required"):
|
|
await manager.open()
|
|
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(path="/chat/stream")
|
|
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(path="/chat/stream")
|
|
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(path="/chat/stream")
|
|
with pytest.raises(Overloaded):
|
|
await manager.open(path="/chat/stream")
|
|
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(path="/chat/stream")
|
|
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(path="/chat/stream")
|
|
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(path="/chat/stream")
|
|
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(path="/chat/stream")
|
|
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('closed') end}",
|
|
"return {close=function() error('private') end}",
|
|
],
|
|
)
|
|
session = await manager.open(path="/chat/stream")
|
|
await session.aclose()
|
|
assert "plugin_log" in caplog.text
|
|
assert 'message="closed"' in caplog.text
|
|
assert "private" not in caplog.text
|
|
|
|
|
|
async def test_plugin_log_preserves_arguments_levels_and_single_line(tmp_path, caplog):
|
|
caplog.set_level("INFO", logger="middleware.audit")
|
|
manager = manager_for(
|
|
tmp_path,
|
|
[
|
|
r"""
|
|
return {on_request=function()
|
|
host.log.info("中文\n下一行", 42, true, {ok=true})
|
|
host.log.warning("warning message")
|
|
host.log.error("error message")
|
|
end}
|
|
"""
|
|
],
|
|
)
|
|
session = await manager.open(path="/chat/stream")
|
|
try:
|
|
await session.apply("on_request", {})
|
|
finally:
|
|
await session.aclose()
|
|
records = [r for r in caplog.records if r.getMessage().startswith("plugin_log ")]
|
|
assert [r.levelname for r in records] == ["INFO", "WARNING", "ERROR"]
|
|
assert json.loads(records[0].getMessage().split(" message=", 1)[1]) == (
|
|
'中文\n下一行 42 true {"ok":true}'
|
|
)
|
|
assert all("\n" not in r.getMessage() for r in records)
|
|
|
|
|
|
async def test_plugin_log_truncation_keeps_valid_unicode(tmp_path, caplog):
|
|
caplog.set_level("INFO", logger="middleware.audit")
|
|
manager = manager_for(
|
|
tmp_path,
|
|
['return {on_request=function() host.log.info(string.rep("中", 4000)) end}'],
|
|
max_plugin_buffer_bytes=10001,
|
|
)
|
|
session = await manager.open(path="/chat/stream")
|
|
try:
|
|
await session.apply("on_request", {})
|
|
finally:
|
|
await session.aclose()
|
|
record = next(
|
|
r.getMessage() for r in caplog.records if r.getMessage().startswith("plugin_log ")
|
|
)
|
|
assert "truncated=True" in record
|
|
message = json.loads(record.split(" message=", 1)[1])
|
|
assert message == "中" * 3333
|
|
|
|
|
|
async def test_buffered_json_events_are_rewritten_on_end(tmp_path):
|
|
source = """
|
|
local parts={}
|
|
return {
|
|
on_event=function(ctx,event)
|
|
parts[#parts+1]=host.json.decode(event.data).data.content
|
|
return {action='hold'}
|
|
end,
|
|
on_end=function(ctx)
|
|
return {action='replace',events={{
|
|
data=host.json.encode({data={content=table.concat(parts),count=#parts}})
|
|
}}}
|
|
end,
|
|
}
|
|
"""
|
|
manager = manager_for(tmp_path, [source])
|
|
session = await manager.open(path="/chat/stream")
|
|
try:
|
|
for content in ["第一段", "中间段", "结束"]:
|
|
assert (
|
|
await session.apply(
|
|
"on_event",
|
|
{
|
|
"event": "text_delta",
|
|
"data": json.dumps({"data": {"content": content}}),
|
|
},
|
|
)
|
|
== []
|
|
)
|
|
results = await session.end()
|
|
assert len(results) == 1
|
|
assert json.loads(results[0]["data"]) == {
|
|
"data": {"content": "第一段中间段结束", "count": 3}
|
|
}
|
|
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(path="/chat/stream")
|
|
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(path="/chat/stream")
|
|
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(path="/chat/stream")
|
|
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()
|
|
|
|
|
|
@pytest.mark.parametrize(
|
|
("status", "body", "allowed"),
|
|
[
|
|
(200, '{"allow":true}', True),
|
|
(200, '{"allow":false}', False),
|
|
(503, '{"allow":true}', False),
|
|
],
|
|
)
|
|
async def test_http_callback_uses_plugin_configuration_and_result(tmp_path, status, body, allowed):
|
|
from middleware.config import NetworkPolicy, NetworkRule
|
|
|
|
source = """
|
|
local settings
|
|
return {
|
|
init=function(ctx,config) settings=config end,
|
|
on_request=function(ctx,request)
|
|
local response=host.http.request({
|
|
url=settings.url,
|
|
method='POST',
|
|
headers={['content-type']='application/json'},
|
|
body=request.body,
|
|
})
|
|
if response.status ~= 200 or host.json.decode(response.body).allow ~= true then
|
|
return {action='block'}
|
|
end
|
|
return {action='pass'}
|
|
end,
|
|
}
|
|
"""
|
|
file = tmp_path / "http_callback.lua"
|
|
file.write_text(source, encoding="utf-8")
|
|
plugin = PluginConfig(
|
|
id="review",
|
|
file=file,
|
|
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": status, "headers": {}, "body": body}
|
|
|
|
manager.broker = RecordingBroker()
|
|
session = await manager.open(path="/chat/stream")
|
|
try:
|
|
original = {"body": '{"message":"test"}'}
|
|
if allowed:
|
|
assert await session.apply("on_request", original) == [original]
|
|
else:
|
|
with pytest.raises(PolicyBlocked):
|
|
await session.apply("on_request", original)
|
|
assert calls == [
|
|
{
|
|
"url": "https://review.example.com/check",
|
|
"method": "POST",
|
|
"headers": {"content-type": "application/json"},
|
|
"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(path="/chat/stream")
|
|
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()
|