feat(中间层): 实现 Lua 插件驱动的安全代理

新增固定上游的 HTTP/SSE 转发、Lua 插件生命周期和请求级进程隔离。
实现逐插件域名与内网白名单、DNS 地址固定、超时取消和受控错误收尾。
提供三个 Lua 示例插件、配置与开发文档、Docker 和 APISIX 部署示例。
通过 65 项测试及静态检查,验证真实 TCP 流式转发、取消、资源限制和 Windows 命令行启动。
This commit is contained in:
zhaiyn committed 2026-10-08 15:47:16 +08:00
commit d0bb045134
28 files changed
+2764

No files matched your search

+1
View File
@@ -0,0 +1 @@
"""Lua-first agent middleware."""
+31
View File
@@ -0,0 +1,31 @@
import argparse
import logging
import uvicorn
from .config import load_settings
from .proxy import create_app
def main():
parser = argparse.ArgumentParser(description="Lua-first agent safety middleware")
parser.add_argument("--config", default="config.yaml")
args = parser.parse_args()
logging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)s %(name)s %(message)s")
try:
settings = load_settings(args.config)
app = create_app(settings)
except Exception:
# Validation tracebacks can include configuration secrets; keep CLI output generic.
parser.exit(2, "配置加载失败,请检查配置字段及插件文件。\n")
uvicorn.run(
app,
host=settings.listen_host,
port=settings.listen_port,
# Uvicorn access logs contain raw query strings; use metadata-only audit logs instead.
access_log=False,
)
if __name__ == "__main__":
main()
+140
View File
@@ -0,0 +1,140 @@
import ipaddress
from pathlib import Path
from urllib.parse import urlsplit
import yaml
from pydantic import BaseModel, ConfigDict, Field, field_validator, model_validator
def normalize_domain(value: str) -> str:
value = value.rstrip(".").lower()
try:
value = value.encode("idna").decode("ascii")
except UnicodeError:
raise ValueError("invalid domain") from None
labels = value.split(".")
if len(value) > 253 or any(
not label
or len(label) > 63
or label.startswith("-")
or label.endswith("-")
or not all(c.isascii() and (c.isalnum() or c == "-") for c in label)
for label in labels
):
raise ValueError("invalid domain")
try:
ipaddress.ip_address(value)
except ValueError:
return value
raise ValueError("IP literals are not domains")
class Model(BaseModel):
model_config = ConfigDict(extra="forbid", frozen=True)
class NetworkRule(Model):
domain: str
scheme: str = "https"
ports: list[int] = Field(default_factory=lambda: [443], min_length=1)
cidrs: list[str] = Field(default_factory=list)
@field_validator("domain")
@classmethod
def domain_valid(cls, value: str) -> str:
wildcard = value.startswith("*.")
return ("*." if wildcard else "") + normalize_domain(value[2:] if wildcard else value)
@field_validator("scheme")
@classmethod
def scheme_valid(cls, value: str) -> str:
if value not in {"https", "http"}:
raise ValueError("only http/https are supported")
return value
@field_validator("ports")
@classmethod
def ports_valid(cls, value: list[int]) -> list[int]:
if any(not 1 <= port <= 65535 for port in value):
raise ValueError("invalid port")
return value
@field_validator("cidrs")
@classmethod
def cidrs_valid(cls, value: list[str]) -> list[str]:
for item in value:
ipaddress.ip_network(item, strict=True)
return value
def matches(self, hostname: str, scheme: str, port: int) -> bool:
domain = self.domain
domain_match = (
hostname.endswith(domain[1:]) if domain.startswith("*.") else hostname == domain
)
return domain_match and scheme == self.scheme and port in self.ports
class NetworkPolicy(Model):
allow: list[NetworkRule] = Field(default_factory=list)
timeout_seconds: float = Field(default=3, gt=0, le=60)
max_response_bytes: int = Field(default=1024 * 1024, gt=0)
class PluginConfig(Model):
id: str = Field(pattern=r"^[a-zA-Z0-9_-]{1,64}$")
file: Path
enabled: bool = True
config: dict = Field(default_factory=dict)
network: NetworkPolicy = Field(default_factory=NetworkPolicy)
class Limits(Model):
max_sessions: int = Field(default=4, gt=0)
hook_timeout_seconds: float = Field(default=5, gt=0)
lua_memory_bytes: int = Field(default=32 * 1024 * 1024, gt=0)
max_request_bytes: int = Field(default=2 * 1024 * 1024, gt=0)
max_response_bytes: int = Field(default=2 * 1024 * 1024, gt=0)
max_sse_frame_bytes: int = Field(default=256 * 1024, gt=0)
max_plugin_buffer_bytes: int = Field(default=1024 * 1024, gt=0)
max_host_calls_per_hook: int = Field(default=64, gt=0)
upstream_timeout_seconds: float = Field(default=120, gt=0)
class Settings(Model):
upstream: str
listen_host: str = "0.0.0.0"
listen_port: int = Field(default=8080, ge=1, le=65535)
limits: Limits = Field(default_factory=Limits)
plugins: list[PluginConfig] = Field(default_factory=list)
@field_validator("upstream")
@classmethod
def upstream_valid(cls, value: str) -> str:
url = urlsplit(value)
if url.scheme not in {"http", "https"} or not url.hostname or url.username is not None:
raise ValueError("invalid fixed upstream URL")
if url.query or url.fragment:
raise ValueError("upstream cannot contain query or fragment")
_ = url.port
return value.rstrip("/")
@model_validator(mode="after")
def plugins_valid(self):
ids = [p.id for p in self.plugins]
if len(ids) != len(set(ids)):
raise ValueError("duplicate plugin IDs")
return self
def load_settings(path: str | Path) -> Settings:
path = Path(path).resolve()
with path.open(encoding="utf-8") as file:
raw = yaml.safe_load(file)
settings = Settings.model_validate(raw)
plugins = []
for plugin in settings.plugins:
file = (path.parent / plugin.file).resolve()
if not file.is_file():
raise ValueError(f"plugin file not found: {plugin.id}")
plugins.append(plugin.model_copy(update={"file": file}))
return settings.model_copy(update={"plugins": plugins})
+22
View File
@@ -0,0 +1,22 @@
class MiddlewareError(Exception):
"""Never include plugin text, payloads or upstream exceptions in errors."""
class PluginFailure(MiddlewareError):
pass
class PolicyBlocked(MiddlewareError):
pass
class Overloaded(MiddlewareError):
pass
class LimitExceeded(MiddlewareError):
pass
class NetworkDenied(MiddlewareError):
pass
+40
View File
@@ -0,0 +1,40 @@
-- Agent-specific error serialization is Lua, not a rule in the Python transport.
local plugin = {}
local completed = nil
function plugin.on_event(ctx, event)
if event.event == 'run_completed' then
if completed then error('duplicate terminal event') end
completed = event
return {action='hold'}
end
return {action='pass'}
end
function plugin.on_end(ctx)
if completed then
local event = completed
completed = nil
return {action='replace', events={event}}
end
end
function plugin.on_error(ctx, failure)
local payload = nil
if failure.last_event and failure.last_event.data then
local ok, decoded = pcall(host.json.decode, failure.last_event.data)
if ok then payload = decoded end
end
local sequence = 1
local request_id = ctx.request_id
if type(payload) == 'table' then
if type(payload.sequence) == 'number' then sequence = payload.sequence + 1 end
if type(payload.request_id) == 'string' then request_id = payload.request_id end
end
return {
event = 'run_error', id = tostring(sequence), has_data = true,
data = host.json.encode({
request_id = request_id, sequence = sequence,
timestamp = failure.timestamp,
data = {error_type = failure.error_type},
}),
}
end
return plugin
+159
View File
@@ -0,0 +1,159 @@
"""Plugin egress: approve every address and connect through that same resolver."""
import asyncio
import ipaddress
import socket
import aiohttp
from aiohttp.abc import AbstractResolver
from yarl import URL
from .config import NetworkPolicy, NetworkRule, normalize_domain
from .errors import LimitExceeded, NetworkDenied
HOP_HEADERS = {
"connection",
"keep-alive",
"proxy-authenticate",
"proxy-authorization",
"te",
"trailer",
"transfer-encoding",
"upgrade",
"content-length",
"host",
}
def safe_headers(headers: dict) -> dict[str, str]:
if not isinstance(headers, dict):
raise ValueError("invalid headers")
connection = next((str(v) for k, v in headers.items() if str(k).lower() == "connection"), "")
excluded = HOP_HEADERS | {part.strip().lower() for part in connection.split(",")}
result = {}
for name, value in headers.items():
if not isinstance(name, str) or not isinstance(value, str):
raise ValueError("invalid headers")
if any(c in name + value for c in "\r\n\x00"):
raise ValueError("invalid headers")
if name.lower() not in excluded:
result[name] = value
return result
def address_allowed(value: str, rules: list[NetworkRule]) -> bool:
try:
ip = ipaddress.ip_address(value)
except ValueError:
return False
if isinstance(ip, ipaddress.IPv6Address):
if ip.ipv4_mapped:
ip = ip.ipv4_mapped
elif ip.sixtofour or ip.teredo:
return False
if (
ip.is_loopback
or ip.is_link_local
or ip.is_multicast
or ip.is_unspecified
or ip.is_reserved
or str(ip) in {"100.100.100.200", "168.63.129.16", "fd00:ec2::254"}
):
return False
return ip.is_global or any(
ip in ipaddress.ip_network(cidr) for rule in rules for cidr in rule.cidrs
)
class PolicyResolver(AbstractResolver):
def __init__(self, hostname: str, rules: list[NetworkRule]):
self.hostname = hostname
self.rules = rules
async def resolve(self, host: str, port: int = 0, family: int = socket.AF_UNSPEC):
if normalize_domain(host) != self.hostname:
raise NetworkDenied()
addresses = await asyncio.get_running_loop().getaddrinfo(
host,
port,
family=family,
type=socket.SOCK_STREAM,
)
# Reject the complete answer set if ANY address is unauthorized.
if not addresses or any(not address_allowed(item[4][0], self.rules) for item in addresses):
raise NetworkDenied()
return [
{
"hostname": host,
"host": item[4][0],
"port": port,
"family": item[0],
"proto": item[2],
"flags": socket.AI_NUMERICHOST,
}
for item in addresses
]
async def close(self):
pass
def approved_url(raw: str, policy: NetworkPolicy) -> tuple[URL, list[NetworkRule]]:
if not isinstance(raw, str) or any(ord(c) < 32 or ord(c) == 127 for c in raw):
raise NetworkDenied()
try:
url = URL(raw)
if url.scheme not in {"http", "https"} or url.user is not None or not url.host:
raise ValueError()
hostname = normalize_domain(url.host)
port = url.port
rules = [rule for rule in policy.allow if rule.matches(hostname, url.scheme, port)]
if not rules:
raise ValueError()
return url.with_host(hostname).with_fragment(None), rules
except (ValueError, UnicodeError):
raise NetworkDenied() from None
class NetworkBroker:
async def request(self, policy: NetworkPolicy, request: dict, max_request_bytes: int) -> dict:
if not isinstance(request, dict) or set(request) - {"url", "method", "headers", "body"}:
raise NetworkDenied()
url, rules = approved_url(request.get("url"), policy)
method = request.get("method", "GET")
if method not in {"GET", "POST", "PUT", "PATCH", "DELETE", "HEAD", "OPTIONS"}:
raise NetworkDenied()
body = request.get("body", "")
if not isinstance(body, str):
raise NetworkDenied()
encoded = body.encode("utf-8")
if len(encoded) > max_request_bytes:
raise LimitExceeded()
headers = safe_headers(request.get("headers", {}))
resolver = PolicyResolver(url.host, rules)
connector = aiohttp.TCPConnector(resolver=resolver, use_dns_cache=False)
# No default credentials/cookies/proxies. Default TLS verification stays enabled.
async with aiohttp.ClientSession(
connector=connector,
trust_env=False,
cookie_jar=aiohttp.DummyCookieJar(),
timeout=aiohttp.ClientTimeout(total=policy.timeout_seconds),
) as client:
async with client.request(
method,
url,
headers=headers,
data=encoded,
allow_redirects=False,
) as response:
chunks, size = [], 0
async for chunk in response.content.iter_chunked(16384):
size += len(chunk)
if size > policy.max_response_bytes:
raise LimitExceeded()
chunks.append(chunk)
return {
"status": response.status,
"headers": dict(response.headers),
"body": b"".join(chunks).decode("utf-8"),
}
+314
View File
@@ -0,0 +1,314 @@
import asyncio
import logging
import time
from contextlib import asynccontextmanager
from uuid import uuid4
import aiohttp
from fastapi import FastAPI, Request
from starlette.responses import JSONResponse, Response
from yarl import URL
from .config import Settings, load_settings
from .errors import LimitExceeded, MiddlewareError, Overloaded, PluginFailure, PolicyBlocked
from .network import safe_headers
from .runtime import PluginManager
from .sse import decode_sse, encode_sse
logger = logging.getLogger("middleware.audit")
async def bounded_body(chunks, maximum):
data = bytearray()
async for chunk in chunks:
if len(data) + len(chunk) > maximum:
raise LimitExceeded()
data.extend(chunk)
return bytes(data)
async def disconnected(receive):
while True:
message = await receive()
if message["type"] == "http.disconnect":
return
async def until_disconnect(awaitable, receive):
task = asyncio.create_task(awaitable)
watch = asyncio.create_task(disconnected(receive))
delivered = False
try:
done, _ = await asyncio.wait({task, watch}, return_when=asyncio.FIRST_COMPLETED)
if watch in done:
if task in done and not task.cancelled() and task.exception() is None:
result = task.result()
if isinstance(result, ProxyStream):
await result.close()
else:
task.cancel()
raise asyncio.CancelledError()
result = await task
delivered = True
return result
finally:
watch.cancel()
if not task.done():
task.cancel()
await asyncio.gather(task, watch, return_exceptions=True)
if not delivered and not task.cancelled() and task.exception() is None:
result = task.result()
if isinstance(result, ProxyStream):
await result.close()
def validate_request(value, original, limit):
if not isinstance(value, dict) or set(value) != set(original):
raise PluginFailure()
if value["method"] != original["method"] or value["path"] != original["path"]:
raise PluginFailure()
if not isinstance(value["body"], str):
raise PluginFailure()
if len(value["body"].encode("utf-8")) > limit:
raise LimitExceeded()
value["headers"] = safe_headers(value["headers"])
return value
def validate_response(value, streaming, limit):
if not isinstance(value, dict) or set(value) != {"status", "headers", "body", "streaming"}:
raise PluginFailure()
if type(value["status"]) is not int or not 200 <= value["status"] <= 599:
raise PluginFailure()
if value["streaming"] is not streaming:
raise PluginFailure()
if streaming:
if value["body"] is not None:
raise PluginFailure()
elif not isinstance(value["body"], str):
raise PluginFailure()
elif len(value["body"].encode("utf-8")) > limit:
raise LimitExceeded()
headers = safe_headers(value["headers"])
# aiohttp already decompresses upstream responses; never forward stale encoding headers.
headers = {k: v for k, v in headers.items() if k.lower() != "content-encoding"}
if streaming:
headers = {
k: v
for k, v in headers.items()
if k.lower() not in {"content-type", "cache-control", "x-accel-buffering"}
}
headers.update(
{
"content-type": "text/event-stream; charset=utf-8",
"cache-control": "no-cache",
"x-accel-buffering": "no",
}
)
value["headers"] = headers
return value
class ProxyStream(Response):
"""Own the complete ASGI lifetime, including disconnects before the first chunk."""
def __init__(self, upstream, session, value, manager):
super().__init__(status_code=value["status"], headers=value["headers"])
self.raw_headers = [(k, v) for k, v in self.raw_headers if k != b"content-length"]
self.upstream = upstream
self.session = session
self.manager = manager
async def close(self):
self.upstream.close()
await self.session.aclose()
async def chunks(self):
last_event = None
maximum = self.manager.settings.limits.max_sse_frame_bytes
try:
remaining = self.manager.settings.limits.upstream_timeout_seconds - (
time.monotonic() - self.session.started
)
async with asyncio.timeout(max(0.001, remaining)):
async for event in decode_sse(self.upstream.content.iter_chunked(16384), maximum):
for output in await self.session.apply("on_event", event):
encoded = encode_sse(output, maximum)
last_event = output
yield encoded
for output in await self.session.end():
encoded = encode_sse(output, maximum)
last_event = output
yield encoded
except asyncio.CancelledError:
raise
except Exception as exc:
error_type = "PolicyBlocked" if isinstance(exc, PolicyBlocked) else "MiddlewareFailure"
logger.info(
"stream_failure request=%s category=%s",
self.session.context["request_id"],
error_type,
)
# Cancel upstream and release a worker slot before starting the clean error adapter.
await self.close()
try:
event = await self.manager.error_event(
self.session.context["request_id"],
last_event,
error_type,
)
yield encode_sse(event, maximum)
except Exception:
return
async def __call__(self, scope, receive, send):
async def transmit():
await send(
{
"type": "http.response.start",
"status": self.status_code,
"headers": self.raw_headers,
}
)
async for chunk in self.chunks():
await send({"type": "http.response.body", "body": chunk, "more_body": True})
await send({"type": "http.response.body", "body": b"", "more_body": False})
try:
await until_disconnect(transmit(), receive)
except (asyncio.CancelledError, OSError):
pass
finally:
await self.close()
def create_app(settings: Settings | str = "config.yaml") -> FastAPI:
if not isinstance(settings, Settings):
settings = load_settings(settings)
@asynccontextmanager
async def lifespan(app):
app.state.ready = False
manager = PluginManager(settings)
app.state.manager = manager
try:
await manager.validate()
async with aiohttp.ClientSession(
trust_env=False,
cookie_jar=aiohttp.DummyCookieJar(),
timeout=aiohttp.ClientTimeout(total=settings.limits.upstream_timeout_seconds),
) as client:
app.state.client = client
app.state.ready = True
yield
finally:
app.state.ready = False
await manager.shutdown()
app = FastAPI(
title="Lua Agent Safety Middleware",
lifespan=lifespan,
docs_url=None,
redoc_url=None,
openapi_url=None,
)
@app.get("/healthz")
async def healthz():
return {"status": "ok"}
@app.get("/readyz")
async def readyz():
if not getattr(app.state, "ready", False):
return JSONResponse({"status": "not_ready"}, status_code=503)
return {"status": "ready"}
@app.post("/chat/stream")
async def chat(request: Request):
request_id = str(uuid4())
try:
body = await bounded_body(request.stream(), settings.limits.max_request_bytes)
text = body.decode("utf-8")
except LimitExceeded:
return JSONResponse({"error": "RequestTooLarge"}, status_code=413)
except UnicodeError:
return JSONResponse({"error": "InvalidEncoding"}, status_code=400)
async def prepare():
session = None
upstream = None
handed_off = False
try:
manager = app.state.manager
session = await manager.open(request_id)
original = {
"method": "POST",
"path": "/chat/stream",
"headers": safe_headers(dict(request.headers)),
"body": text,
}
result = (await session.apply("on_request", original))[0]
value = validate_request(result, original, settings.limits.max_request_bytes)
base_url = URL(settings.upstream + "/chat/stream")
query = request.scope["query_string"].decode("ascii")
if any(ord(c) <= 32 or ord(c) == 127 for c in query):
raise ValueError("invalid query encoding")
# with_query(str) would re-escape existing percent encodings (e.g. %2F → %252F).
url = URL(str(base_url) + ("?" + query if query else ""), encoded=True)
upstream = await app.state.client.post(
url,
data=value["body"].encode("utf-8"),
headers=value["headers"],
allow_redirects=False,
)
is_stream = (
upstream.headers.get("content-type", "").split(";", 1)[0].strip().lower()
== "text/event-stream"
)
value = {
"status": upstream.status,
"headers": dict(upstream.headers),
"streaming": is_stream,
"body": None
if is_stream
else (
await bounded_body(
upstream.content.iter_chunked(16384), settings.limits.max_response_bytes
)
).decode("utf-8"),
}
value = (await session.apply("on_response", value))[0]
value = validate_response(value, is_stream, settings.limits.max_response_bytes)
if is_stream:
response = ProxyStream(upstream, session, value, manager)
handed_off = True
return response
if await session.end():
raise PluginFailure()
return Response(
value["body"].encode("utf-8"), value["status"], headers=value["headers"]
)
except Overloaded:
return JSONResponse({"error": "Overloaded"}, status_code=503)
except PolicyBlocked:
return JSONResponse({"error": "PolicyBlocked"}, status_code=403)
except (MiddlewareError, aiohttp.ClientError, TimeoutError, UnicodeError, ValueError):
logger.info("request_failure request=%s category=MiddlewareFailure", request_id)
return JSONResponse({"error": "MiddlewareFailure"}, status_code=502)
finally:
if not handed_off:
if upstream is not None:
upstream.close()
if session is not None:
await session.aclose()
async def prepare_with_budget():
async with asyncio.timeout(settings.limits.upstream_timeout_seconds):
return await prepare()
try:
return await until_disconnect(prepare_with_budget(), request.receive)
except TimeoutError:
return JSONResponse({"error": "MiddlewareFailure"}, status_code=502)
return app
+306
View File
@@ -0,0 +1,306 @@
import asyncio
import json
import logging
import multiprocessing
import time
from datetime import UTC, datetime
from pathlib import Path
from uuid import uuid4
from .config import Settings
from .errors import LimitExceeded, Overloaded, PluginFailure, PolicyBlocked
from .network import NetworkBroker
from .worker import json_bytes, worker_main
logger = logging.getLogger("middleware.audit")
ADAPTER_ID = "__protocol_adapter__"
class Session:
def __init__(self, manager, request_id=None):
self.manager = manager
self.context = {"request_id": request_id or str(uuid4())}
self.started = time.monotonic()
self.closed = False
self.dead = False
self.initialized = []
context = multiprocessing.get_context("spawn")
self.connection, child = context.Pipe(duplex=True)
limits = manager.settings.limits.model_dump()
limits["ipc_bytes"] = manager.ipc_bytes
self.process = context.Process(target=worker_main, args=(child, limits), daemon=True)
try:
self.process.start()
except Exception:
self.connection.close()
raise PluginFailure() from None
finally:
child.close()
async def kill(self):
self.dead = True
self.connection.close()
if self.process.is_alive():
self.process.terminate()
await asyncio.to_thread(self.process.join, 1)
if self.process.is_alive():
self.process.kill()
await asyncio.to_thread(self.process.join, 1)
async def rpc(self, command: dict):
if self.dead:
raise PluginFailure()
plugin = command["plugin"]
started = time.perf_counter()
action = "failure"
completed = False
try:
async with asyncio.timeout(self.manager.settings.limits.hook_timeout_seconds):
message = json_bytes(command)
if len(message) > self.manager.ipc_bytes:
raise LimitExceeded()
await asyncio.to_thread(self.connection.send_bytes, message)
callbacks = 0
while True:
raw = await asyncio.to_thread(
self.connection.recv_bytes,
self.manager.ipc_bytes,
)
result = json.loads(raw)
if result.get("type") == "callback":
callbacks += 1
if callbacks > self.manager.settings.limits.max_host_calls_per_hook:
raise LimitExceeded()
if result.get("plugin") != plugin:
raise PluginFailure()
reply = {"type": "callback_result"}
try:
if result["kind"] == "http":
config = self.manager.plugins_by_id.get(plugin)
if config is None:
raise PluginFailure()
reply["value"] = await self.manager.broker.request(
config.network,
result["value"],
self.manager.settings.limits.max_request_bytes,
)
elif result["kind"] == "log":
reply["value"] = None
logger.info(
"plugin_log request=%s plugin=%s",
self.context["request_id"],
plugin,
)
else:
raise PluginFailure()
except Exception:
reply["error"] = "CapabilityFailed"
await asyncio.to_thread(self.connection.send_bytes, json_bytes(reply))
elif result.get("type") == "result":
completed = True
if result.get("error"):
raise PluginFailure()
value = result.get("value")
action = value.get("action", "pass") if isinstance(value, dict) else "pass"
# Only allow fixed log tokens, never caller-supplied action strings.
action = (
action if action in {"pass", "replace", "hold", "block"} else "invalid"
)
return value
else:
raise PluginFailure()
except asyncio.CancelledError:
await self.kill()
raise
except Exception:
if not completed:
await self.kill()
raise PluginFailure() from None
finally:
logger.info(
"plugin_hook request=%s plugin=%s hook=%s action=%s duration_ms=%d",
self.context["request_id"],
plugin,
command.get("hook", "load"),
action,
int((time.perf_counter() - started) * 1000),
)
async def initialize(self, adapter_only=False):
for plugin_id, source in self.manager.sources.items():
if adapter_only and plugin_id != ADAPTER_ID:
continue
await self.rpc({"op": "load", "plugin": plugin_id, "source": source})
self.initialized.append(plugin_id)
config = self.manager.plugins_by_id.get(plugin_id)
result = await self.invoke(plugin_id, "init", config.config if config else {})
if result is not None:
raise PluginFailure()
async def invoke(self, plugin_id, hook, value=None):
return await self.rpc(
{
"op": "invoke",
"plugin": plugin_id,
"hook": hook,
"context": {**self.context, "plugin_id": plugin_id},
"value": value,
}
)
async def apply(self, hook, value, start=0):
values = [value]
for plugin in self.manager.plugins[start:]:
output = []
for item in values:
result = await self.invoke(plugin.id, hook, item)
output.extend(self.decision(result, item, hook))
if hook == "on_event":
self.check_events_size(output)
values = output
if hook == "on_event":
output = []
for item in values:
result = await self.invoke(ADAPTER_ID, hook, item)
output.extend(self.decision(result, item, hook))
self.check_events_size(output)
values = output
return values
def check_events_size(self, events):
if len(json_bytes(events)) > self.manager.settings.limits.max_plugin_buffer_bytes:
raise LimitExceeded()
def decision(self, result, original, hook):
if result is None:
return [original] if hook != "on_end" else []
if not isinstance(result, dict) or set(result) - {"action", "value", "events", "reason"}:
raise PluginFailure()
action = result.get("action")
if action == "block":
raise PolicyBlocked()
if action == "pass":
if "value" in result or "events" in result:
raise PluginFailure()
return [original] if hook != "on_end" else []
if action == "hold" and hook == "on_event":
if "value" in result or "events" in result:
raise PluginFailure()
return []
if action == "replace":
if hook in {"on_event", "on_end"}:
if (
"events" not in result
or "value" in result
or not isinstance(result["events"], list)
):
raise PluginFailure()
output = result["events"]
if len(json_bytes(output)) > self.manager.settings.limits.max_plugin_buffer_bytes:
raise LimitExceeded()
return output
if "value" not in result or "events" in result or not isinstance(result["value"], dict):
raise PluginFailure()
return [result["value"]]
raise PluginFailure()
async def end(self):
output = []
for index, plugin in enumerate(self.manager.plugins):
result = await self.invoke(plugin.id, "on_end")
for event in self.decision(result, None, "on_end"):
output.extend(await self.apply("on_event", event, start=index + 1))
if len(json_bytes(output)) > self.manager.settings.limits.max_plugin_buffer_bytes:
raise LimitExceeded()
# The protocol adapter defers the success terminal event until every end hook passes.
result = await self.invoke(ADAPTER_ID, "on_end")
output.extend(self.decision(result, None, "on_end"))
self.check_events_size(output)
return output
async def aclose(self):
if self.closed:
return
self.closed = True
try:
if not self.dead:
for plugin_id in reversed(self.initialized):
try:
await self.invoke(plugin_id, "close")
except Exception:
continue
finally:
await self.kill()
self.manager.sessions.discard(self)
class PluginManager:
def __init__(self, settings: Settings):
self.settings = settings
self.plugins = [plugin for plugin in settings.plugins if plugin.enabled]
self.plugins_by_id = {plugin.id: plugin for plugin in self.plugins}
self.sources = {
plugin.id: plugin.file.read_text(encoding="utf-8") for plugin in self.plugins
}
if ADAPTER_ID in self.plugins_by_id:
raise ValueError("reserved plugin ID")
self.sources[ADAPTER_ID] = (
Path(__file__)
.with_name("lua")
.joinpath("agent_protocol.lua")
.read_text(encoding="utf-8")
)
limits = settings.limits
self.ipc_bytes = (
4
* max(
limits.max_request_bytes,
limits.max_response_bytes,
limits.max_plugin_buffer_bytes,
limits.max_sse_frame_bytes,
*(p.network.max_response_bytes for p in self.plugins),
)
+ 65536
)
self.broker = NetworkBroker()
self.sessions = set()
self.stopping = False
async def open(self, request_id=None, adapter_only=False):
if self.stopping or len(self.sessions) >= self.settings.limits.max_sessions:
raise Overloaded()
session = Session(self, request_id)
self.sessions.add(session)
try:
await session.initialize(adapter_only)
return session
except BaseException:
await session.aclose()
raise
async def validate(self):
session = await self.open()
await session.aclose()
async def error_event(self, request_id, last_event, error_type):
# Failed/timed-out business runtimes never render their own errors.
session = await self.open(request_id, adapter_only=True)
try:
result = await session.invoke(
ADAPTER_ID,
"on_error",
{
"last_event": last_event,
"error_type": error_type,
"timestamp": datetime.now(UTC).isoformat(),
},
)
if not isinstance(result, dict):
raise PluginFailure()
return result
finally:
await session.aclose()
async def shutdown(self):
self.stopping = True
await asyncio.gather(*(s.aclose() for s in list(self.sessions)), return_exceptions=True)
+104
View File
@@ -0,0 +1,104 @@
"""SSE framing only; application data stays opaque to the host."""
from collections.abc import AsyncIterable, AsyncIterator
from .errors import LimitExceeded, PluginFailure
def parse_frame(lines: list[str]) -> dict:
event = {"data": "", "comments": []}
data = []
for line in lines:
if line.startswith(":"):
event["comments"].append(line[1:])
continue
name, sep, value = line.partition(":")
if sep and value.startswith(" "):
value = value[1:]
if name == "data":
data.append(value)
elif name in {"event", "id"}:
if name != "id" or "\x00" not in value:
event[name] = value
elif name == "retry" and value.isascii() and value.isdigit():
event["retry"] = int(value)
event["data"] = "\n".join(data)
event["has_data"] = bool(data)
return event
async def decode_sse(chunks: AsyncIterable[bytes], max_frame_bytes: int) -> AsyncIterator[dict]:
# Byte-level line framing preserves split UTF-8 without unbounded chunk accumulation.
line = bytearray()
lines = []
frame_size = 0
after_cr = False
first_line = True
async for chunk in chunks:
for byte in chunk:
frame_size += 1
if frame_size > max_frame_bytes:
raise LimitExceeded()
if after_cr:
after_cr = False
if byte == 10:
continue
if byte not in (10, 13):
line.append(byte)
continue
text = bytes(line).decode("utf-8", errors="strict")
line.clear()
if first_line:
text = text.removeprefix("\ufeff")
first_line = False
after_cr = byte == 13
if text:
lines.append(text)
else:
if lines:
yield parse_frame(lines)
lines = []
frame_size = 0
# SSE dispatches only complete frames; a partial final frame is not trusted/released.
if line or lines:
raise PluginFailure()
def encode_sse(event: dict, max_frame_bytes: int) -> bytes:
if not isinstance(event, dict) or set(event) - {
"event",
"id",
"data",
"comments",
"retry",
"has_data",
}:
raise PluginFailure()
lines = []
comments = event.get("comments", [])
if not isinstance(comments, list):
raise PluginFailure()
for comment in comments:
if not isinstance(comment, str) or "\r" in comment or "\n" in comment:
raise PluginFailure()
lines.append(":" + comment)
for field in ("event", "id"):
if field in event:
value = event[field]
if not isinstance(value, str) or any(c in value for c in "\r\n\x00"):
raise PluginFailure()
lines.append(f"{field}: {value}")
if "retry" in event:
retry = event["retry"]
if type(retry) is not int or retry < 0:
raise PluginFailure()
lines.append(f"retry: {retry}")
if event.get("has_data", "data" in event):
data = event.get("data", "")
if not isinstance(data, str) or "\r" in data:
raise PluginFailure()
lines.extend("data: " + part for part in data.split("\n"))
encoded = ("\n".join(lines) + "\n\n").encode("utf-8")
if len(encoded) > max_frame_bytes:
raise LimitExceeded()
return encoded
+199
View File
@@ -0,0 +1,199 @@
"""Child process: pure Lua capabilities, JSON-only IPC (never unpickle child data)."""
import json
import math
from lupa.lua54 import LuaRuntime, lua_type
HOOKS = {"init", "on_request", "on_response", "on_event", "on_end", "close", "on_error"}
def deny_attributes(obj, name, setting):
raise AttributeError("Python attributes are unavailable")
def json_bytes(value) -> bytes:
return json.dumps(value, ensure_ascii=False, allow_nan=False, separators=(",", ":")).encode()
class LuaPlugin:
def __init__(self, source: str, limits: dict, callback):
self.limits = limits
self.callback = callback
self.lua = LuaRuntime(
register_eval=False,
register_builtins=False,
attribute_filter=deny_attributes,
unpack_returned_tuples=True,
max_memory=limits["lua_memory_bytes"],
)
self.mark, self.kind, self.identity, self.null = self.lua.execute("""
local tags = setmetatable({}, {__mode='k'})
local ids = setmetatable({}, {__mode='k'})
local next_id = 0
local null = {}
tags[null] = 'null'
return function(t, kind) tags[t] = kind; return t end,
function(t) return tags[t] end,
function(t)
if not ids[t] then next_id=next_id+1; ids[t]=next_id end
return ids[t]
end, null
""")
self.gc = self.lua.execute("local gc=collectgarbage; return function() gc('collect') end")
# Capture GC privately, then remove all uncontrolled capabilities.
self.lua.execute("""
os=nil; io=nil; debug=nil; package=nil; require=nil
dofile=nil; loadfile=nil; load=nil; python=nil
print=nil; warn=nil; collectgarbage=nil
""")
host = self.lua.table()
json_api = self.lua.table()
json_api["decode"] = lambda text: self.to_lua(json.loads(text))
json_api["encode"] = lambda value: json_bytes(self.to_python(value)).decode()
json_api["array"] = lambda value=None: self.mark(
self.lua.table() if value is None else value,
"array",
)
json_api["null"] = self.null
host["json"] = json_api
http = self.lua.table()
http["request"] = lambda request: self.to_lua(
self.callback("http", self.to_python(request)),
)
host["http"] = http
log = self.lua.table()
for level in ("info", "warning", "error"):
# Deliberately discard caller-provided text; logs contain metadata only.
log[level] = lambda *_, level=level: self.callback("log", {"level": level})
host["log"] = log
self.lua.globals()["host"] = host
self.plugin = self.lua.execute(source)
if lua_type(self.plugin) != "table":
raise ValueError("plugin must return a table")
for hook in HOOKS:
value = self.plugin[hook]
if value is not None and lua_type(value) != "function":
raise ValueError("invalid hook")
self.gc()
self.baseline = self.lua.get_memory_used()
def to_lua(self, value, depth=0):
if depth > 64:
raise ValueError("nesting limit")
if value is None:
return self.null
if isinstance(value, dict):
table = self.mark(self.lua.table(), "object")
for key, item in value.items():
table[key] = self.to_lua(item, depth + 1)
return table
if isinstance(value, list):
table = self.mark(self.lua.table(), "array")
for i, item in enumerate(value, 1):
table[i] = self.to_lua(item, depth + 1)
return table
if type(value) in {str, int, float, bool}:
return value
raise ValueError("non-data value")
def to_python(self, value):
seen = set()
nodes = 0
def convert(item, depth=0):
nonlocal nodes
nodes += 1
if depth > 64 or nodes > 100_000:
raise ValueError("conversion limit")
if lua_type(item) == "table":
identity = self.identity(item)
if identity in seen:
raise ValueError("cyclic table")
kind = self.kind(item)
if kind == "null":
return None
seen.add(identity)
keys = list(item.keys())
is_array = kind == "array" or (
kind is None and keys and all(type(k) is int for k in keys)
)
if is_array:
if set(keys) != set(range(1, len(keys) + 1)):
raise ValueError("sparse array")
result = [convert(item[k], depth + 1) for k in range(1, len(keys) + 1)]
else:
if any(type(k) is not str for k in keys):
raise ValueError("object keys must be strings")
result = {k: convert(item[k], depth + 1) for k in keys}
seen.remove(identity)
return result
if item is None or type(item) in {str, int, bool}:
return item
if type(item) is float and math.isfinite(item):
return item
raise ValueError("non-data value")
result = convert(value)
if len(json_bytes(result)) > self.limits["ipc_bytes"]:
raise ValueError("conversion size limit")
return result
def invoke(self, hook: str, context: dict, value):
func = self.plugin[hook]
if func is None:
return None
# Conversion and GC are completed before returning so only persistent Lua state is counted.
result = self.to_python(func(self.to_lua(context), self.to_lua(value)))
self.gc()
if self.lua.get_memory_used() - self.baseline > self.limits["max_plugin_buffer_bytes"]:
raise ValueError("retained state limit")
return result
def worker_main(connection, limits: dict):
plugins = {}
current = None
def send(value):
data = json_bytes(value)
if len(data) > limits["ipc_bytes"]:
raise ValueError("IPC limit")
connection.send_bytes(data)
def receive():
return json.loads(connection.recv_bytes(limits["ipc_bytes"]))
def callback(kind, value):
send({"type": "callback", "plugin": current, "kind": kind, "value": value})
response = receive()
if response.get("type") != "callback_result" or response.get("error"):
raise RuntimeError("host capability failed")
return response.get("value")
try:
while True:
command = receive()
current = command.get("plugin")
try:
if command["op"] == "load":
plugins[current] = LuaPlugin(command["source"], limits, callback)
result = None
elif command["op"] == "invoke":
result = plugins[current].invoke(
command["hook"],
command["context"],
command.get("value"),
)
elif command["op"] == "stop":
return
else:
raise ValueError("invalid operation")
send({"type": "result", "value": result})
except Exception:
# Never transmit exception messages/tracebacks or Lua source fragments.
send({"type": "result", "error": "PluginFailure"})
except (EOFError, OSError, Exception):
pass
finally:
connection.close()