Files
Автомата Калашникова c76972c623 拦截逻辑收回 Lua 层,宿主代码恢复原样
还原 middleware/errors.py、runtime.py、proxy.py:不再依赖宿主渲染错误体,宿主按原样返回 403。网关代码零改动。

response_guard.lua:请求侧判定不通过时,把发往上游的请求体换成最小 stub(原文不出网关),在响应侧用 replace 输出 OpenAI 错误体 400 content_policy_violation;审核不可用时 503 safety_review_unavailable。拦截响应形态完全由插件自己控制。

tools/verify_plugins.py:断言同步回 stub 流程,57 项。
2026-11-27 17:56:03 +08:00

388 lines
16 KiB
Python

import asyncio
import json
import logging
import multiprocessing
import time
from datetime import UTC, datetime
from pathlib import Path
from uuid import uuid4
from .attachments import validate_multipart
from .config import Settings
from .errors import LimitExceeded, Overloaded, PluginFailure, PolicyBlocked
from .llm import LLMRegistry
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, plugins=None, attachments=None):
self.manager = manager
self.attachments = attachments
self.plugins = list(manager.plugins if plugins is None else plugins)
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"] == "files":
if self.attachments is None or plugin == ADAPTER_ID:
raise PluginFailure()
reply["value"] = self.attachments.read_text(result["value"])
elif result["kind"] == "log":
reply["value"] = None
payload = result["value"]
if not isinstance(payload, dict):
raise PluginFailure()
level = payload.get("level")
message = payload.get("message")
levels = {
"info": logging.INFO,
"warning": logging.WARNING,
"error": logging.ERROR,
}
if (
not isinstance(level, str)
or level not in levels
or not isinstance(message, str)
):
raise PluginFailure()
raw = message.encode("utf-8")
max_bytes = self.manager.settings.limits.max_plugin_buffer_bytes
truncated = len(raw) > max_bytes
message = raw[:max_bytes].decode("utf-8", errors="ignore")
logger.log(
levels[level],
"plugin_log request=%s plugin=%s truncated=%s message=%s",
self.context["request_id"],
plugin,
truncated,
json.dumps(message, ensure_ascii=False),
)
elif result["kind"] == "llm":
payload = result["value"]
if (
not isinstance(payload, dict)
or set(payload) != {"model", "request"}
or not isinstance(payload["model"], str)
or not isinstance(payload["request"], dict)
):
raise PluginFailure()
reply["value"] = await self.manager.llm.call(
plugin, payload["model"], payload["request"]
)
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):
plugin_ids = [] if adapter_only else [plugin.id for plugin in self.plugins]
plugin_ids.append(ADAPTER_ID)
for plugin_id in plugin_ids:
source = self.manager.sources[plugin_id]
config = self.manager.plugins_by_id.get(plugin_id)
await self.rpc(
{
"op": "load",
"plugin": plugin_id,
"source": source,
"llm": self.manager.llm.describe_for(plugin_id),
}
)
self.initialized.append(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.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_request" and self.attachments is not None:
for candidate in output:
# Validate every stage so later plugins never see forged file metadata.
validate_multipart(candidate, item)
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.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:
try:
await self.kill()
finally:
try:
if self.attachments is not None:
await self.attachments.aclose()
finally:
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,
2 * limits.max_attachment_text_bytes,
*(p.network.max_response_bytes for p in self.plugins),
)
+ 65536
)
self.broker = NetworkBroker()
self.llm = LLMRegistry(settings)
self.llm_started = False
self.sessions = set()
self.stopping = False
async def start(self):
if not self.llm_started:
await self.llm.start()
self.llm_started = True
async def open(
self, request_id=None, path=None, adapter_only=False, all_plugins=False, attachments=None
):
if self.stopping or len(self.sessions) >= self.settings.limits.max_sessions:
raise Overloaded()
if path is None and not adapter_only and not all_plugins:
raise ValueError("path is required when opening a plugin session")
await self.start()
plugins = self.plugins if all_plugins else self.plugins_for_path(path)
session = Session(self, request_id, plugins, attachments)
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(all_plugins=True)
await session.aclose()
def plugins_for_path(self, path):
return [
plugin for plugin in self.plugins if plugin.match is None or plugin.match.matches(path)
]
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)
await self.llm.stop()