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,10 @@
|
||||
.git
|
||||
.venv
|
||||
__pycache__
|
||||
.pytest_cache
|
||||
.ruff_cache
|
||||
*.egg-info
|
||||
config.local.yaml
|
||||
.env
|
||||
tests
|
||||
tmp
|
||||
@@ -0,0 +1 @@
|
||||
* text=auto eol=lf
|
||||
+12
@@ -0,0 +1,12 @@
|
||||
.venv/
|
||||
__pycache__/
|
||||
*.py[cod]
|
||||
.pytest_cache/
|
||||
.ruff_cache/
|
||||
*.egg-info/
|
||||
build/
|
||||
dist/
|
||||
config.local.yaml
|
||||
.env
|
||||
tmp/
|
||||
*.log
|
||||
+10
@@ -0,0 +1,10 @@
|
||||
FROM python:3.14-slim
|
||||
WORKDIR /service
|
||||
COPY pyproject.toml ./
|
||||
COPY middleware ./middleware
|
||||
RUN pip install --no-cache-dir .
|
||||
COPY config.yaml ./
|
||||
COPY plugins ./plugins
|
||||
USER 65532:65532
|
||||
EXPOSE 8080
|
||||
CMD ["agent-safe-middleware", "--config", "/service/config.yaml"]
|
||||
@@ -0,0 +1,96 @@
|
||||
# Lua 插件驱动的 Agent 安全中间层
|
||||
|
||||
运行链路:`APISIX → 本服务 → Python Agent`。Python 负责 HTTP/SSE、插件生命周期和网络授权,Lua 负责输入输出内容的业务处理。一个 Lua 文件就是一个插件,配置文件控制启用和执行顺序。
|
||||
|
||||
当前代理 `POST /chat/stream`,兼容现有 Agent 的 `message`、`conversation_id` 请求及自定义 SSE 事件。Python 核心不解析这些业务字段。这里检查的是 Agent 的 HTTP 边界,不能在执行前授权 Agent 内部的工具调用。
|
||||
|
||||
## 本地运行
|
||||
|
||||
要求 Python 3.12+,Windows/Linux 均采用 spawn 子进程。建议使用 Python 3.14。
|
||||
|
||||
```powershell
|
||||
python -m venv .venv
|
||||
.venv\Scripts\python.exe -m pip install -e ".[dev]"
|
||||
Copy-Item config.yaml config.local.yaml
|
||||
# 修改 config.local.yaml 中的 upstream、插件开关和网络授权
|
||||
.venv\Scripts\agent-safe-middleware.exe --config config.local.yaml
|
||||
```
|
||||
|
||||
Linux 安装后使用 `agent-safe-middleware --config config.local.yaml`。默认 Agent 地址为 `http://127.0.0.1:8000`,中间层监听 `8080`。三个示例插件默认关闭,因此初始配置转发原始请求和响应。
|
||||
|
||||
检查 `GET /healthz` 和 `GET /readyz`。就绪表示配置与插件初始化通过,不表示真实模型、MCP 或上游 Agent 已连通。
|
||||
|
||||
```powershell
|
||||
Invoke-RestMethod http://127.0.0.1:8080/readyz
|
||||
curl.exe -N http://127.0.0.1:8080/chat/stream -H "Content-Type: application/json" -d '{"message":"你好"}'
|
||||
```
|
||||
|
||||
## 配置与部署
|
||||
|
||||
配置结构及默认限制见 `config.yaml`。插件路径相对于配置文件解析,列表顺序就是执行顺序。启用、停用、代码和配置变更均重启生效。所有插件文件(含关闭的条目)必须存在;只有启用的插件会校验 Lua 代码和初始化。加载失败时服务不就绪。
|
||||
|
||||
网络授权位于每个插件的 `network.allow`。公网 HTTPS 默认端口 443;内网域名需额外配置 CIDR,HTTP 和其他端口须明确配置。空列表表示插件不能发起网络请求。
|
||||
|
||||
```yaml
|
||||
plugins:
|
||||
- id: network-review
|
||||
file: plugins/network_review.lua
|
||||
enabled: true
|
||||
config:
|
||||
url: http://review.internal.example.com:8080/check
|
||||
network:
|
||||
allow:
|
||||
- domain: review.internal.example.com
|
||||
scheme: http
|
||||
ports: [8080]
|
||||
cidrs: [10.20.0.0/16]
|
||||
- domain: '*.review.example.com'
|
||||
```
|
||||
|
||||
`*.example.com` 匹配一层或多层子域名,不匹配根域名或 `badexample.com`。公网地址可访问;非公网地址只有命中指定 CIDR 才可访问。回环、链路本地、组播、保留地址以及已列出的云元数据地址始终拒绝。DNS 返回混合的允许/禁止地址时整体拒绝,连接使用已校验结果;HTTPS 保留原域名证书校验。
|
||||
|
||||
插件不能改变 Agent 上游地址。上游是管理员配置的固定地址,与插件域名白名单分开:因此可以把本机 Agent 配为上游,但 Lua 网络接口仍不能访问本机。
|
||||
|
||||
```sh
|
||||
docker build -t agent-safe-middleware .
|
||||
docker run --rm -p 8080:8080 --add-host host.docker.internal:host-gateway \
|
||||
-v "$PWD/config.local.yaml:/service/config.yaml:ro" agent-safe-middleware
|
||||
```
|
||||
|
||||
容器内的 `127.0.0.1` 指向容器自身,宿主机 Agent 应配置为 `http://host.docker.internal:8000`;同网络的容器使用服务名。自定义插件也需以只读方式挂载到配置引用的位置。镜像以非 root 用户运行。
|
||||
|
||||
`deploy/apisix-route.json` 是 APISIX Admin API 路由对象示例,需要替换上游节点为中间层实际地址,再通过已有部署流程导入。APISIX 的 read timeout 应大于中间层的任务超时,部署时关闭会延迟 SSE 的响应缓冲。
|
||||
|
||||
## 插件与安全行为
|
||||
|
||||
接口、返回值、JSON 桥接和暂存示例见 [插件开发文档](docs/plugins.md)。
|
||||
|
||||
- `request_rewrite.lua` 修改请求 message,演示业务字段处理留在 Lua。
|
||||
- `stream_redact.lua` 暂存全部 SSE,在结束时合并文本检测跨事件手机号/身份证号,脱敏后按原事件结构释放。这个示例主动选择全缓冲,会增加首字延迟,规则仅用于演示。
|
||||
- `network_review.lua` 通过受控 HTTP 请求审核原始请求,要求审核接口返回 `200` 和 `{"allow":true}` 才放行。
|
||||
|
||||
默认引擎逐个完整 SSE 帧执行插件,不按网络字节块审核。插件决定何时放行或暂存。已经发出的内容无法撤回;跨段检测必须在放行前保留上下文。
|
||||
|
||||
单请求租用一个子进程,进程内每个插件使用独立 Lua 5.4 运行时,请求结束销毁整个进程。默认最多 4 个活跃会话,满载立即返回 503。每次钩子含宿主网络调用最多 5 秒;超时或取消终止进程,下一请求创建新进程。`upstream_timeout_seconds` 同时限制转发与插件处理的总时长(默认 120 秒),异常清理和错误返回在此后完成。
|
||||
|
||||
Lua 标准库的文件、进程、模块加载、动态代码加载及 Python 桥接不可用,Python 回调属性不可访问。这是面向管理员维护插件的能力限制与进程隔离,不是第三方不可信代码的操作系统沙箱。
|
||||
|
||||
`lua_memory_bytes` 限制每个 Lua 运行时的分配量;`max_plugin_buffer_bytes` 同时限制钩子后 GC 剩余的 Lua 状态增量和单次释放事件集合的序列化大小。Lua 表与字符串有额外开销,因此实际可暂存正文会小于配置字节数。这些不是整个 Python 子进程的 OS 级内存限制。HTTP、IPC、帧和正文也分别有限制。
|
||||
|
||||
策略阻断在响应头发送前返回 403;插件异常、非法结果、超时或上游错误返回 502。SSE 已开始时返回兼容的 `run_error` 并关闭流;成功完成事件由内置 Lua 适配器暂存至结束检查通过。错误适配器失败则直接关闭。错误和拒绝原因不回显插件文本。
|
||||
|
||||
关闭钩子按反向初始化顺序执行,普通异常不会跳过其他插件。若进程死循环、超时或已崩溃,只能强制终止,无法保证其中的 Lua 清理钩子完成。客户端断开会关闭上游及取消插件网络请求,但无法撤销 Agent 已产生的工具副作用。
|
||||
|
||||
日志只记录随机请求 ID、插件 ID、钩子、耗时、决定和固定错误类别。Lua 日志接口丢弃文本参数;服务关闭访问日志以避免原始查询参数进入日志。APISIX 和 Agent 的日志策略需在各自服务中配置。
|
||||
|
||||
## 验证
|
||||
|
||||
```powershell
|
||||
.venv\Scripts\python.exe -m pytest -q
|
||||
.venv\Scripts\python.exe -m ruff check .
|
||||
.venv\Scripts\python.exe -m ruff format --check .
|
||||
.venv\Scripts\python.exe -m pip check
|
||||
git diff --check
|
||||
```
|
||||
|
||||
测试使用模拟 Agent,并包含真实 Uvicorn/TCP 流式接收、并发满载和客户端断开检查。网络授权测试验证 DNS 地址、白名单、TLS 默认设置及禁止代理/自动重定向;不会连接真实审核供应商、模型或 MCP。实际部署仍需使用甲方接口执行连通性验收。
|
||||
+39
@@ -0,0 +1,39 @@
|
||||
# Relative plugin paths resolve against this configuration file.
|
||||
upstream: http://127.0.0.1:8000
|
||||
listen_host: 0.0.0.0
|
||||
listen_port: 8080
|
||||
limits:
|
||||
max_sessions: 4
|
||||
hook_timeout_seconds: 5
|
||||
lua_memory_bytes: 33554432
|
||||
max_request_bytes: 2097152
|
||||
max_response_bytes: 2097152
|
||||
max_sse_frame_bytes: 262144
|
||||
max_plugin_buffer_bytes: 1048576
|
||||
max_host_calls_per_hook: 64
|
||||
upstream_timeout_seconds: 120
|
||||
plugins:
|
||||
- id: request-rewrite
|
||||
file: plugins/request_rewrite.lua
|
||||
enabled: false
|
||||
config:
|
||||
prefix: ""
|
||||
- id: stream-redact
|
||||
file: plugins/stream_redact.lua
|
||||
enabled: false
|
||||
- id: network-review
|
||||
file: plugins/network_review.lua
|
||||
enabled: false
|
||||
config:
|
||||
url: https://review.example.com/check
|
||||
network:
|
||||
timeout_seconds: 3
|
||||
max_response_bytes: 1048576
|
||||
allow:
|
||||
- domain: review.example.com
|
||||
- domain: '*.review.example.com'
|
||||
# Explicit intranet example: enable only after replacing with actual deployment values.
|
||||
# - domain: review.internal.example.com
|
||||
# scheme: http
|
||||
# ports: [8080]
|
||||
# cidrs: [10.20.0.0/16]
|
||||
@@ -0,0 +1,11 @@
|
||||
{
|
||||
"uri": "/chat/stream",
|
||||
"methods": ["POST"],
|
||||
"name": "agent-safety-middleware",
|
||||
"upstream": {
|
||||
"type": "roundrobin",
|
||||
"scheme": "http",
|
||||
"nodes": {"agent-safe-middleware:8080": 1},
|
||||
"timeout": {"connect": 5, "send": 130, "read": 130}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,82 @@
|
||||
# Lua 插件开发接口 v1
|
||||
|
||||
插件文件返回一个 Lua table,已知钩子若存在必须是函数。未知元数据字段可以保留。`init` 不返回决定,缺省钩子或返回 `nil` 表示继续;`on_end` 返回 `nil` 表示没有待释放事件。
|
||||
|
||||
```lua
|
||||
local plugin = {}
|
||||
local settings = {}
|
||||
function plugin.init(ctx, config) settings = config end
|
||||
function plugin.on_request(ctx, request)
|
||||
local data = host.json.decode(request.body)
|
||||
if data.message == 'blocked' then return {action='block'} end
|
||||
return {action='pass'}
|
||||
end
|
||||
return plugin
|
||||
```
|
||||
|
||||
`ctx` 包含中间层生成的 `request_id` 和当前 `plugin_id`。它不是用户身份或授权证据。每次钩子获得数据副本,需通过返回值传递修改。插件用模块局部变量保存本请求状态;不同插件、不同请求均不共享全局变量。
|
||||
|
||||
## 钩子数据
|
||||
|
||||
| 钩子 | 第二参数 | 可以返回的动作 |
|
||||
|---|---|---|
|
||||
| `init(ctx, config)` | 此插件的 YAML `config` 对象 | 必须返回 nil |
|
||||
| `on_request(ctx, request)` | `{method, path, headers, body}` | pass、replace、block |
|
||||
| `on_response(ctx, response)` | `{status, headers, body, streaming}` | pass、replace、block |
|
||||
| `on_event(ctx, event)` | `{event?, id?, data, has_data, comments, retry?}` | pass、replace、hold、block |
|
||||
| `on_end(ctx)` | 无业务参数 | pass、replace、block |
|
||||
| `close(ctx)` | 无业务参数 | 返回值忽略 |
|
||||
|
||||
请求/非流式正文是 UTF-8 字符串;`method`、`path` 不可改变。请求头和正文允许修改。SSE 响应的 body 是 JSON null,不能替换或切换 streaming 模式,应使用 `on_event`。状态码必须为 200–599。
|
||||
|
||||
SSE `data` 是原始文本,不是宿主解码的 JSON。`has_data=false` 表示无 data 行,例如心跳注释。多行 data 合并为 `\n`;comments 是注释字符串数组。宿主会规范化 SSE 的行分隔及空格,保持协议语义,不承诺字节一致。缺少完整结束空行、非法 UTF-8 或超大帧会导致流失败。修改 event、id 时不能包含换行或 NUL。
|
||||
|
||||
```lua
|
||||
-- 原样继续;修改了参数但返回 pass,不会保留修改
|
||||
return {action='pass'}
|
||||
|
||||
-- 请求/响应替换,返回完整对象
|
||||
return {action='replace', value=request}
|
||||
|
||||
-- SSE 替换,可以产生一个或多个事件
|
||||
return {action='replace', events={event1, event2}}
|
||||
|
||||
-- 不输出任何事件;空数组须明确标记
|
||||
return {action='replace', events=host.json.array()}
|
||||
|
||||
-- 暂存由插件自行维护,宿主本次不发出事件
|
||||
return {action='hold'}
|
||||
|
||||
-- 立即阻断;reason 可作为插件内部说明,但不记录、不回显
|
||||
return {action='block', reason='internal explanation'}
|
||||
```
|
||||
|
||||
替换事件按数组顺序进入后续插件。`on_end` 释放的事件也经过后续插件的 `on_event`;前一个插件释放完成后才调用后一个插件的 `on_end`。内置 Lua 协议适配器最后处理事件,暂存 `run_completed`,在所有业务结束钩子通过后放行。
|
||||
|
||||
非流式响应也调用 `on_end`;此时不能释放 SSE 事件。执行性输出若需要审核,应在请求或完整响应钩子中完成。本层看到的工具生命周期事件不能阻止已经发生的 Agent 内部工具调用。
|
||||
|
||||
## JSON 数据桥
|
||||
|
||||
`host.json.decode(text)`、`host.json.encode(value)` 保留对象、数组、布尔、数字和 null。JSON null 用 `host.json.null` 表示;不与 Lua nil 混淆。
|
||||
|
||||
解码所得空数组保留数组类型,新建空数组请用 `host.json.array()` 或 `host.json.array(table)`。新建空 `{}` 默认编码为对象;连续的正整数键表编码为数组。禁止稀疏数组、循环引用、非字符串对象键、函数、Python userdata 和非有限数字;嵌套深度最多 64。
|
||||
|
||||
## 网络与日志
|
||||
|
||||
```lua
|
||||
local result = host.http.request({
|
||||
url='https://review.example.com/check',
|
||||
method='POST',
|
||||
headers={['content-type']='application/json'},
|
||||
body=host.json.encode({text='待审核内容'}),
|
||||
})
|
||||
-- result: {status=200, headers={...}, body='UTF-8 response text'}
|
||||
```
|
||||
|
||||
仅接受 url、method、headers、body。method 支持 GET/POST/PUT/PATCH/DELETE/HEAD/OPTIONS,默认 GET;body 默认空字符串。HTTP body 为 UTF-8 文本,第一版不提供二进制、文件上传或原始 socket。
|
||||
|
||||
请求在 Lua 中表现为同步调用,实际由宿主的异步网络代理执行,不阻塞主事件循环。网络错误抛出可被 `pcall` 捕获的异常;未捕获时插件失败并阻断。插件不得改变白名单、TLS 校验、代理、重定向或超时设置。3xx 直接返回,若自行跟随 Location,新地址也必须满足白名单。宿主不提供凭据,插件若需 API Key,应由管理员在此插件配置中注入,不能放进日志。
|
||||
|
||||
`host.log.info(...)`、`warning(...)`、`error(...)` 只生成固定的插件日志标记,不保存文本参数。每钩子最多 64 次宿主调用,限制可配置;日志和 HTTP 都计数。
|
||||
|
||||
模块加载及所有钩子都有超时与内存限制;配置修改后重启生效,不提供热加载或长期跨请求状态。业务规则应有正常对照测试,避免关键词规则把合法的安全研究或引用内容误判为攻击。
|
||||
@@ -0,0 +1 @@
|
||||
"""Lua-first agent middleware."""
|
||||
@@ -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()
|
||||
@@ -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})
|
||||
@@ -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
|
||||
@@ -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
|
||||
@@ -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"),
|
||||
}
|
||||
@@ -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
|
||||
@@ -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)
|
||||
@@ -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
|
||||
@@ -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()
|
||||
@@ -0,0 +1,15 @@
|
||||
local plugin = {}
|
||||
local config = {}
|
||||
function plugin.init(ctx, options) config = options end
|
||||
function plugin.on_request(ctx, request)
|
||||
local response = host.http.request({
|
||||
method='POST', url=config.url,
|
||||
headers={['content-type']='application/json'},
|
||||
body=request.body,
|
||||
})
|
||||
if response.status ~= 200 then return {action='block'} end
|
||||
local verdict = host.json.decode(response.body)
|
||||
if verdict.allow ~= true then return {action='block'} end
|
||||
return {action='pass'}
|
||||
end
|
||||
return plugin
|
||||
@@ -0,0 +1,11 @@
|
||||
local plugin = {}
|
||||
local config = {}
|
||||
function plugin.init(ctx, options) config = options end
|
||||
function plugin.on_request(ctx, request)
|
||||
local body = host.json.decode(request.body)
|
||||
if type(body.message) ~= 'string' then return {action='block'} end
|
||||
body.message = (config.prefix or '') .. body.message
|
||||
request.body = host.json.encode(body)
|
||||
return {action='replace', value=request}
|
||||
end
|
||||
return plugin
|
||||
@@ -0,0 +1,43 @@
|
||||
-- Demonstrates cross-event inspection. Intentionally buffers the entire SSE response.
|
||||
-- Masking keeps byte lengths, so redacted text can be placed back in original events.
|
||||
local plugin = {}
|
||||
local frames = {}
|
||||
function plugin.on_event(ctx, event)
|
||||
frames[#frames+1] = event
|
||||
return {action='hold'}
|
||||
end
|
||||
function plugin.on_end(ctx)
|
||||
local text = {}
|
||||
local payloads = {}
|
||||
for i, event in ipairs(frames) do
|
||||
if event.event == 'text_delta' then
|
||||
local payload = host.json.decode(event.data)
|
||||
local content = payload.data and payload.data.content
|
||||
if type(content) ~= 'string' then return {action='block'} end
|
||||
text[#text+1] = content
|
||||
payloads[i] = payload
|
||||
end
|
||||
end
|
||||
local combined = table.concat(text)
|
||||
local masked = string.gsub(combined, string.rep('%d',17)..'[%dXx]', function(v)
|
||||
return string.rep('*', #v)
|
||||
end)
|
||||
masked = string.gsub(masked, '1[3-9]'..string.rep('%d',9), function(v)
|
||||
return string.rep('*', #v)
|
||||
end)
|
||||
local offset = 1
|
||||
for i, event in ipairs(frames) do
|
||||
local payload = payloads[i]
|
||||
if payload then
|
||||
local length = #payload.data.content
|
||||
payload.data.content = string.sub(masked, offset, offset+length-1)
|
||||
offset = offset + length
|
||||
event.data = host.json.encode(payload)
|
||||
end
|
||||
end
|
||||
local released = host.json.array(frames)
|
||||
frames = {}
|
||||
return {action='replace', events=released}
|
||||
end
|
||||
function plugin.close(ctx) frames = {} end
|
||||
return plugin
|
||||
@@ -0,0 +1,39 @@
|
||||
[build-system]
|
||||
requires = ["setuptools>=78"]
|
||||
build-backend = "setuptools.build_meta"
|
||||
|
||||
[project]
|
||||
name = "agent-safe-middleware"
|
||||
version = "0.1.0"
|
||||
description = "Lua-first HTTP/SSE safety middleware for Python agents"
|
||||
requires-python = ">=3.12"
|
||||
dependencies = [
|
||||
"fastapi==0.142.4",
|
||||
"aiohttp==3.14.4",
|
||||
"PyYAML==6.0.3",
|
||||
"lupa==2.8",
|
||||
"uvicorn>=0.35,<1",
|
||||
]
|
||||
|
||||
[project.optional-dependencies]
|
||||
dev = ["pytest>=8,<10", "pytest-asyncio>=1,<2", "httpx>=0.28,<1", "ruff>=0.14,<1"]
|
||||
|
||||
[project.scripts]
|
||||
agent-safe-middleware = "middleware.cli:main"
|
||||
|
||||
[tool.setuptools.packages.find]
|
||||
include = ["middleware*"]
|
||||
|
||||
[tool.setuptools.package-data]
|
||||
middleware = ["lua/*.lua"]
|
||||
|
||||
[tool.pytest.ini_options]
|
||||
asyncio_mode = "auto"
|
||||
testpaths = ["tests"]
|
||||
|
||||
[tool.ruff]
|
||||
target-version = "py312"
|
||||
line-length = 100
|
||||
|
||||
[tool.ruff.lint]
|
||||
select = ["E4", "E7", "E9", "F", "I", "UP", "B"]
|
||||
@@ -0,0 +1,45 @@
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
from pydantic import ValidationError
|
||||
|
||||
from middleware.config import NetworkRule, Settings, load_settings
|
||||
|
||||
|
||||
def test_configuration_and_paths():
|
||||
settings = load_settings(Path(__file__).parents[1] / "config.yaml")
|
||||
assert settings.plugins[0].file.is_absolute()
|
||||
assert settings.limits.max_sessions == 4
|
||||
|
||||
|
||||
def test_duplicate_ids_and_missing_file(tmp_path):
|
||||
path = tmp_path / "config.yaml"
|
||||
path.write_text(
|
||||
"upstream: http://agent:8000\nplugins:\n - id: x\n file: absent.lua\n", encoding="utf-8"
|
||||
)
|
||||
with pytest.raises(ValueError):
|
||||
load_settings(path)
|
||||
with pytest.raises(ValidationError):
|
||||
Settings(
|
||||
upstream="http://agent",
|
||||
plugins=[
|
||||
{"id": "x", "file": "a.lua"},
|
||||
{"id": "x", "file": "b.lua"},
|
||||
],
|
||||
)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("domain", ["*", "bad/example.com", "foo..com", "127.0.0.1", "*.com*"])
|
||||
def test_bad_domains(domain):
|
||||
with pytest.raises(ValueError):
|
||||
NetworkRule(domain=domain)
|
||||
|
||||
|
||||
def test_wildcard_and_idna():
|
||||
rule = NetworkRule(domain="*.EXAMPLE.com.")
|
||||
assert rule.matches("a.example.com", "https", 443)
|
||||
assert rule.matches("a.b.example.com", "https", 443)
|
||||
assert not rule.matches("example.com", "https", 443)
|
||||
assert not rule.matches("badexample.com", "https", 443)
|
||||
assert not rule.matches("a.example.com", "http", 443)
|
||||
assert NetworkRule(domain="例子.测试").domain == "xn--fsqu00a.xn--0zwm56d"
|
||||
@@ -0,0 +1,95 @@
|
||||
"""Native TCP client → Uvicorn middleware → mock agent, including SSE cancellation."""
|
||||
|
||||
import asyncio
|
||||
from contextlib import asynccontextmanager
|
||||
|
||||
import httpx
|
||||
import uvicorn
|
||||
from aiohttp import web
|
||||
from test_proxy import frame, settings_for, upstream_server
|
||||
|
||||
from middleware.proxy import create_app
|
||||
from middleware.sse import encode_sse
|
||||
|
||||
|
||||
@asynccontextmanager
|
||||
async def running_service(app):
|
||||
server = uvicorn.Server(
|
||||
uvicorn.Config(
|
||||
app,
|
||||
host="127.0.0.1",
|
||||
port=0,
|
||||
log_level="critical",
|
||||
access_log=False,
|
||||
)
|
||||
)
|
||||
task = asyncio.create_task(server.serve())
|
||||
try:
|
||||
async with asyncio.timeout(10):
|
||||
while not server.started:
|
||||
if task.done():
|
||||
await task
|
||||
raise RuntimeError("server exited before startup")
|
||||
await asyncio.sleep(0.01)
|
||||
port = server.servers[0].sockets[0].getsockname()[1]
|
||||
yield f"http://127.0.0.1:{port}"
|
||||
finally:
|
||||
server.should_exit = True
|
||||
await asyncio.wait_for(task, 10)
|
||||
|
||||
|
||||
async def test_real_tcp_stream_overload_and_disconnect(tmp_path):
|
||||
release = asyncio.Event()
|
||||
agent_cancelled = asyncio.Event()
|
||||
|
||||
async def handler(request):
|
||||
message = (await request.json())["message"]
|
||||
response = web.StreamResponse(headers={"Content-Type": "text/event-stream"})
|
||||
await response.prepare(request)
|
||||
await response.write(encode_sse(frame("run_started", 1, {}), 1024))
|
||||
if message == "stream":
|
||||
await release.wait()
|
||||
await response.write(encode_sse(frame("text_delta", 2, {"content": "中文"}), 1024))
|
||||
await response.write(encode_sse(frame("run_completed", 3, {"status": "success"}), 1024))
|
||||
else:
|
||||
try:
|
||||
for _ in range(100):
|
||||
await asyncio.sleep(0.02)
|
||||
await response.write(b": heartbeat\n\n")
|
||||
except (ConnectionError, asyncio.CancelledError):
|
||||
agent_cancelled.set()
|
||||
return response
|
||||
|
||||
async with upstream_server(handler) as upstream:
|
||||
app = create_app(settings_for(tmp_path, upstream, max_sessions=1))
|
||||
async with running_service(app) as url, httpx.AsyncClient(base_url=url) as client:
|
||||
assert (await client.get("/readyz")).status_code == 200
|
||||
async with client.stream(
|
||||
"POST", "/chat/stream", json={"message": "stream"}
|
||||
) as response:
|
||||
lines = response.aiter_lines()
|
||||
first_event = []
|
||||
async with asyncio.timeout(3):
|
||||
async for line in lines:
|
||||
first_event.append(line)
|
||||
if not line:
|
||||
break
|
||||
assert "event: run_started" in first_event
|
||||
# First frame reached the client while the agent's remaining output is blocked.
|
||||
assert not release.is_set()
|
||||
assert (
|
||||
await client.post("/chat/stream", json={"message": "overload"})
|
||||
).status_code == 503
|
||||
release.set()
|
||||
remainder = "\n".join([line async for line in lines])
|
||||
assert "中文" in remainder and "event: run_completed" in remainder
|
||||
async with client.stream(
|
||||
"POST", "/chat/stream", json={"message": "disconnect"}
|
||||
) as response:
|
||||
async for line in response.aiter_lines():
|
||||
if line == "event: run_started":
|
||||
break
|
||||
await asyncio.wait_for(agent_cancelled.wait(), 3)
|
||||
async with asyncio.timeout(3):
|
||||
while app.state.manager.sessions:
|
||||
await asyncio.sleep(0.01)
|
||||
@@ -0,0 +1,238 @@
|
||||
import asyncio
|
||||
import socket
|
||||
|
||||
import pytest
|
||||
|
||||
from middleware.config import NetworkPolicy, NetworkRule
|
||||
from middleware.errors import LimitExceeded, NetworkDenied
|
||||
from middleware.network import NetworkBroker, PolicyResolver, address_allowed, approved_url
|
||||
|
||||
|
||||
def policy(**kwargs):
|
||||
return NetworkPolicy(allow=[NetworkRule(domain="*.example.com", **kwargs)])
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"url",
|
||||
[
|
||||
"https://example.com/",
|
||||
"https://badexample.com/",
|
||||
"http://a.example.com/",
|
||||
"https://a.example.com:444/",
|
||||
"https://user:pw@a.example.com/",
|
||||
"https://127.0.0.1/",
|
||||
"https://[::1]/",
|
||||
"https://2130706433/",
|
||||
"https://a.example.com.evil.test/",
|
||||
"file:///etc/passwd",
|
||||
"https://a.example.com\n/",
|
||||
],
|
||||
)
|
||||
def test_urls_denied(url):
|
||||
with pytest.raises(NetworkDenied):
|
||||
approved_url(url, policy())
|
||||
|
||||
|
||||
def test_exact_domain_and_case():
|
||||
url, _ = approved_url("https://A.Example.com./check", policy())
|
||||
assert url.host == "a.example.com"
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"address",
|
||||
[
|
||||
"127.0.0.1",
|
||||
"::1",
|
||||
"169.254.169.254",
|
||||
"100.100.100.200",
|
||||
"fd00:ec2::254",
|
||||
"224.0.0.1",
|
||||
"0.0.0.0",
|
||||
"::ffff:127.0.0.1",
|
||||
"240.1.1.1",
|
||||
"::",
|
||||
],
|
||||
)
|
||||
def test_permanent_denials_even_with_cidrs(address):
|
||||
rules = [NetworkRule(domain="a.example.com", cidrs=["0.0.0.0/0", "::/0"])]
|
||||
assert not address_allowed(address, rules)
|
||||
|
||||
|
||||
def test_private_network_must_be_explicit():
|
||||
rules = [NetworkRule(domain="a.example.com", cidrs=["10.20.0.0/16"])]
|
||||
assert address_allowed("8.8.8.8", rules)
|
||||
assert address_allowed("10.20.1.2", rules)
|
||||
assert not address_allowed("10.21.1.2", rules)
|
||||
assert not address_allowed("10.20.1.2", [NetworkRule(domain="a.example.com")])
|
||||
|
||||
|
||||
async def test_resolver_rejects_mixed_answers_and_pins_numeric_addresses(monkeypatch):
|
||||
loop = asyncio.get_running_loop()
|
||||
calls = []
|
||||
|
||||
async def lookup(host, port, **kwargs):
|
||||
calls.append(host)
|
||||
return [(socket.AF_INET, socket.SOCK_STREAM, 6, "", ("8.8.8.8", port))]
|
||||
|
||||
monkeypatch.setattr(loop, "getaddrinfo", lookup)
|
||||
resolver = PolicyResolver("a.example.com", policy().allow)
|
||||
addresses = await resolver.resolve("a.example.com", 443)
|
||||
assert calls == ["a.example.com"]
|
||||
assert addresses[0]["host"] == "8.8.8.8"
|
||||
assert addresses[0]["hostname"] == "a.example.com"
|
||||
assert addresses[0]["flags"] == socket.AI_NUMERICHOST
|
||||
|
||||
async def mixed(host, port, **kwargs):
|
||||
return [
|
||||
(socket.AF_INET, socket.SOCK_STREAM, 6, "", (ip, port))
|
||||
for ip in ["8.8.8.8", "127.0.0.1"]
|
||||
]
|
||||
|
||||
monkeypatch.setattr(loop, "getaddrinfo", mixed)
|
||||
with pytest.raises(NetworkDenied):
|
||||
await resolver.resolve("a.example.com", 443)
|
||||
with pytest.raises(NetworkDenied):
|
||||
await resolver.resolve("b.example.com", 443)
|
||||
|
||||
|
||||
async def test_broker_disables_proxy_redirect_and_cookies(monkeypatch):
|
||||
import middleware.network as module
|
||||
|
||||
seen = {}
|
||||
|
||||
class Content:
|
||||
async def iter_chunked(self, size):
|
||||
yield b"{}"
|
||||
|
||||
class Response:
|
||||
status = 302
|
||||
headers = {"Location": "http://127.0.0.1/admin"}
|
||||
content = Content()
|
||||
|
||||
async def __aenter__(self):
|
||||
return self
|
||||
|
||||
async def __aexit__(self, *args):
|
||||
pass
|
||||
|
||||
class Client:
|
||||
def __init__(self, **kwargs):
|
||||
seen.update(kwargs)
|
||||
|
||||
async def __aenter__(self):
|
||||
return self
|
||||
|
||||
async def __aexit__(self, *args):
|
||||
await seen["connector"].close()
|
||||
|
||||
def request(self, method, url, **kwargs):
|
||||
seen["request"] = kwargs
|
||||
return Response()
|
||||
|
||||
monkeypatch.setenv("HTTPS_PROXY", "http://127.0.0.1:3128")
|
||||
monkeypatch.setattr(module.aiohttp, "ClientSession", Client)
|
||||
result = await NetworkBroker().request(
|
||||
policy(),
|
||||
{
|
||||
"url": "https://a.example.com/",
|
||||
"headers": {"Host": "other", "X-Test": "ok"},
|
||||
},
|
||||
100,
|
||||
)
|
||||
assert result["status"] == 302
|
||||
assert seen["trust_env"] is False
|
||||
assert seen["request"]["allow_redirects"] is False
|
||||
assert seen["request"]["headers"] == {"X-Test": "ok"}
|
||||
assert isinstance(seen["connector"]._resolver, PolicyResolver)
|
||||
assert seen["connector"]._use_dns_cache is False
|
||||
assert seen["connector"]._ssl is True
|
||||
with pytest.raises(LimitExceeded):
|
||||
await NetworkBroker().request(policy(), {"url": "https://a.example.com", "body": "xx"}, 1)
|
||||
|
||||
|
||||
async def test_broker_response_cap_and_timeout(monkeypatch):
|
||||
import middleware.network as module
|
||||
|
||||
class Content:
|
||||
async def iter_chunked(self, size):
|
||||
yield b"too-large"
|
||||
|
||||
class Response:
|
||||
status = 200
|
||||
headers = {}
|
||||
content = Content()
|
||||
|
||||
async def __aenter__(self):
|
||||
return self
|
||||
|
||||
async def __aexit__(self, *args):
|
||||
pass
|
||||
|
||||
class Client:
|
||||
def __init__(self, **kwargs):
|
||||
self.connector = kwargs["connector"]
|
||||
|
||||
async def __aenter__(self):
|
||||
return self
|
||||
|
||||
async def __aexit__(self, *args):
|
||||
await self.connector.close()
|
||||
|
||||
def request(self, *args, **kwargs):
|
||||
return Response()
|
||||
|
||||
monkeypatch.setattr(module.aiohttp, "ClientSession", Client)
|
||||
restricted = policy().model_copy(update={"max_response_bytes": 3})
|
||||
with pytest.raises(LimitExceeded):
|
||||
await NetworkBroker().request(restricted, {"url": "https://a.example.com"}, 100)
|
||||
|
||||
|
||||
async def test_real_client_uses_pinned_address_without_second_dns_or_redirect(monkeypatch):
|
||||
# Test-only transport redirection lets a real aiohttp client use a local fake service
|
||||
# while observing the approved numeric address presented to the actual connector.
|
||||
import aiohttp
|
||||
from aiohttp import web
|
||||
|
||||
hits = []
|
||||
|
||||
async def handler(request):
|
||||
hits.append(request.headers["Host"])
|
||||
return web.Response(status=302, headers={"Location": "http://127.0.0.1/admin"})
|
||||
|
||||
app = web.Application()
|
||||
app.router.add_get("/", handler)
|
||||
runner = web.AppRunner(app)
|
||||
await runner.setup()
|
||||
site = web.TCPSite(runner, "127.0.0.1", 0)
|
||||
await site.start()
|
||||
port = site._server.sockets[0].getsockname()[1]
|
||||
lookups = []
|
||||
|
||||
async def rebinding_dns(host, requested_port, **kwargs):
|
||||
lookups.append(host)
|
||||
ip = "8.8.8.8" if len(lookups) == 1 else "127.0.0.1"
|
||||
return [(socket.AF_INET, socket.SOCK_STREAM, 6, "", (ip, requested_port))]
|
||||
|
||||
original = aiohttp.TCPConnector._wrap_create_connection
|
||||
|
||||
async def observed_connect(self, *args, addr_infos, **kwargs):
|
||||
assert addr_infos[0][4][0] == "8.8.8.8"
|
||||
assert kwargs["req"].url.host == "a.example.com"
|
||||
local = [(socket.AF_INET, socket.SOCK_STREAM, 6, "", ("127.0.0.1", port))]
|
||||
return await original(self, *args, addr_infos=local, **kwargs)
|
||||
|
||||
monkeypatch.setattr(asyncio.get_running_loop(), "getaddrinfo", rebinding_dns)
|
||||
monkeypatch.setattr(aiohttp.TCPConnector, "_wrap_create_connection", observed_connect)
|
||||
monkeypatch.setenv("HTTP_PROXY", "http://127.0.0.1:1")
|
||||
configured = NetworkPolicy(
|
||||
allow=[NetworkRule(domain="a.example.com", scheme="http", ports=[port])]
|
||||
)
|
||||
try:
|
||||
response = await NetworkBroker().request(
|
||||
configured, {"url": f"http://a.example.com:{port}/"}, 100
|
||||
)
|
||||
assert response["status"] == 302
|
||||
assert lookups == ["a.example.com"]
|
||||
assert hits == [f"a.example.com:{port}"]
|
||||
finally:
|
||||
await runner.cleanup()
|
||||
@@ -0,0 +1,323 @@
|
||||
import asyncio
|
||||
import json
|
||||
from contextlib import asynccontextmanager
|
||||
|
||||
import httpx
|
||||
import pytest
|
||||
from aiohttp import web
|
||||
|
||||
from middleware.config import Limits, PluginConfig, Settings
|
||||
from middleware.proxy import create_app
|
||||
from middleware.sse import decode_sse, encode_sse
|
||||
|
||||
|
||||
def frame(name, sequence, data):
|
||||
return {
|
||||
"event": name,
|
||||
"id": str(sequence),
|
||||
"has_data": True,
|
||||
"data": json.dumps(
|
||||
{
|
||||
"request_id": "00000000-0000-4000-8000-000000000000",
|
||||
"sequence": sequence,
|
||||
"timestamp": "2026-10-08T00:00:00+00:00",
|
||||
"data": data,
|
||||
},
|
||||
ensure_ascii=False,
|
||||
),
|
||||
}
|
||||
|
||||
|
||||
@asynccontextmanager
|
||||
async def upstream_server(handler):
|
||||
app = web.Application()
|
||||
app.router.add_post("/chat/stream", handler)
|
||||
runner = web.AppRunner(app)
|
||||
await runner.setup()
|
||||
site = web.TCPSite(runner, "127.0.0.1", 0)
|
||||
await site.start()
|
||||
port = site._server.sockets[0].getsockname()[1]
|
||||
try:
|
||||
yield f"http://127.0.0.1:{port}"
|
||||
finally:
|
||||
await runner.cleanup()
|
||||
|
||||
|
||||
def settings_for(tmp_path, upstream, source=None, **limits):
|
||||
plugins = []
|
||||
if source is not None:
|
||||
file = tmp_path / "test.lua"
|
||||
file.write_text(source, encoding="utf-8")
|
||||
plugins.append(PluginConfig(id="test", file=file))
|
||||
return Settings(upstream=upstream, plugins=plugins, limits=Limits(**limits))
|
||||
|
||||
|
||||
@asynccontextmanager
|
||||
async def client_for(settings):
|
||||
app = create_app(settings)
|
||||
async with app.router.lifespan_context(app):
|
||||
async with httpx.AsyncClient(
|
||||
transport=httpx.ASGITransport(app), base_url="http://middleware"
|
||||
) as client:
|
||||
yield client, app
|
||||
|
||||
|
||||
async def event_list(content):
|
||||
async def pieces():
|
||||
for byte in content:
|
||||
yield bytes([byte])
|
||||
|
||||
return [e async for e in decode_sse(pieces(), 262144)]
|
||||
|
||||
|
||||
async def test_passthrough_sse_and_health(tmp_path):
|
||||
expected = [
|
||||
frame("run_started", 1, {"conversation_id": "c"}),
|
||||
frame("text_delta", 2, {"content": "中文"}),
|
||||
frame("mcp_call_started", 3, {"server": "weather", "tool": "query"}),
|
||||
frame("mcp_call_finished", 4, {"status": "success"}),
|
||||
frame("run_completed", 5, {"status": "success"}),
|
||||
]
|
||||
received = []
|
||||
queries = []
|
||||
|
||||
async def handler(request):
|
||||
received.append(await request.json())
|
||||
queries.append(request.rel_url.raw_query_string)
|
||||
response = web.StreamResponse(headers={"Content-Type": "text/event-stream"})
|
||||
await response.prepare(request)
|
||||
for item in expected:
|
||||
# Exercise real upstream network chunking including split Chinese UTF-8.
|
||||
for byte in encode_sse(item, 262144):
|
||||
await response.write(bytes([byte]))
|
||||
await response.write_eof()
|
||||
return response
|
||||
|
||||
async with upstream_server(handler) as upstream:
|
||||
async with client_for(settings_for(tmp_path, upstream)) as (client, app):
|
||||
assert (await client.get("/healthz")).json() == {"status": "ok"}
|
||||
assert (await client.get("/readyz")).status_code == 200
|
||||
result = await client.post(
|
||||
"/chat/stream?token=a%2Fb&x=a+b", json={"message": "你好", "conversation_id": "c"}
|
||||
)
|
||||
assert result.status_code == 200
|
||||
events = await event_list(result.content)
|
||||
assert [e["event"] for e in events] == [e["event"] for e in expected]
|
||||
assert [json.loads(e["data"]) for e in events] == [
|
||||
json.loads(e["data"]) for e in expected
|
||||
]
|
||||
assert received == [{"message": "你好", "conversation_id": "c"}]
|
||||
assert queries == ["token=a%2Fb&x=a+b"]
|
||||
assert not app.state.manager.sessions
|
||||
|
||||
|
||||
async def test_block_request_never_reaches_agent(tmp_path):
|
||||
calls = []
|
||||
|
||||
async def handler(request):
|
||||
calls.append(1)
|
||||
return web.json_response({})
|
||||
|
||||
async with upstream_server(handler) as upstream:
|
||||
settings = settings_for(
|
||||
tmp_path, upstream, "return {on_request=function() return {action='block'} end}"
|
||||
)
|
||||
async with client_for(settings) as (client, app):
|
||||
assert (await client.post("/chat/stream", json={"message": "x"})).status_code == 403
|
||||
assert not calls
|
||||
assert not app.state.manager.sessions
|
||||
|
||||
|
||||
async def test_json_rewrite_and_non_stream_response(tmp_path):
|
||||
async def handler(request):
|
||||
data = await request.json()
|
||||
return web.json_response({"echo": data["message"]})
|
||||
|
||||
source = """
|
||||
return {on_request=function(ctx,r)
|
||||
local b=host.json.decode(r.body); b.message='rewritten'
|
||||
r.body=host.json.encode(b); return {action='replace',value=r}
|
||||
end,on_response=function(ctx,r)
|
||||
local b=host.json.decode(r.body); b.checked=true
|
||||
r.body=host.json.encode(b); return {action='replace',value=r}
|
||||
end}
|
||||
"""
|
||||
async with upstream_server(handler) as upstream:
|
||||
async with client_for(settings_for(tmp_path, upstream, source)) as (client, _):
|
||||
result = await client.post("/chat/stream", json={"message": "x"})
|
||||
assert result.json() == {"echo": "rewritten", "checked": True}
|
||||
|
||||
|
||||
@pytest.mark.parametrize("hook", ["on_event", "on_end"])
|
||||
async def test_stream_failure_has_run_error_without_success(tmp_path, hook, caplog):
|
||||
async def handler(request):
|
||||
return web.Response(
|
||||
body=b"".join(
|
||||
encode_sse(e, 1024)
|
||||
for e in [
|
||||
frame("run_started", 1, {}),
|
||||
frame("text_delta", 2, {"content": "secret"}),
|
||||
frame("run_completed", 3, {"status": "success"}),
|
||||
]
|
||||
),
|
||||
content_type="text/event-stream",
|
||||
)
|
||||
|
||||
source = (
|
||||
"return {on_event=function(ctx,e) if e.event=='text_delta' then error('private-key') end end}"
|
||||
if hook == "on_event"
|
||||
else "return {on_end=function() error('private-key') end}"
|
||||
)
|
||||
async with upstream_server(handler) as upstream:
|
||||
async with client_for(settings_for(tmp_path, upstream, source)) as (client, app):
|
||||
result = await client.post("/chat/stream", json={"message": "x"})
|
||||
events = await event_list(result.content)
|
||||
assert events[-1]["event"] == "run_error"
|
||||
assert not any(e["event"] == "run_completed" for e in events)
|
||||
payload = json.loads(events[-1]["data"])
|
||||
assert payload["timestamp"]
|
||||
assert payload["request_id"] == "00000000-0000-4000-8000-000000000000"
|
||||
assert payload["data"] == {"error_type": "MiddlewareFailure"}
|
||||
assert "private-key" not in result.text + caplog.text
|
||||
assert not app.state.manager.sessions
|
||||
|
||||
|
||||
async def test_stream_size_failure_and_request_limit(tmp_path):
|
||||
async def handler(request):
|
||||
return web.Response(
|
||||
body=b"data: " + b"x" * 1000 + b"\n\n", content_type="text/event-stream"
|
||||
)
|
||||
|
||||
async with upstream_server(handler) as upstream:
|
||||
settings = settings_for(tmp_path, upstream, max_sse_frame_bytes=500, max_request_bytes=100)
|
||||
async with client_for(settings) as (client, _):
|
||||
result = await client.post("/chat/stream", content=b"x" * 101)
|
||||
assert result.status_code == 413
|
||||
result = await client.post("/chat/stream", json={"message": "x"})
|
||||
assert (await event_list(result.content))[-1]["event"] == "run_error"
|
||||
|
||||
|
||||
async def test_disconnect_before_first_chunk_releases_session(tmp_path):
|
||||
cancelled = asyncio.Event()
|
||||
|
||||
async def handler(request):
|
||||
response = web.StreamResponse(headers={"Content-Type": "text/event-stream"})
|
||||
await response.prepare(request)
|
||||
try:
|
||||
for _ in range(100):
|
||||
await asyncio.sleep(0.02)
|
||||
await response.write(b": heartbeat\n\n")
|
||||
except (ConnectionError, asyncio.CancelledError):
|
||||
cancelled.set()
|
||||
return response
|
||||
|
||||
async with upstream_server(handler) as upstream:
|
||||
app = create_app(settings_for(tmp_path, upstream))
|
||||
async with app.router.lifespan_context(app):
|
||||
queue = asyncio.Queue()
|
||||
await queue.put(
|
||||
{"type": "http.request", "body": b'{"message":"x"}', "more_body": False}
|
||||
)
|
||||
|
||||
async def send(message):
|
||||
if message["type"] == "http.response.start":
|
||||
await queue.put({"type": "http.disconnect"})
|
||||
|
||||
scope = {
|
||||
"type": "http",
|
||||
"asgi": {"version": "3.0", "spec_version": "2.4"},
|
||||
"http_version": "1.1",
|
||||
"method": "POST",
|
||||
"scheme": "http",
|
||||
"path": "/chat/stream",
|
||||
"raw_path": b"/chat/stream",
|
||||
"query_string": b"",
|
||||
"headers": [(b"content-type", b"application/json")],
|
||||
"server": ("middleware", 80),
|
||||
"client": ("client", 1),
|
||||
}
|
||||
await asyncio.wait_for(app(scope, queue.get, send), 5)
|
||||
assert not app.state.manager.sessions
|
||||
await asyncio.wait_for(cancelled.wait(), 2)
|
||||
|
||||
|
||||
async def test_blocked_stream_discards_frame_and_adapter_failure_closes(tmp_path):
|
||||
async def handler(request):
|
||||
return web.Response(
|
||||
body=b"".join(
|
||||
encode_sse(e, 1024)
|
||||
for e in [
|
||||
frame("run_started", 1, {}),
|
||||
frame("text_delta", 2, {"content": "DO-NOT-SEND"}),
|
||||
frame("run_completed", 3, {"status": "success"}),
|
||||
]
|
||||
),
|
||||
content_type="text/event-stream",
|
||||
)
|
||||
|
||||
source = "return {on_event=function(ctx,e) if e.event=='text_delta' then return {action='block'} end end}"
|
||||
async with upstream_server(handler) as upstream:
|
||||
async with client_for(settings_for(tmp_path, upstream, source)) as (client, app):
|
||||
result = await client.post("/chat/stream", json={"message": "x"})
|
||||
events = await event_list(result.content)
|
||||
assert events[-1]["event"] == "run_error"
|
||||
assert json.loads(events[-1]["data"])["data"]["error_type"] == "PolicyBlocked"
|
||||
assert "DO-NOT-SEND" not in result.text
|
||||
|
||||
async def broken_adapter(*args):
|
||||
raise RuntimeError("private adapter detail")
|
||||
|
||||
app.state.manager.error_event = broken_adapter
|
||||
result = await client.post("/chat/stream", json={"message": "x"})
|
||||
assert [e["event"] for e in await event_list(result.content)] == ["run_started"]
|
||||
assert "private adapter detail" not in result.text
|
||||
assert not app.state.manager.sessions
|
||||
|
||||
|
||||
async def test_plugin_failure_before_response_and_nonstream_limit(tmp_path):
|
||||
calls = []
|
||||
|
||||
async def handler(request):
|
||||
calls.append(1)
|
||||
return web.json_response({"long": "x" * 100})
|
||||
|
||||
async with upstream_server(handler) as upstream:
|
||||
source = "return {on_request=function() error('sensitive-input') end}"
|
||||
async with client_for(settings_for(tmp_path, upstream, source)) as (client, _):
|
||||
result = await client.post("/chat/stream", json={"message": "x"})
|
||||
assert result.status_code == 502
|
||||
assert not calls
|
||||
async with client_for(settings_for(tmp_path, upstream, max_response_bytes=10)) as (
|
||||
client,
|
||||
app,
|
||||
):
|
||||
result = await client.post("/chat/stream", json={"message": "x"})
|
||||
assert result.status_code == 502
|
||||
assert not app.state.manager.sessions
|
||||
|
||||
|
||||
async def test_stream_total_deadline_closes_upstream(tmp_path):
|
||||
closed = asyncio.Event()
|
||||
|
||||
async def handler(request):
|
||||
response = web.StreamResponse(headers={"Content-Type": "text/event-stream"})
|
||||
await response.prepare(request)
|
||||
await response.write(encode_sse(frame("run_started", 1, {}), 1024))
|
||||
try:
|
||||
while True:
|
||||
await asyncio.sleep(0.02)
|
||||
await response.write(b": heartbeat\n\n")
|
||||
except ConnectionError:
|
||||
closed.set()
|
||||
return response
|
||||
|
||||
async with upstream_server(handler) as upstream:
|
||||
async with client_for(settings_for(tmp_path, upstream, upstream_timeout_seconds=0.8)) as (
|
||||
client,
|
||||
app,
|
||||
):
|
||||
result = await client.post("/chat/stream", json={"message": "x"})
|
||||
events = await event_list(result.content)
|
||||
assert events[-1]["event"] == "run_error"
|
||||
assert not app.state.manager.sessions
|
||||
await asyncio.wait_for(closed.wait(), 2)
|
||||
@@ -0,0 +1,337 @@
|
||||
import asyncio
|
||||
from pathlib import Path
|
||||
|
||||
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()
|
||||
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_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()
|
||||
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()
|
||||
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()
|
||||
with pytest.raises(Overloaded):
|
||||
await manager.open()
|
||||
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()
|
||||
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()
|
||||
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()
|
||||
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()
|
||||
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('raw-secret') end}",
|
||||
"return {close=function() error('private') end}",
|
||||
],
|
||||
)
|
||||
session = await manager.open()
|
||||
await session.aclose()
|
||||
assert "plugin_log" in caplog.text
|
||||
assert "raw-secret" not in caplog.text
|
||||
|
||||
|
||||
async def test_example_redacts_cross_event_phone(tmp_path):
|
||||
source = (Path(__file__).parents[1] / "plugins/stream_redact.lua").read_text(encoding="utf-8")
|
||||
manager = manager_for(tmp_path, [source])
|
||||
session = await manager.open()
|
||||
try:
|
||||
for content in ["号码138", "1234", "5678"]:
|
||||
import json
|
||||
|
||||
assert (
|
||||
await session.apply(
|
||||
"on_event",
|
||||
{
|
||||
"event": "text_delta",
|
||||
"data": json.dumps({"data": {"content": content}}),
|
||||
},
|
||||
)
|
||||
== []
|
||||
)
|
||||
results = await session.end()
|
||||
text = "".join(json.loads(e["data"])["data"]["content"] for e in results)
|
||||
assert text == "号码***********"
|
||||
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()
|
||||
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()
|
||||
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()
|
||||
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()
|
||||
|
||||
|
||||
async def test_network_example_uses_configuration_and_http_result(tmp_path):
|
||||
from middleware.config import NetworkPolicy, NetworkRule
|
||||
|
||||
source = Path(__file__).parents[1] / "plugins/network_review.lua"
|
||||
plugin = PluginConfig(
|
||||
id="review",
|
||||
file=source,
|
||||
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": 200, "headers": {}, "body": '{"allow":true}'}
|
||||
|
||||
manager.broker = RecordingBroker()
|
||||
session = await manager.open()
|
||||
try:
|
||||
original = {"body": '{"message":"test"}'}
|
||||
assert await session.apply("on_request", original) == [original]
|
||||
assert calls[0]["url"] == "https://review.example.com/check"
|
||||
assert calls[0]["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()
|
||||
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()
|
||||
@@ -0,0 +1,41 @@
|
||||
import pytest
|
||||
|
||||
from middleware.errors import LimitExceeded, PluginFailure
|
||||
from middleware.sse import decode_sse, encode_sse
|
||||
|
||||
|
||||
async def pieces(value, size=1):
|
||||
for i in range(0, len(value), size):
|
||||
yield value[i : i + size]
|
||||
|
||||
|
||||
async def test_split_unicode_crlf_multiline_comments():
|
||||
raw = "\ufeff: heartbeat\r\nevent: text_delta\r\nid: 1\r\ndata: 中文\r\ndata: second\r\nretry: 20\r\n\r\n".encode()
|
||||
events = [event async for event in decode_sse(pieces(raw), 1024)]
|
||||
assert events == [
|
||||
{
|
||||
"data": "中文\nsecond",
|
||||
"comments": [" heartbeat"],
|
||||
"event": "text_delta",
|
||||
"id": "1",
|
||||
"retry": 20,
|
||||
"has_data": True,
|
||||
}
|
||||
]
|
||||
assert [e async for e in decode_sse(pieces(encode_sse(events[0], 1024)), 1024)] == events
|
||||
|
||||
|
||||
async def test_heartbeat_and_incomplete_frame():
|
||||
events = [e async for e in decode_sse(pieces(b": ping\n\n"), 1024)]
|
||||
assert events[0]["has_data"] is False
|
||||
with pytest.raises(PluginFailure):
|
||||
_ = [e async for e in decode_sse(pieces(b"data: unfinished"), 1024)]
|
||||
|
||||
|
||||
async def test_frame_size_and_invalid_utf8():
|
||||
with pytest.raises(LimitExceeded):
|
||||
_ = [e async for e in decode_sse(pieces(b"data: " + b"x" * 100), 20)]
|
||||
with pytest.raises(UnicodeError):
|
||||
_ = [e async for e in decode_sse(pieces(b"data: \xff\n\n"), 100)]
|
||||
with pytest.raises(PluginFailure):
|
||||
encode_sse({"event": "evil\ndata: bad", "data": "x"}, 1024)
|
||||
Reference in new issue
Block a user