插件改造:输出改为 OpenAI 协议,审核改走远程接口

response_guard.lua 重写:按 OpenAI 协议定位内容(choices[*].delta.content / message.content,支持多路径覆盖 tool_calls.arguments),判定改走远程 /chat/completions,拦截输出 400 content_policy_violation,审核不可用输出 503 safety_review_unavailable。

stream_redact.lua 改为 OpenAI SSE 全缓冲 PII 兜底,默认关闭;request_rewrite.lua 改为只重写最后一条 user 消息,默认关闭。

config.yaml 接口路径改为 /v1/chat/completions,停用缺模型文件的 guard_model 段与依赖 host.files 的 /upload 插件段,hook_timeout 调到 45s。

新增 tools/verify_plugins.py:13 个场景 57 项断言的契约校验。
This commit is contained in:
Автомата Калашникова committed 2026-11-27 17:25:18 +08:00
1 parent e1f944f16d
commit 9218bdf1e8
6 files changed
+1967 -1288

No files matched your search

+3
View File
@@ -10,3 +10,6 @@ config.local.yaml
.env
tmp/
*.log
# 本次改造前的插件备份
_bak_before_openai/
+78 -27
View File
@@ -4,7 +4,8 @@ listen_port: 8080
limits:
max_sessions: 4
hook_timeout_seconds: 30
# 判定走远程 /chat/completions:单次 1~5s,最多切 8 段,留足余量
hook_timeout_seconds: 45
upstream_timeout_seconds: 120
max_attachment_files: 8
max_attachment_fields: 128
@@ -14,69 +15,119 @@ limits:
attachment_timeout_seconds: 30
max_attachment_reads: 64
llm:
- id: guard_model
type: guard
file: models/guard_model
load: {device: cpu}
limits:
max_input_tokens: 8192
max_new_tokens: 32
timeout_seconds: 30
queue_size: 8
# 本地守卫模型已停用,判定统一走下面的 OpenAI 兼容接口。
# models/guard_model 在当前环境中不存在,保留本段会导致网关启动失败,故整段注释。
# 若要把本地守卫模型加回来:取消注释,并把模型文件放到 models/guard_model。
# llm:
# - id: guard_model
# type: guard
# file: models/guard_model
# load: {device: cpu}
# limits:
# max_input_tokens: 8192
# max_new_tokens: 32
# timeout_seconds: 30
# queue_size: 8
plugins:
# ---------------------------------------------------------------------------
# 旧协议遗留(/upload),依赖上面已停用的 guard_model,并且宿主没有 host.files
# 能力,实际无法工作。文件保留在 plugins/ 下,配置停用;需要时再恢复。
# ---------------------------------------------------------------------------
- id: file-content-review
enabled: false
file: plugins/file_content_review.lua
match:
paths: [/upload]
llm:
allow: [guard_model]
paths: ["/upload"]
config:
model: guard_model
allowed_extensions: [txt, doc, docx]
max_review_bytes: 8192
max_files: 8
# ---------------------------------------------------------------------------
# 旧协议遗留(/chat/stream),外部审核服务白名单转发,本来就是停用状态。
# ---------------------------------------------------------------------------
- id: network-review
enabled: false
file: plugins/network_review.lua
match:
paths: [/chat/stream]
paths: ["/chat/stream"]
network:
allow:
- domain: review.example.com # 本地联调改 mock-review.local
- domain: review.example.com
scheme: https
ports: [443]
timeout_seconds: 5
max_response_bytes: 1048576
config:
url: https://review.example.com/check # 本地联调改 http://mock-review.local:8001/check
url: https://review.example.com/check
fields: [messages]
headers: {x-api-key: "injected-by-admin"}
# ---------------------------------------------------------------------------
# 输入 + 输出内容安全(OpenAI 协议)
# 请求侧:判定不通过 → 请求体换成 stub(原文不发给模型)→ 响应侧返回 400
# 响应侧:逐段审核 → 脱敏 → 放行;不安全/审核不可用 → OpenAI 错误体
# ---------------------------------------------------------------------------
- id: response-guard
file: plugins/response_guard.lua
match:
paths: [/chat/stream]
llm: {allow: [guard_model]}
paths: ["/v1/chat/completions", "/v1/completions"]
network:
allow:
- domain: ai.leapstella.com
scheme: https
ports: [443]
timeout_seconds: 20
max_response_bytes: 1048576
config:
model: guard_model # 必须与 llm 注册的 id 一致
content_path: data.content
base_url: https://ai.leapstella.com/v1
# 部署时填入自己的密钥;仓库里只有占位符,真实密钥不入库
api_key: "sk-REPLACE_ME"
model: deepseek-flash
# 拦截状态码:400 = OpenAI 内容策略拒绝的标准形态
block_status: 400
# incremental: 攒够 flush_chars 且遇到句边界就审核放行(有增量输出)
# buffered : 整条响应结束再一次审核(1 次判定,但客户端看不到增量)
stream_mode: incremental
flush_chars: 512
force_flush_bytes: 4096
# 上限与判定能力对齐:8 段 × judge_chunk_bytes(16KB) = 128KB
max_buffer_bytes: 131072
# 正文之外还要审核工具调用参数时,改成数组即可(默认只审核正文):
# content_path_stream: ["choices.*.delta.content",
# "choices.*.delta.tool_calls.*.function.arguments"]
# content_path_full: ["choices.*.message.content",
# "choices.*.message.tool_calls.*.function.arguments"]
judge_chunk_bytes: 16384
judge_max_tokens: 512
# deepseek 系列默认带思维链,判定用不到;none 可省 ~0.3s 且避免思维链吃光 token。
# 换后端若报 400,删掉这一行即可。
judge_reasoning_effort: none
check_input: true
check_output: true
# ---------------------------------------------------------------------------
# 最后一条 user 消息打标;会重写整个 body,默认关闭
# ---------------------------------------------------------------------------
- id: request-rewrite
enabled: false
file: plugins/request_rewrite.lua
match:
paths: [/chat/stream]
paths: ["/v1/chat/completions"]
config:
prefix: "[checked] "
# ---------------------------------------------------------------------------
# 全缓冲 PII 兜底(跨帧拆分的证件号/手机号)
# 代价:流式退化为一次性输出,与 response_guard 的增量放行冲突,默认关闭
# ---------------------------------------------------------------------------
- id: stream-redact
enabled: false
file: plugins/stream_redact.lua
match:
paths: [/chat/stream]
paths: ["/v1/chat/completions"]
config:
text_event: text_delta
content_path: data.content
terminal_error_events: [run_error]
control_event_names: [heartbeat, run_started, run_finished, run_error, run_completed]
content_path: choices.*.delta.content
max_buffer_bytes: 262144
+97 -97
View File
@@ -1,88 +1,96 @@
-- request_rewrite.lua
-- Request rewrite example following docs/plugins.md (Lua plugin interface v1).
-- ============================================================================
-- request_rewrite.lua —— OpenAI Chat Completions 请求改写(Lua 插件接口 v1)
--
-- Example config:
-- prefix: "[checked] "
-- 作用
-- 在最后一条 user 消息的正文前加上配置的前缀,用于打标/灰度/审计定位。
-- 只认 OpenAI 的 messages 结构,不再处理旧的单 message 字段。
--
-- Scope:
-- Intended for route-level use on chat-style JSON requests with a string
-- "message" field. Requests that are not applicable (invalid/non-object JSON,
-- or missing/non-string message) pass through unchanged.
-- 适用性
-- content 为字符串,或 content 为 [{type:"text",text:"..."}] 数组时改写;
-- 其它情况(非 JSON、无 user 消息、多模态纯图片等)原样放行。
--
-- Important:
-- This implementation decodes and re-encodes the complete JSON object after
-- changing message. Other fields' serialized representation (key order,
-- whitespace, escapes, numeric representation, etc.) may change. Do not use
-- it where downstream systems require byte-identical body/signature stability.
--
-- Contract:
-- init(ctx, config) must return nil.
-- on_request may return pass, replace, or block.
-- method/path are preserved; a new request table is returned for replace.
-- 注意
-- 改写会重新序列化整个 body(键序、空白、转义可能与原始字节不同),
-- 下游若要求签名稳定的字节级一致,请不要启用本插件。
-- ============================================================================
local plugin = {}
local settings = {
prefix = "",
}
local settings = { prefix = "" }
local MAX_PREFIX_BYTES = 1024
local function is_valid_utf8(value)
if type(value) ~= "string" then
if type(value) ~= "string" then return false end
local i, n = 1, #value
while i <= n do
local b1 = value:byte(i)
if b1 <= 0x7F then
i = i + 1
elseif b1 >= 0xC2 and b1 <= 0xDF then
local b2 = value:byte(i + 1)
if not b2 or b2 < 0x80 or b2 > 0xBF then return false end
i = i + 2
elseif b1 == 0xE0 then
local b2, b3 = value:byte(i + 1, i + 2)
if not b2 or not b3 or b2 < 0xA0 or b2 > 0xBF or b3 < 0x80 or b3 > 0xBF then
return false
end
i = i + 3
elseif (b1 >= 0xE1 and b1 <= 0xEC) or (b1 >= 0xEE and b1 <= 0xEF) then
local b2, b3 = value:byte(i + 1, i + 2)
if not b2 or not b3 or b2 < 0x80 or b2 > 0xBF or b3 < 0x80 or b3 > 0xBF then
return false
end
i = i + 3
elseif b1 == 0xED then
local b2, b3 = value:byte(i + 1, i + 2)
if not b2 or not b3 or b2 < 0x80 or b2 > 0x9F or b3 < 0x80 or b3 > 0xBF then
return false
end
i = i + 3
elseif b1 == 0xF0 then
local b2, b3, b4 = value:byte(i + 1, i + 3)
if not b2 or not b3 or not b4 or b2 < 0x90 or b2 > 0xBF
or b3 < 0x80 or b3 > 0xBF or b4 < 0x80 or b4 > 0xBF then
return false
end
i = i + 4
elseif b1 >= 0xF1 and b1 <= 0xF3 then
local b2, b3, b4 = value:byte(i + 1, i + 3)
if not b2 or not b3 or not b4 or b2 < 0x80 or b2 > 0xBF
or b3 < 0x80 or b3 > 0xBF or b4 < 0x80 or b4 > 0xBF then
return false
end
i = i + 4
elseif b1 == 0xF4 then
local b2, b3, b4 = value:byte(i + 1, i + 3)
if not b2 or not b3 or not b4 or b2 < 0x80 or b2 > 0x8F
or b3 < 0x80 or b3 > 0xBF or b4 < 0x80 or b4 > 0xBF then
return false
end
i = i + 4
else
return false
end
end
return true
end
local i = 1
local n = #value
while i <= n do
local b1 = value:byte(i)
if b1 <= 0x7F then
i = i + 1
elseif b1 >= 0xC2 and b1 <= 0xDF then
local b2 = value:byte(i + 1)
if not b2 or b2 < 0x80 or b2 > 0xBF then return false end
i = i + 2
elseif b1 == 0xE0 then
local b2, b3 = value:byte(i + 1, i + 2)
if not b2 or not b3 or b2 < 0xA0 or b2 > 0xBF
or b3 < 0x80 or b3 > 0xBF then return false end
i = i + 3
elseif (b1 >= 0xE1 and b1 <= 0xEC) or (b1 >= 0xEE and b1 <= 0xEF) then
local b2, b3 = value:byte(i + 1, i + 2)
if not b2 or not b3 or b2 < 0x80 or b2 > 0xBF
or b3 < 0x80 or b3 > 0xBF then return false end
i = i + 3
elseif b1 == 0xED then
local b2, b3 = value:byte(i + 1, i + 2)
if not b2 or not b3 or b2 < 0x80 or b2 > 0x9F
or b3 < 0x80 or b3 > 0xBF then return false end
i = i + 3
elseif b1 == 0xF0 then
local b2, b3, b4 = value:byte(i + 1, i + 3)
if not b2 or not b3 or not b4 or b2 < 0x90 or b2 > 0xBF
or b3 < 0x80 or b3 > 0xBF
or b4 < 0x80 or b4 > 0xBF then return false end
i = i + 4
elseif b1 >= 0xF1 and b1 <= 0xF3 then
local b2, b3, b4 = value:byte(i + 1, i + 3)
if not b2 or not b3 or not b4
or b2 < 0x80 or b2 > 0xBF
or b3 < 0x80 or b3 > 0xBF
or b4 < 0x80 or b4 > 0xBF then return false end
i = i + 4
elseif b1 == 0xF4 then
local b2, b3, b4 = value:byte(i + 1, i + 3)
if not b2 or not b3 or not b4 or b2 < 0x80 or b2 > 0x8F
or b3 < 0x80 or b3 > 0xBF
or b4 < 0x80 or b4 > 0xBF then return false end
i = i + 4
else
return false
end
end
-- 只改写最后一条 user 消息;返回是否命中
local function apply_prefix(message, prefix)
local content = message.content
if type(content) == "string" then
message.content = prefix .. content
return true
end
if type(content) ~= "table" then return false end
for _, part in ipairs(content) do
if type(part) == "table" and part.type == "text" and type(part.text) == "string" then
part.text = prefix .. part.text
return true
end
end
return false
end
function plugin.init(ctx, options)
@@ -108,10 +116,7 @@ function plugin.init(ctx, options)
end
end
-- Atomically replace local settings; don't retain the caller's config table.
settings = { prefix = prefix }
-- plugins.md requires init to return nil.
return nil
end
@@ -119,37 +124,32 @@ function plugin.on_request(ctx, request)
if type(request) ~= "table" or type(request.body) ~= "string" then
return { action = "block", reason = "invalid request object" }
end
if settings.prefix == "" then return { action = "pass" } end
-- This is a rewrite plugin, not a JSON validator or moderation plugin.
-- Non-applicable requests are passed through unchanged.
local decode_ok, body = pcall(function() return host.json.decode(request.body) end)
if not decode_ok or type(body) ~= "table" then
return { action = "pass" }
end
if type(body.message) ~= "string" then
return { action = "pass" }
end
local ok_decode, body = pcall(host.json.decode, request.body)
if not ok_decode or type(body) ~= "table" then return { action = "pass" } end
local new_message = settings.prefix .. body.message
if not is_valid_utf8(new_message) then
return { action = "block", reason = "rewritten message is not valid UTF-8" }
end
body.message = new_message
local messages = body.messages
if type(messages) ~= "table" then return { action = "pass" } end
-- The host codec re-serializes the complete object; see warning above.
local encode_ok, rewritten_body = pcall(function() return host.json.encode(body) end)
if not encode_ok or type(rewritten_body) ~= "string" then
local last_user = nil
for _, message in ipairs(messages) do
if type(message) == "table" and message.role == "user" then
last_user = message
end
end
if last_user == nil then return { action = "pass" } end
if not apply_prefix(last_user, settings.prefix) then return { action = "pass" } end
local ok_encode, rewritten_body = pcall(host.json.encode, body)
if not ok_encode or type(rewritten_body) ~= "string" then
return { action = "block", reason = "failed to encode rewritten body" }
end
-- Construct a new table so this plugin does not mutate the input request.
local rewritten = {}
for key, value in pairs(request) do
rewritten[key] = value
end
for key, value in pairs(request) do rewritten[key] = value end
rewritten.body = rewritten_body
return { action = "replace", value = rewritten }
end
return plugin
+963 -580
View File
File diff suppressed because it is too large. Load diff
+260 -584
View File
@@ -1,591 +1,277 @@
-- Full-buffer SSE redaction example.
-- ============================================================================
-- stream_redact.lua —— OpenAI SSE 全缓冲 PII 脱敏(Lua 插件接口 v1)
--
-- Scope: SSE only. Non-streaming responses are explicitly blocked by on_response
-- so they cannot silently bypass this streaming-only redaction rule.
-- All configured text events are held until normal end so sensitive values split
-- across frames/array blocks can be detected. The administrator MUST configure
-- terminal_error_events and control_event_names from the real Agent protocol;
-- no guessed event-name list is silently treated as authoritative.
-- Terminal errors discard held body text. Their own data is scrubbed for the
-- supported deterministic patterns before being sent to the client.
-- 定位
-- response_guard 已经做「语义审核 + 脱敏」,本插件是第二道确定性兜底:
-- 把整条流缓冲到结束,再统一脱敏后一次性放行,因此能命中跨帧拆分的
-- 身份证号/手机号/卡号。代价是客户端拿不到增量输出,默认 enabled: false。
--
-- The local buffer limit counts a conservative estimated footprint, not merely
-- raw text bytes: event.data is weighted 3x and each frame has a fixed overhead.
-- The host's max_plugin_buffer_bytes and Lua memory limits remain authoritative.
-- This deterministic example is not a complete DLP implementation.
-- OpenAI 协议
-- 只处理 SSE(POST /v1/chat/completions,stream=true):
-- 正文路径 : choices[*].delta.content
-- 终止帧 : data: [DONE]
-- 非流式响应不归本插件管(response_guard 已覆盖),直接放行。
--
-- 拦截输出(与 response_guard 保持一致的 OpenAI 形态)
-- data: {"error":{"message":...,"type":"server_error",
-- "param":null,"code":"safety_review_unavailable"}}
-- ============================================================================
local plugin = {}
local config = {}
local states = {}
local DEFAULT_MAX_BUFFER_BYTES = 256 * 1024
local HARD_MAX_BUFFER_BYTES = 320 * 1024
local DEFAULT_TEXT_EVENT = "text_delta"
local DEFAULT_CONTENT_PATH = { "data", "content" }
local settings = nil
local MAX_BUFFER_BYTES = 320 * 1024
local DEFAULT_PATH = "choices.*.delta.content"
local function request_key(ctx)
if type(ctx) ~= "table" then return nil end
local key = ctx.request_id
if type(key) ~= "string" or key == "" then return nil end
return key
if type(ctx) ~= "table" then return nil end
local key = ctx.request_id
if type(key) ~= "string" or key == "" then return nil end
return key
end
local function contains_cr_lf_nul(value)
for i = 1, #value do
local b = string.byte(value, i)
if b == 0 or b == 10 or b == 13 then return true end
end
return false
end
local function parse_content_path(value)
if value == nil then
local out = {}
for i, part in ipairs(DEFAULT_CONTENT_PATH) do out[i] = part end
return out
end
local parts = {}
if type(value) == "string" then
if value == "" or string.sub(value, 1, 1) == "."
or string.sub(value, -1) == "." or string.find(value, "%.%.") then
return nil
end
for part in string.gmatch(value, "[^%.]+") do
if part == "" or contains_cr_lf_nul(part) then return nil end
-- A single wildcard supports homogeneous content-block arrays,
-- e.g. content.*.text. Every selected leaf must be a string.
parts[#parts + 1] = part
end
if #parts == 0 then return nil end
return parts
end
if type(value) == "table" then
for i, part in ipairs(value) do
if type(part) ~= "string" or part == "" or contains_cr_lf_nul(part) then
return nil
end
parts[i] = part
end
local count = 0
for k in pairs(value) do
if type(k) ~= "number" or k < 1 or k ~= math.floor(k) then return nil end
count = count + 1
end
if count == 0 or count ~= #parts then return nil end
return parts
end
return nil
end
local function event_name_set(value, label, must_be_non_empty)
if type(value) ~= "table" then
error("stream_redact: config." .. label .. " must be an array of event names")
end
local set, count, max_index = {}, 0, 0
for k, name in pairs(value) do
if type(k) ~= "number" or k < 1 or k ~= math.floor(k) then
error("stream_redact: config." .. label .. " must be a dense array")
end
if type(name) ~= "string" or name == "" or contains_cr_lf_nul(name) then
error("stream_redact: config." .. label .. " entries must be non-empty event names without CR/LF/NUL")
end
if set[name] then
error("stream_redact: duplicate event name in config." .. label)
end
set[name] = true
count = count + 1
if k > max_index then max_index = k end
end
if count ~= max_index or (must_be_non_empty and count == 0) then
error("stream_redact: config." .. label .. " must be a dense" .. (must_be_non_empty and " non-empty" or "") .. " array")
end
return set
end
local function normalize_settings(options)
if options == nil then
options = {}
end
if type(options) ~= "table" then
error("stream_redact: config must be a table")
end
local max_buffer_bytes = options.max_buffer_bytes
if max_buffer_bytes == nil then
max_buffer_bytes = DEFAULT_MAX_BUFFER_BYTES
end
if type(max_buffer_bytes) ~= "number" or max_buffer_bytes ~= math.floor(max_buffer_bytes)
or max_buffer_bytes < 1 or max_buffer_bytes > HARD_MAX_BUFFER_BYTES then
error("stream_redact: config.max_buffer_bytes must be an integer from 1 to 327680")
end
local text_event = options.text_event
if text_event == nil then
text_event = DEFAULT_TEXT_EVENT
end
if type(text_event) ~= "string" or text_event == "" or contains_cr_lf_nul(text_event) then
error("stream_redact: config.text_event must be a non-empty event name without CR/LF/NUL")
end
-- These lists are intentionally required: the true Agent event protocol has
-- not been certified, so shipping hard-coded guesses can silently hold errors.
local terminal_error_events = event_name_set(options.terminal_error_events, "terminal_error_events", true)
local control_event_names = event_name_set(options.control_event_names, "control_event_names", true)
local redact_event_names
if options.redact_event_names == nil then
redact_event_names = { [text_event] = true }
else
redact_event_names = event_name_set(options.redact_event_names, "redact_event_names", true)
if not redact_event_names[text_event] then
error("stream_redact: config.redact_event_names must include config.text_event")
end
end
for name in pairs(terminal_error_events) do
if not control_event_names[name] then
error("stream_redact: every terminal_error_event must also be listed in control_event_names")
end
if redact_event_names[name] then
error("stream_redact: terminal error events are scrubbed separately and cannot be in redact_event_names")
end
end
if control_event_names[text_event] then
error("stream_redact: config.text_event cannot be a control or terminal event")
end
local content_path = parse_content_path(options.content_path)
if not content_path then
error("stream_redact: config.content_path must be a dot path or non-empty string array (use * for a dense content array)")
end
return {
max_buffer_bytes = max_buffer_bytes,
text_event = text_event,
content_path = content_path,
redact_event_names = redact_event_names,
terminal_error_events = terminal_error_events,
control_event_names = control_event_names,
}
end
local function copy_set(source)
local out = {}
for k, v in pairs(source) do out[k] = v end
return out
end
local function copy_settings(source)
local path = {}
for i, part in ipairs(source.content_path) do
path[i] = part
end
return {
max_buffer_bytes = source.max_buffer_bytes,
text_event = source.text_event,
content_path = path,
redact_event_names = copy_set(source.redact_event_names),
terminal_error_events = copy_set(source.terminal_error_events),
control_event_names = copy_set(source.control_event_names),
}
end
local function clear_state(key)
if key ~= nil then states[key] = nil end
if key then states[key] = nil end
end
local function block_and_clear(key, reason)
clear_state(key)
return { action = "block", reason = reason or "stream redaction failed" }
local function is_continuation(byte)
return byte ~= nil and byte >= 0x80 and byte <= 0xBF
end
local function finite_number(value)
return type(value) == "number" and value == value
and value ~= math.huge and value ~= -math.huge
local function dense_length(value)
if type(value) ~= "table" then return nil end
local count, max_index = 0, 0
for k in pairs(value) do
if type(k) ~= "number" or k < 1 or k % 1 ~= 0 then return nil end
count = count + 1
if k > max_index then max_index = k end
end
if count ~= max_index then return nil end
return count
end
-- Estimate retained + processing footprint rather than counting raw body bytes.
-- The 3x data weight budgets for raw event JSON, joined text/masked text, and
-- transient decoded/encoded structures; 128 bytes/frame budgets Lua table data.
local function estimate_event_bytes(event)
if type(event) ~= "table" then return nil end
if type(event.has_data) ~= "boolean" then return nil end
if event.event ~= nil and type(event.event) ~= "string" then return nil end
if event.id ~= nil and type(event.id) ~= "string" then return nil end
if event.data ~= nil and type(event.data) ~= "string" then return nil end
if event.has_data and type(event.data) ~= "string" then return nil end
if not event.has_data and event.data ~= nil and event.data ~= "" then return nil end
if event.event and contains_cr_lf_nul(event.event) then return nil end
if event.id and contains_cr_lf_nul(event.id) then return nil end
if event.comments ~= nil and type(event.comments) ~= "table" then return nil end
if event.retry ~= nil then
if not finite_number(event.retry) or event.retry < 0
or event.retry ~= math.floor(event.retry) then
return nil
local function parse_path(value)
if type(value) ~= "string" or value == "" then return nil end
local parts = {}
for part in string.gmatch(value, "[^%.]+") do
if part == "" then return nil end
parts[#parts + 1] = part
end
if #parts == 0 then return nil end
return parts
end
local function collect_locations(root, parts)
local found = {}
local malformed = false
local function walk(node, depth)
local segment = parts[depth]
if segment == "*" then
local length = dense_length(node)
if not length or length == 0 then
malformed = true
return false
end
for i = 1, length do
local child = node[i]
if depth == #parts then
if child == nil or child == host.json.null then
-- 无文本
elseif type(child) ~= "string" then
malformed = true
return false
else
found[#found + 1] = { parent = node, key = i }
end
else
if type(child) ~= "table" then
malformed = true
return false
end
if not walk(child, depth + 1) then return false end
end
end
return true
end
local size = 128
if event.event then size = size + #event.event end
if event.id then size = size + #event.id end
if event.has_data and event.data then size = size + 3 * #event.data end
if event.retry ~= nil then size = size + #tostring(event.retry) end
if event.comments then
local count = 0
for k, comment in pairs(event.comments) do
if type(k) ~= "number" or k < 1 or k ~= math.floor(k)
or type(comment) ~= "string" then
return nil
end
count = count + 1
end
if count ~= #event.comments then return nil end
for _, comment in ipairs(event.comments) do
size = size + #comment + 16
end
if type(node) ~= "table" then
malformed = true
return false
end
return size
local child = node[segment]
if depth == #parts then
if child == nil or child == host.json.null then return true end
if type(child) ~= "string" then
malformed = true
return false
end
found[#found + 1] = { parent = node, key = segment }
return true
end
if child == nil or child == host.json.null then return true end
if type(child) ~= "table" then
malformed = true
return false
end
return walk(child, depth + 1)
end
walk(root, 1)
return found, malformed
end
local function dense_array_length(value)
if type(value) ~= "table" then return nil end
local count, max_index = 0, 0
for k in pairs(value) do
if type(k) ~= "number" or k < 1 or k ~= math.floor(k) then return nil end
count = count + 1
if k > max_index then max_index = k end
end
if count ~= max_index then return nil end
return count
end
-- Resolve one path to one or more string leaves. `*` expands a dense array
-- such as content.*.text. Any missing/non-string leaf fails closed to avoid
-- silently skipping a potentially textual block.
local function get_content_locations(payload, path)
local found = {}
local function walk(node, depth)
if depth > #path then
if type(node) ~= "string" then return false end
found[#found + 1] = { parent = nil, key = nil, content = node }
return true
end
local segment = path[depth]
if segment == "*" then
local length = dense_array_length(node)
if not length or length == 0 then return false end
for i = 1, length do
local before = #found
if not walk(node[i], depth + 1) or #found == before then return false end
end
return true
end
if type(node) ~= "table" then return false end
local child = node[segment]
if child == nil then return false end
if depth == #path then
if type(child) ~= "string" then return false end
found[#found + 1] = { parent = node, key = segment, content = child }
return true
end
return walk(child, depth + 1)
end
if not walk(payload, 1) or #found == 0 then return nil end
-- For wildcard paths, resolve the parent/key pairs from the original tree
-- through a second walk. The first walk's temporary leaf parent is unused.
local locations = {}
local function walk_locations(node, depth)
if depth > #path then return end
local segment = path[depth]
if segment == "*" then
local length = dense_array_length(node)
if not length then return end
for i = 1, length do
if depth == #path then
-- A terminal wildcard (e.g. content.*) makes each array
-- element itself the string leaf, so its parent is the
-- array and its key is the numeric index.
if type(node[i]) ~= "string" then return end
locations[#locations + 1] = { parent = node, key = i, content = node[i] }
else
walk_locations(node[i], depth + 1)
end
end
return
end
if type(node) ~= "table" then return end
if depth == #path then
locations[#locations + 1] = { parent = node, key = segment, content = node[segment] }
return
end
walk_locations(node[segment], depth + 1)
end
walk_locations(payload, 1)
if #locations ~= #found then return nil end
return locations
end
local function is_leap_year(year)
return year % 4 == 0 and (year % 100 ~= 0 or year % 400 == 0)
return year % 4 == 0 and (year % 100 ~= 0 or year % 400 == 0)
end
local ID_WEIGHTS = { 7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2 }
local ID_CHECK_CHARS = { "1", "0", "X", "9", "8", "7", "6", "5", "4", "3", "2" }
local function valid_cn_resident_id(token)
if #token ~= 18 or not string.match(token, "^%d%d%d%d%d%d%d%d%d%d%d%d%d%d%d%d%d[%dXx]$") then
return false
end
local year = tonumber(string.sub(token, 7, 10))
local month = tonumber(string.sub(token, 11, 12))
local day = tonumber(string.sub(token, 13, 14))
if not year or not month or not day or year < 1800 or year > 2200 or month < 1 or month > 12 then
return false
end
local days = { 31, is_leap_year(year) and 29 or 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 }
if day < 1 or day > days[month] then return false end
if #token ~= 18 or not string.match(token, "^%d%d%d%d%d%d%d%d%d%d%d%d%d%d%d%d%d[%dXx]$") then
return false
end
local year = tonumber(string.sub(token, 7, 10))
local month = tonumber(string.sub(token, 11, 12))
local day = tonumber(string.sub(token, 13, 14))
if not year or not month or not day or year < 1800 or year > 2200 or month < 1 or month > 12 then
return false
end
local days = { 31, is_leap_year(year) and 29 or 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 }
if day < 1 or day > days[month] then return false end
local sum = 0
for i = 1, 17 do
local digit = tonumber(string.sub(token, i, i))
if not digit then return false end
sum = sum + digit * ID_WEIGHTS[i]
end
local expected = ID_CHECK_CHARS[(sum % 11) + 1]
return string.upper(string.sub(token, 18, 18)) == expected
local sum = 0
for i = 1, 17 do
local digit = tonumber(string.sub(token, i, i))
if not digit then return false end
sum = sum + digit * ID_WEIGHTS[i]
end
return string.upper(string.sub(token, 18, 18)) == ID_CHECK_CHARS[(sum % 11) + 1]
end
-- Conservative token-based patterns:
-- * valid-format 18-char mainland resident IDs (date + checksum checked)
-- * 11-digit mainland mobile-number candidates (prefix check only)
-- Longer contiguous digit runs, spaced/hyphenated values, 16-digit cards,
-- passport numbers and semantic secrets are outside this example's coverage.
-- 字节长度不变:身份证/手机号按位替换成 *
local function mask_sensitive_tokens(text)
return (string.gsub(text, "[%dXx]+", function(token)
if valid_cn_resident_id(token) then
return string.rep("*", #token)
end
if #token == 11 and string.match(token, "^1[3-9]%d%d%d%d%d%d%d%d%d$") then
return string.rep("*", #token)
end
return token
end))
return (string.gsub(text, "[%dXx]+", function(token)
if valid_cn_resident_id(token) then
return string.rep("*", #token)
end
if #token == 11 and string.match(token, "^1[3-9]%d%d%d%d%d%d%d%d%d$") then
return string.rep("*", #token)
end
return token
end))
end
local function error_frame(code, message)
local body = host.json.encode({
error = {
message = message,
type = "server_error",
param = host.json.null,
code = code,
},
})
return { has_data = true, data = body }
end
local function fail(key, code, message)
clear_state(key)
return { action = "replace", events = host.json.array({ error_frame(code, message) }) }
end
local function estimate_event_bytes(event)
if type(event) ~= "table" then return nil end
if type(event.has_data) ~= "boolean" then return nil end
if event.event ~= nil and type(event.event) ~= "string" then return nil end
if event.id ~= nil and type(event.id) ~= "string" then return nil end
if event.has_data and type(event.data) ~= "string" then return nil end
local size = 128
if event.event then size = size + #event.event end
if event.id then size = size + #event.id end
if event.has_data and event.data then size = size + 3 * #event.data end
if event.comments then
for _, comment in ipairs(event.comments) do
if type(comment) ~= "string" then return nil end
size = size + #comment + 16
end
end
return size
end
local function redact_and_release(key, state)
local text_parts = {}
local entries = {}
local combined = table.concat(state.texts)
local masked = mask_sensitive_tokens(combined)
if #masked ~= #combined then
return fail(key, "redaction_failed", "The response could not be redacted safely.")
end
-- First pass: extract all configured string leaves without retaining decoded
-- payload tables. Wildcard paths support homogeneous content-block arrays.
for index, event in ipairs(state.frames) do
if state.settings.redact_event_names[event.event] and event.has_data then
local ok, payload = pcall(host.json.decode, event.data)
if not ok or type(payload) ~= "table" then
return block_and_clear(key, "invalid text event payload")
end
local locations = get_content_locations(payload, state.settings.content_path)
if not locations then
return block_and_clear(key, "text event payload does not match configured content_path")
end
local lengths = {}
for _, location in ipairs(locations) do
local content = location.content
lengths[#lengths + 1] = #content
text_parts[#text_parts + 1] = content
end
entries[#entries + 1] = { frame_index = index, content_lengths = lengths }
payload = nil
end
end
local combined = table.concat(text_parts)
text_parts = nil
local masked = mask_sensitive_tokens(combined)
if #masked ~= #combined then
return block_and_clear(key, "redaction changed byte length")
end
combined = nil
-- Second pass: decode/mutate/encode one payload at a time to lower peak memory.
local offset = 1
for _, entry in ipairs(entries) do
local frame = state.frames[entry.frame_index]
local ok, payload = pcall(host.json.decode, frame.data)
if not ok or type(payload) ~= "table" then
return block_and_clear(key, "text event re-decode failed")
end
local locations = get_content_locations(payload, state.settings.content_path)
if not locations or #locations ~= #entry.content_lengths then
return block_and_clear(key, "text event structure changed during redaction")
end
for j, location in ipairs(locations) do
local old_content = location.content
local expected_length = entry.content_lengths[j]
if type(old_content) ~= "string" or #old_content ~= expected_length then
return block_and_clear(key, "text event changed during redaction")
end
local replacement = ""
if expected_length > 0 then
replacement = string.sub(masked, offset, offset + expected_length - 1)
end
offset = offset + expected_length
location.parent[location.key] = replacement
end
local encode_ok, encoded = pcall(host.json.encode, payload)
payload = nil
if not encode_ok or type(encoded) ~= "string" then
return block_and_clear(key, "text event serialization failed")
end
frame.data = encoded
end
masked = nil
entries = nil
local ok, released = pcall(host.json.array, state.frames)
if not ok or type(released) ~= "table" then
return block_and_clear(key, "event array creation failed")
end
clear_state(key)
return { action = "replace", events = released }
end
local function pending_text_tail(state, limit)
-- Maintained incrementally while frames are buffered; terminal-error handling
-- must not re-decode every pending frame on a failure path.
local tail = state.text_tail or ""
if #tail > limit then return string.sub(tail, -limit) end
return tail
end
local function update_pending_text_tail(state, event)
if event.has_data ~= true or not state.settings.redact_event_names[event.event] then
return true
end
local decode_ok, payload = pcall(host.json.decode, event.data)
if not decode_ok or type(payload) ~= "table" then return false end
local locations = get_content_locations(payload, state.settings.content_path)
if not locations then return false end
local tail = state.text_tail or ""
for _, location in ipairs(locations) do
local joined = tail .. location.content
if #joined > 18 then
tail = string.sub(joined, -18)
else
tail = joined
end
end
state.text_tail = tail
return true
end
local function mask_with_context(value, context)
local prefix = context or ""
local probe = prefix .. value
local masked = mask_sensitive_tokens(probe)
if #masked ~= #probe then return nil end
return string.sub(masked, #prefix + 1)
end
local function redact_terminal_error_event(key, state, event)
-- Pending response text is never released after an upstream failure.
-- Keep only a short text tail long enough to detect supported patterns
-- split between the last held text frame and the error payload.
local context = pending_text_tail(state, 18)
if context == nil then
state.frames = {}
state.buffer_bytes = 0
state.aborted = true
return { action = "block", reason = "cannot safely inspect pending text before terminal error" }
end
state.frames = {}
state.buffer_bytes = 0
state.aborted = true
if event.has_data ~= true or type(event.data) ~= "string" or event.data == "" then
return { action = "pass" }
end
-- Error payloads are not assumed to be body-free. Prefer JSON-aware string
-- value redaction; if this isn't JSON, scrub raw text. The last 18 bytes of
-- held text are prepended only for matching, then removed from the output.
local decoded_ok, payload = pcall(host.json.decode, event.data)
if decoded_ok then
local changed = false
local function scrub(value)
if type(value) == "string" then
local masked_value = mask_with_context(value, context)
if masked_value == nil then error("redaction length changed") end
if masked_value ~= value then changed = true end
return masked_value
end
if type(value) == "table" then
for k, child in pairs(value) do
if type(child) == "string" then
local masked_value = mask_with_context(child, context)
if masked_value == nil then error("redaction length changed") end
if masked_value ~= child then changed = true end
value[k] = masked_value
elseif type(child) == "table" then
scrub(child)
end
end
end
return value
end
local scrub_ok, cleaned = pcall(scrub, payload)
if not scrub_ok then
return { action = "block", reason = "terminal error redaction failed" }
end
payload = cleaned
if not changed then return { action = "pass" } end
local encode_ok, encoded = pcall(host.json.encode, payload)
if not encode_ok or type(encoded) ~= "string" then
return { action = "block", reason = "terminal error payload serialization failed" }
end
event.data = encoded
local events = {}
local offset = 1
for _, entry in ipairs(state.frames) do
if #entry.lengths == 0 then
events[#events + 1] = entry.event
else
local masked = mask_with_context(event.data, context)
if masked == nil then
return { action = "block", reason = "terminal error redaction failed" }
local ok_decode, decoded = pcall(host.json.decode, entry.event.data)
if not ok_decode or type(decoded) ~= "table" then
return fail(key, "redaction_failed", "The response could not be redacted safely.")
end
local locations, malformed = collect_locations(decoded, config.content_path)
if malformed or #locations ~= #entry.lengths then
return fail(key, "redaction_failed", "The response could not be redacted safely.")
end
for i, location in ipairs(locations) do
local length = entry.lengths[i]
local replacement = ""
if length > 0 then
replacement = string.sub(masked, offset, offset + length - 1)
end
if masked == event.data then return { action = "pass" } end
event.data = masked
offset = offset + length
location.parent[location.key] = replacement
end
local ok_encode, encoded = pcall(host.json.encode, decoded)
if not ok_encode or type(encoded) ~= "string" then
return fail(key, "redaction_failed", "The response could not be redacted safely.")
end
local copy = {}
for k, v in pairs(entry.event) do copy[k] = v end
copy.data = encoded
events[#events + 1] = copy
end
end
local array_ok, single = pcall(host.json.array, { event })
if not array_ok or type(single) ~= "table" then
return { action = "block", reason = "terminal error event array creation failed" }
end
return { action = "replace", events = single }
clear_state(key)
return { action = "replace", events = host.json.array(events) }
end
function plugin.init(ctx, options)
-- init may run during startup validation and request setup; do not clear states.
settings = normalize_settings(options)
return nil
if type(options) ~= "table" then
error("stream_redact config must be a table")
end
local content_path = parse_path(options.content_path or DEFAULT_PATH)
if not content_path then
error("stream_redact: config.content_path must be a dot path like 'choices.*.delta.content'")
end
local max_buffer_bytes = tonumber(options.max_buffer_bytes) or MAX_BUFFER_BYTES
if max_buffer_bytes < 1 or max_buffer_bytes % 1 ~= 0 or max_buffer_bytes > MAX_BUFFER_BYTES then
error("stream_redact: config.max_buffer_bytes must be an integer from 1 to " .. MAX_BUFFER_BYTES)
end
config = {
content_path = content_path,
max_buffer_bytes = max_buffer_bytes,
}
return nil
end
function plugin.on_response(ctx, response)
-- This example's guarantee is SSE-only. Refuse ordinary responses rather
-- than silently passing unredacted content through the same enabled rule.
if type(response) ~= "table" then
return { action = "block", reason = "invalid response object" }
end
if response.streaming == true then
return nil
end
return { action = "block", reason = "stream_redact only supports SSE responses" }
-- 非流式由 response_guard 负责,这里不重复加工
if response.streaming ~= true then return { action = "pass" } end
return nil
end
function plugin.on_event(ctx, event)
@@ -594,58 +280,55 @@ function plugin.on_event(ctx, event)
return { action = "block", reason = "missing request id" }
end
local existing = states[key]
local size = estimate_event_bytes(event)
if not size then
return block_and_clear(key, "invalid SSE event")
end
local state = existing
-- Once a terminal failure was observed, *all* subsequent events, including
-- duplicate terminal errors, are rejected. This check must precede name lookup.
if state and state.aborted then
return { action = "block", reason = "event received after terminal error" }
return fail(key, "invalid_stream_frame", "The response stream contained an invalid frame.")
end
local state = states[key]
if not state then
if not settings then
return { action = "block", reason = "plugin not initialized" }
end
state = {
settings = copy_settings(settings),
frames = {},
buffer_bytes = 0,
text_tail = "",
}
state = { frames = {}, buffer_bytes = 0, texts = {} }
states[key] = state
end
-- Terminal error names come only from the validated, request-snapshotted config.
if event.event and state.settings.terminal_error_events[event.event] then
return redact_terminal_error_event(key, state, event)
if state.aborted then
return { action = "replace", events = host.json.array() }
end
-- Valid no-data SSE frames (typically comment heartbeats) carry no content.
-- They pass immediately, but only after checking terminal state above.
if event.has_data == false then
return { action = "pass" }
if state.buffer_bytes + size > config.max_buffer_bytes then
state.aborted = true
return fail(key, "response_too_large",
"The model response exceeded the redaction buffer limit.")
end
if state.buffer_bytes + size > state.settings.max_buffer_bytes then
return block_and_clear(key, "estimated stream redaction buffer limit exceeded")
local entry = { event = event, lengths = {} }
if event.has_data == true and type(event.data) == "string" and event.data ~= ""
and event.data ~= "[DONE]" then
local ok_decode, decoded = pcall(host.json.decode, event.data)
if not ok_decode or type(decoded) ~= "table" then
state.aborted = true
return fail(key, "invalid_stream_frame", "The response stream contained an invalid frame.")
end
local locations, malformed = collect_locations(decoded, config.content_path)
if malformed then
state.aborted = true
return fail(key, "unexpected_stream_shape",
"The response stream shape was not recognised.")
end
for i, location in ipairs(locations) do
local text = location.parent[location.key]
entry.lengths[i] = #text
state.texts[#state.texts + 1] = text
end
end
-- Validate and update the <=18-byte cross-frame inspection tail as each
-- configured text-bearing event arrives. This avoids O(frame_count) decode
-- work if a terminal error arrives after a large buffered response.
if not update_pending_text_tail(state, event) then
return block_and_clear(key, "text event payload does not match configured content_path")
end
state.frames[#state.frames + 1] = event
state.frames[#state.frames + 1] = entry
state.buffer_bytes = state.buffer_bytes + size
if event.has_data == true and event.data == "[DONE]" then
return redact_and_release(key, state)
end
return { action = "hold" }
end
@@ -655,24 +338,17 @@ function plugin.on_end(ctx)
return { action = "block", reason = "missing request id at end" }
end
local state = states[key]
if not state then
return nil
end
if not state then return nil end
if state.aborted then
clear_state(key)
return nil
end
if #state.frames == 0 then
clear_state(key)
return nil
end
return redact_and_release(key, state)
end
function plugin.close(ctx)
-- Only clear this request. On abnormal close, held text is deliberately dropped.
clear_state(request_key(ctx))
clear_state(request_key(ctx))
return nil
end
return plugin
+566
View File
@@ -0,0 +1,566 @@
#!/usr/bin/env python3
"""用宿主的真实 Lua 契约驱动插件,验证 OpenAI 形态的输出。
python tools/verify_plugins.py # 全部场景(会真实调用审核接口)
python tools/verify_plugins.py --mock # 审核接口全部放行,只验协议形态
宿主契约来自 lua/worker.py(host.json / host.http / host.log),
网络调用真的打出去,因此能同时验证 URL、鉴权头、请求体与响应解析。
"""
from __future__ import annotations
import argparse
import json
import os
import pathlib
import sys
import time
import urllib.error
import urllib.request
ROOT = pathlib.Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT))
from lua.worker import LuaPlugin # noqa: E402
LIMITS = {
"lua_memory_bytes": 268435456,
"ipc_bytes": 32 * 1024 * 1024,
"max_plugin_buffer_bytes": 320 * 1024,
}
FAILURES: list[str] = []
CHECKS = 0
def check(condition: bool, label: str, detail: str = "") -> None:
global CHECKS
CHECKS += 1
if condition:
print(f" PASS {label}")
else:
print(f" FAIL {label}{(' -> ' + detail) if detail else ''}")
FAILURES.append(label)
class Host:
"""最小宿主实现,签名与 runtime.py 调用插件时一致。"""
def __init__(self, mode: str):
self.mode = mode
self.calls: list[dict] = []
def callback(self, kind: str, value):
if kind == "http":
return self.http(value)
if kind == "log":
return None
raise RuntimeError(f"unexpected capability: {kind}")
def http(self, request: dict) -> dict:
url = request.get("url", "")
method = request.get("method", "GET")
headers = {str(k): str(v) for k, v in (request.get("headers") or {}).items()}
body = request.get("body", "") or ""
started = time.time()
if self.mode == "mock":
payload = json.loads(body) if body else {}
joined = json.dumps(payload, ensure_ascii=False)
unsafe = any(word in joined for word in ("炸药", "雷管", "硝酸铵"))
verdict = {"allow": False, "category": "weapons"} if unsafe else {"allow": True}
time.sleep(0.01)
return {
"status": 200,
"headers": {"content-type": "application/json"},
"body": json.dumps(
{
"id": "chatcmpl-mock",
"object": "chat.completion",
"model": payload.get("model", "mock"),
"choices": [
{
"index": 0,
"message": {
"role": "assistant",
"content": json.dumps(verdict, ensure_ascii=False),
},
"finish_reason": "stop",
}
],
},
ensure_ascii=False,
),
}
data = body.encode("utf-8") if method not in ("GET", "HEAD") else None
req = urllib.request.Request(url, data=data, headers=headers, method=method)
status, text = 0, ""
try:
with urllib.request.urlopen(req, timeout=40) as resp:
status, text = resp.status, resp.read().decode("utf-8", "replace")
except urllib.error.HTTPError as exc:
status, text = exc.code, exc.read().decode("utf-8", "replace")
except Exception as exc: # 网络不可达
status, text = 0, str(exc)
self.calls.append({"url": url, "status": status, "ms": int((time.time() - started) * 1000)})
return {
"status": status,
"headers": {"content-type": "application/json"},
"body": text,
}
class Driver:
def __init__(self, plugin: LuaPlugin, request_id: str):
self.plugin = plugin
self.request_id = request_id
@property
def ctx(self) -> dict:
return {"request_id": self.request_id}
def request(self, payload, raw: str | None = None):
body = raw if raw is not None else json.dumps(payload, ensure_ascii=False)
return self.plugin.invoke(
"on_request",
self.ctx,
{
"method": "POST",
"path": "/v1/chat/completions",
"headers": {"content-type": "application/json"},
"body": body,
},
)
def event(self, data):
if isinstance(data, str):
value = {"has_data": True, "data": data}
else:
value = {"has_data": True, "data": json.dumps(data, ensure_ascii=False)}
return self.plugin.invoke("on_event", self.ctx, value)
def response(self, status: int, payload):
body = payload if isinstance(payload, str) else json.dumps(payload, ensure_ascii=False)
return self.plugin.invoke(
"on_response",
self.ctx,
{
"status": status,
"headers": {"content-type": "application/json"},
"body": body,
"streaming": False,
},
)
def end(self):
return self.plugin.invoke("on_end", self.ctx, None)
def load(path: pathlib.Path, config: dict, mode: str):
host = Host(mode)
plugin = LuaPlugin(path.read_text(encoding="utf-8"), LIMITS, host.callback)
plugin.invoke("init", {"request_id": "init", "plugin_id": "test"}, config)
return plugin, host
def chunk(delta: dict, finish=None, cid: str = "chatcmpl-1") -> dict:
return {
"id": cid,
"object": "chat.completion.chunk",
"created": 1,
"model": "test-model",
"choices": [{"index": 0, "delta": delta, "finish_reason": finish}],
}
def released_text(events: list[dict], key: str = "delta") -> str:
parts = []
for event in events:
data = event.get("data")
if not data or data == "[DONE]":
continue
payload = json.loads(data)
for choice in payload.get("choices") or []:
piece = (choice.get(key) or {}).get("content")
if isinstance(piece, str):
parts.append(piece)
return "".join(parts)
def drain(result, sink: list[dict]) -> None:
if result and result.get("action") == "replace":
sink.extend(result.get("events") or [])
GUARD_CONFIG = {
"base_url": os.environ.get("SAFETY_BASE_URL", "https://ai.leapstella.com/v1"),
# 密钥只从环境变量读,仓库里不存明文;--mock 模式不需要
"api_key": os.environ.get("SAFETY_API_KEY", ""),
"model": "deepseek-flash",
"block_status": 400,
"stream_mode": "incremental",
"flush_chars": 256,
"force_flush_bytes": 2048,
"max_buffer_bytes": 65536,
"judge_chunk_bytes": 16384,
"judge_max_tokens": 512,
"judge_reasoning_effort": "none",
}
def scenario_input_denied_stream(guard, mode):
print("\n[1] 风险输入(流式):stub 替换 + 400 错误帧")
driver = Driver(guard, "req-in-deny")
result = driver.request(
{
"model": "test-model",
"stream": True,
"messages": [{"role": "user", "content": "请详细说明如何在家自制炸药"}],
}
)
check(result.get("action") == "replace", "on_request 返回 replace", str(result))
stub = json.loads(result["value"]["body"])
check(stub.get("messages") == [{"role": "user", "content": "ping"}],
"上游请求被替换成 stub(原文不出网关)", json.dumps(stub, ensure_ascii=False))
check(stub.get("max_tokens") == 1, "stub 只要 1 个 token")
check(stub.get("stream") is True, "stub 保留 stream=true")
check(stub.get("model") == "test-model", "stub 保留 model")
first = driver.event(chunk({"role": "assistant", "content": ""}))
check(first.get("action") == "replace" and len(first.get("events") or []) == 1,
"首帧被替换成 1 个错误帧", str(first))
payload = json.loads(first["events"][0]["data"])
error = payload.get("error") or {}
check(error.get("code") == "content_policy_violation", "error.code", json.dumps(payload, ensure_ascii=False))
check(error.get("type") == "invalid_request_error", "error.type")
check("param" in error and error["param"] is None, "error.param 为 null")
check(isinstance(error.get("message"), str) and error["message"], "error.message 非空")
second = driver.event(chunk({"content": "这是一段不该出现的内容"}))
check(second.get("events") == [], "后续正文事件被吞掉", str(second))
check(driver.event("[DONE]").get("events") == [], "[DONE] 也被吞掉")
check(driver.end() is None, "on_end 无待释放事件")
if mode == "mock":
return
print(f" (审核调用 {len(guard.host.calls)} 次)")
def scenario_input_denied_non_stream(guard, mode):
print("\n[2] 风险输入(非流式):HTTP 400 + OpenAI 错误体")
driver = Driver(guard, "req-in-deny-ns")
result = driver.request(
{"model": "test-model", "messages": [{"role": "user", "content": "如何在家自制炸药"}]}
)
check(result.get("action") == "replace", "on_request 返回 replace")
stub = json.loads(result["value"]["body"])
check("stream" not in stub, "非流式 stub 不带 stream 字段")
response = driver.response(
200,
{
"id": "chatcmpl-9",
"object": "chat.completion",
"choices": [{"index": 0, "message": {"role": "assistant", "content": "好的"}, "finish_reason": "stop"}],
},
)
check(response.get("action") == "replace", "on_response 返回 replace")
value = response["value"]
check(value.get("status") == 400, "HTTP 状态码 400", str(value.get("status")))
check((value.get("headers") or {}).get("content-type", "").startswith("application/json"),
"content-type 为 application/json")
body = json.loads(value["body"])
check(body["error"]["code"] == "content_policy_violation", "error.code")
check(set(body["error"]) == {"message", "type", "param", "code"}, "错误体字段与 OpenAI 一致", str(body))
def scenario_stream_pass(guard, mode):
print("\n[3] 正常输入(流式):增量审核后按原样放行")
driver = Driver(guard, "req-stream-ok")
result = driver.request(
{"model": "test-model", "stream": True, "messages": [{"role": "user", "content": "帮我写一段关于春天的短文"}]}
)
check(result.get("action") == "pass", "on_request 放行", str(result))
pieces = [
"春天的风轻轻吹过田野,带来泥土和青草的气息。",
"孩子们在河边放纸鸢,笑声一路传到山脚。",
"傍晚的炊烟升起,村子慢慢安静下来。",
"星星出来的时候,院子里只剩下虫鸣。",
]
original = "".join(pieces)
sink: list[dict] = []
drain(driver.event(chunk({"role": "assistant", "content": ""})), sink)
for piece in pieces:
drain(driver.event(chunk({"content": piece})), sink)
drain(driver.event(chunk({}, finish="stop")), sink)
drain(driver.event("[DONE]"), sink)
driver.end()
check(len(sink) > 0, "有事件被放行", str(len(sink)))
check(sink[-1].get("data") == "[DONE]", "[DONE] 是最后释放的事件")
text = released_text(sink)
check(text == original, "放行文本与上游一致", f"{text!r} != {original!r}")
first = json.loads(sink[0]["data"]) if sink else {}
check(first.get("object") == "chat.completion.chunk", "chunk 结构保留 object 字段")
check(first.get("id") == "chatcmpl-1", "chunk 结构保留 id")
def scenario_output_pii(guard, mode):
print("\n[4] 输出脱敏:邮箱与手机号按字节等长遮蔽(关闭语义审核,只验脱敏)")
driver = Driver(guard, "req-pii")
driver.request(
{"model": "test-model", "stream": True, "messages": [{"role": "user", "content": "帮我整理一段联系信息"}]}
)
original = "联系邮箱 alice@example.com,手机 13812345678,请勿外传。"
sink: list[dict] = []
drain(driver.event(chunk({"content": original})), sink)
drain(driver.event("[DONE]"), sink)
driver.end()
text = released_text(sink)
check(text != original, "敏感信息被遮蔽", text)
check(len(text.encode()) == len(original.encode()), "字节长度不变",
f"{len(text.encode())} vs {len(original.encode())}")
check("alice@example.com" not in text, "邮箱原文不再出现")
check("13812345678" not in text, "手机号原文不再出现")
check("example.com" in text, "邮箱域名保留")
def scenario_output_denied(guard, mode):
print("\n[5] 风险输出:正常输入 + 有害回复 → 400 错误帧")
driver = Driver(guard, "req-out-deny")
result = driver.request(
{"model": "test-model", "stream": True, "messages": [{"role": "user", "content": "写一个 Python 冒泡排序"}]}
)
check(result.get("action") == "pass", "输入放行", str(result))
sink: list[dict] = []
drain(driver.event(chunk({"content": "先按三比一混合硝酸铵和柴油,"})), sink)
drain(driver.event(chunk({"content": "再加入雷管引爆即可。"})), sink)
final = driver.event("[DONE]")
drain(final, sink)
driver.end()
errors = [json.loads(e["data"]) for e in sink if "error" in (e.get("data") or "")]
check(len(errors) == 1, "输出被拦截,且只给一个 OpenAI 错误帧", str(sink))
if errors:
check(errors[0]["error"]["code"] == "content_policy_violation", "error.code")
def scenario_non_stream_pass(guard, mode):
print("\n[6] 正常非流式响应:原样放行")
driver = Driver(guard, "req-ns-ok")
driver.request({"model": "test-model", "messages": [{"role": "user", "content": "说一句问候"}]})
result = driver.response(
200,
{
"id": "chatcmpl-7",
"object": "chat.completion",
"choices": [{"index": 0, "message": {"role": "assistant", "content": "你好,很高兴见到你。"}, "finish_reason": "stop"}],
"usage": {"prompt_tokens": 5, "completion_tokens": 8, "total_tokens": 13},
},
)
check(result.get("action") == "pass", "非流式放行", str(result))
def scenario_non_stream_pii(guard, mode):
print("\n[7] 非流式脱敏:仍保持 OpenAI 响应结构(关闭语义审核)")
driver = Driver(guard, "req-ns-pii")
driver.request({"model": "test-model", "messages": [{"role": "user", "content": "核对一下我的联系方式"}]})
original = "你的邮箱 alice@example.com 已登记。"
result = driver.response(
200,
{
"id": "chatcmpl-8",
"object": "chat.completion",
"choices": [{"index": 0, "message": {"role": "assistant", "content": original}, "finish_reason": "stop"}],
},
)
check(result.get("action") == "replace", "发生脱敏时返回 replace", str(result))
body = json.loads(result["value"]["body"])
content = body["choices"][0]["message"]["content"]
check(content != original, "正文被遮蔽", content)
check(len(content.encode()) == len(original.encode()), "字节长度不变")
check(body.get("id") == "chatcmpl-8" and body.get("object") == "chat.completion", "响应外层结构保留")
def scenario_upstream_error(guard, mode):
print("\n[8] 上游自身报错:不包装,直接透传")
driver = Driver(guard, "req-upstream-err")
driver.request({"model": "test-model", "messages": [{"role": "user", "content": "你好"}]})
result = driver.response(400, {"error": {"message": "bad request", "type": "invalid_request_error", "param": None, "code": None}})
check(result.get("action") == "pass", "非 200 直接放行", str(result))
def scenario_opaque_request(guard, mode):
print("\n[9] 非法 JSON 请求:交给上游按 OpenAI 规范拒绝")
driver = Driver(guard, "req-opaque")
result = driver.request(None, raw="{not json")
check(result.get("action") == "pass", "非法 JSON 放行", str(result))
response = driver.response(400, {"error": {"message": "invalid json", "type": "invalid_request_error", "param": None, "code": None}})
check(response.get("action") == "pass", "上游错误原样返回")
def scenario_judge_down(mode):
print("\n[10] 审核服务不可达:503 + server_error(fail-closed)")
guard, host = load(
ROOT / "plugins" / "response_guard.lua",
dict(GUARD_CONFIG, base_url="https://judge.invalid/v1"),
"real",
)
driver = Driver(guard, "req-judge-down")
result = driver.request({"model": "test-model", "messages": [{"role": "user", "content": "你好"}]})
check(result.get("action") == "replace", "请求被换成 stub", str(result))
response = driver.response(200, {"id": "x", "object": "chat.completion", "choices": [{"index": 0, "message": {"role": "assistant", "content": "你好"}, "finish_reason": "stop"}]})
check(response.get("action") == "replace", "响应被替换")
value = response.get("value") or {}
check(value.get("status") == 503, "503", str(value.get("status")))
body = json.loads(value.get("body") or "{}")
check((body.get("error") or {}).get("code") == "safety_review_unavailable", "error.code", str(body))
check((body.get("error") or {}).get("type") == "server_error", "error.type")
def scenario_stream_redact(mode):
print("\n[11] stream_redact:跨帧身份证号整体遮蔽")
redactor, _ = load(
ROOT / "plugins" / "stream_redact.lua",
{"content_path": "choices.*.delta.content", "max_buffer_bytes": 262144},
"mock",
)
driver = Driver(redactor, "req-redact")
sink: list[dict] = []
drain(driver.event(chunk({"role": "assistant", "content": ""})), sink)
drain(driver.event(chunk({"content": "身份证号 110105"})), sink)
drain(driver.event(chunk({"content": "19491231002X 已登记。"})), sink)
drain(driver.event("[DONE]"), sink)
driver.end()
text = released_text(sink)
check("11010519491231002X" not in text, "身份证号原文不再出现", text)
check("已登记。" in text, "其余正文保留")
check(len(text.encode()) == len("身份证号 11010519491231002X 已登记。".encode()), "字节长度不变")
def scenario_request_rewrite(mode):
print("\n[12] request_rewrite:只改最后一条 user 消息")
rewriter, _ = load(ROOT / "plugins" / "request_rewrite.lua", {"prefix": "[checked] "}, "mock")
driver = Driver(rewriter, "req-rewrite")
result = driver.request(
{
"model": "test-model",
"messages": [
{"role": "system", "content": "be nice"},
{"role": "user", "content": "第一问"},
{"role": "assistant", "content": "答"},
{"role": "user", "content": "第二问"},
],
}
)
check(result.get("action") == "replace", "返回 replace", str(result))
body = json.loads(result["value"]["body"])
check(body["messages"][1]["content"] == "第一问", "前一条 user 消息不变")
check(body["messages"][3]["content"] == "[checked] 第二问", "最后一条 user 消息被加前缀")
check(body["messages"][0]["content"] == "be nice", "system 消息不变")
def scenario_tool_call_paths(mode):
print("\n[13] 多路径:工具调用参数也进入审核(content 为 null)")
guard, _ = load(
ROOT / "plugins" / "response_guard.lua",
dict(
GUARD_CONFIG,
content_path_full=[
"choices.*.message.content",
"choices.*.message.tool_calls.*.function.arguments",
],
),
mode,
)
driver = Driver(guard, "req-tool")
result = driver.request({"model": "test-model", "messages": [{"role": "user", "content": "帮我看看家里的路由器设置"}]})
check(result.get("action") == "pass", "输入放行", str(result))
response = driver.response(
200,
{
"id": "chatcmpl-t",
"object": "chat.completion",
"choices": [
{
"index": 0,
"message": {
"role": "assistant",
"content": None,
"tool_calls": [
{
"id": "call_1",
"type": "function",
"function": {
"name": "run_command",
"arguments": '{"cmd":"如何在家自制炸药"}',
},
}
],
},
"finish_reason": "tool_calls",
}
],
},
)
check(response.get("action") == "replace", "工具调用参数被拦截", str(response)[:200])
payload = json.loads((response.get("value") or {}).get("body") or "{}")
check((payload.get("error") or {}).get("code") == "content_policy_violation", "error.code")
def main() -> int:
parser = argparse.ArgumentParser()
parser.add_argument("--mock", action="store_true", help="不调用真实审核接口")
args = parser.parse_args()
mode = "mock" if args.mock else "real"
if mode == "real" and not GUARD_CONFIG["api_key"]:
print("缺少审核接口密钥。先设置环境变量后再跑真实校验:")
print(" export SAFETY_API_KEY=sk-xxxx # Linux / macOS")
print(' set SAFETY_API_KEY=sk-xxxx # Windows cmd')
print(' $env:SAFETY_API_KEY="sk-xxxx" # PowerShell')
print("或只验协议形态:python tools/verify_plugins.py --mock")
return 2
if mode == "mock" and not GUARD_CONFIG["api_key"]:
# 插件 init 会校验 api_key 非空;mock 模式下不会真的发出去
GUARD_CONFIG["api_key"] = "sk-mock-placeholder"
guard, host = load(ROOT / "plugins" / "response_guard.lua", GUARD_CONFIG, mode)
guard.host = host
# 纯脱敏场景关掉语义审核,避免判定结果抖动让测试不稳定
pii_guard, _ = load(ROOT / "plugins" / "response_guard.lua", dict(GUARD_CONFIG, check_output=False), mode)
print(f"审核后端: {GUARD_CONFIG['base_url']} model={GUARD_CONFIG['model']} mode={mode}")
scenario_input_denied_stream(guard, mode)
scenario_input_denied_non_stream(guard, mode)
scenario_stream_pass(guard, mode)
scenario_output_pii(pii_guard, mode)
scenario_output_denied(guard, mode)
scenario_non_stream_pass(guard, mode)
scenario_non_stream_pii(pii_guard, mode)
scenario_upstream_error(guard, mode)
scenario_opaque_request(guard, mode)
scenario_judge_down(mode)
scenario_stream_redact(mode)
scenario_request_rewrite(mode)
scenario_tool_call_paths(mode)
total_ms = sum(call["ms"] for call in host.calls)
if host.calls:
print(f"\n审核调用 {len(host.calls)} 次,平均 {total_ms // len(host.calls)} ms")
print(f"\n{CHECKS - len(FAILURES)}/{CHECKS} 通过")
if FAILURES:
print("失败项:")
for name in FAILURES:
print(" -", name)
return 1
return 0
if __name__ == "__main__":
raise SystemExit(main())