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,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)
|
||||
Reference in new issue
Block a user