Files
agent-safe-middleware/middleware/worker.py
T
zhaiyn d0bb045134 feat(中间层): 实现 Lua 插件驱动的安全代理
新增固定上游的 HTTP/SSE 转发、Lua 插件生命周期和请求级进程隔离。
实现逐插件域名与内网白名单、DNS 地址固定、超时取消和受控错误收尾。
提供三个 Lua 示例插件、配置与开发文档、Docker 和 APISIX 部署示例。
通过 65 项测试及静态检查,验证真实 TCP 流式转发、取消、资源限制和 Windows 命令行启动。
2026-10-08 15:47:16 +08:00

200 lines
7.7 KiB
Python

"""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()