拦截逻辑收回 Lua 层,宿主代码恢复原样
还原 middleware/errors.py、runtime.py、proxy.py:不再依赖宿主渲染错误体,宿主按原样返回 403。网关代码零改动。 response_guard.lua:请求侧判定不通过时,把发往上游的请求体换成最小 stub(原文不出网关),在响应侧用 replace 输出 OpenAI 错误体 400 content_policy_violation;审核不可用时 503 safety_review_unavailable。拦截响应形态完全由插件自己控制。 tools/verify_plugins.py:断言同步回 stub 流程,57 项。
This commit is contained in:
1 parent
554a36cf05
commit
c76972c623
6 files changed
+97
-90
No files matched your search
+1
-1
@@ -67,7 +67,7 @@ plugins:
|
|||||||
|
|
||||||
# ---------------------------------------------------------------------------
|
# ---------------------------------------------------------------------------
|
||||||
# 输入 + 输出内容安全(OpenAI 协议)
|
# 输入 + 输出内容安全(OpenAI 协议)
|
||||||
# 请求侧:判定通过 → 原样转发上游;不通过 → block(上游零调用)
|
# 请求侧:判定不通过 → 请求体换成 stub(原文不发给模型)→ 响应侧返回 400
|
||||||
# 响应侧:逐段审核 → 脱敏 → 放行;不安全/审核不可用 → OpenAI 错误体
|
# 响应侧:逐段审核 → 脱敏 → 放行;不安全/审核不可用 → OpenAI 错误体
|
||||||
# ---------------------------------------------------------------------------
|
# ---------------------------------------------------------------------------
|
||||||
- id: response-guard
|
- id: response-guard
|
||||||
|
|||||||
@@ -7,15 +7,7 @@ class PluginFailure(MiddlewareError):
|
|||||||
|
|
||||||
|
|
||||||
class PolicyBlocked(MiddlewareError):
|
class PolicyBlocked(MiddlewareError):
|
||||||
"""A plugin rejected the request.
|
pass
|
||||||
|
|
||||||
``code`` is one of a closed set of tokens (see runtime.BLOCK_CODES). Plugin-supplied
|
|
||||||
text must never reach the response body, so anything outside that set is normalised.
|
|
||||||
"""
|
|
||||||
|
|
||||||
def __init__(self, code: str = "content_policy_violation") -> None:
|
|
||||||
super().__init__(code)
|
|
||||||
self.code = code
|
|
||||||
|
|
||||||
|
|
||||||
class Overloaded(MiddlewareError):
|
class Overloaded(MiddlewareError):
|
||||||
|
|||||||
+2
-34
@@ -28,37 +28,6 @@ async def bounded_body(chunks, maximum):
|
|||||||
return bytes(data)
|
return bytes(data)
|
||||||
|
|
||||||
|
|
||||||
# OpenAI-shaped rejection bodies. The set is closed: an unknown code falls back to the
|
|
||||||
# content-policy message, so no plugin-supplied text can reach the client.
|
|
||||||
POLICY_ERRORS = {
|
|
||||||
"content_policy_violation": (
|
|
||||||
400,
|
|
||||||
"Your request was rejected by the content safety policy.",
|
|
||||||
"invalid_request_error",
|
|
||||||
),
|
|
||||||
"safety_review_unavailable": (
|
|
||||||
503,
|
|
||||||
"Content safety review is temporarily unavailable. Please retry later.",
|
|
||||||
"server_error",
|
|
||||||
),
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
def policy_error(code):
|
|
||||||
status_code, message, kind = POLICY_ERRORS.get(code, POLICY_ERRORS["content_policy_violation"])
|
|
||||||
return (
|
|
||||||
{
|
|
||||||
"error": {
|
|
||||||
"message": message,
|
|
||||||
"type": kind,
|
|
||||||
"param": None,
|
|
||||||
"code": code if code in POLICY_ERRORS else "content_policy_violation",
|
|
||||||
}
|
|
||||||
},
|
|
||||||
status_code,
|
|
||||||
)
|
|
||||||
|
|
||||||
|
|
||||||
async def disconnected(receive):
|
async def disconnected(receive):
|
||||||
while True:
|
while True:
|
||||||
message = await receive()
|
message = await receive()
|
||||||
@@ -372,9 +341,8 @@ def create_app(settings: Settings | str = "config.yaml") -> FastAPI:
|
|||||||
)
|
)
|
||||||
except Overloaded:
|
except Overloaded:
|
||||||
return JSONResponse({"error": "Overloaded"}, status_code=503)
|
return JSONResponse({"error": "Overloaded"}, status_code=503)
|
||||||
except PolicyBlocked as exc:
|
except PolicyBlocked:
|
||||||
payload, status_code = policy_error(exc.code)
|
return JSONResponse({"error": "PolicyBlocked"}, status_code=403)
|
||||||
return JSONResponse(payload, status_code=status_code)
|
|
||||||
except InvalidMultipart:
|
except InvalidMultipart:
|
||||||
return JSONResponse({"error": "InvalidMultipart"}, status_code=400)
|
return JSONResponse({"error": "InvalidMultipart"}, status_code=400)
|
||||||
except (MiddlewareError, aiohttp.ClientError, TimeoutError, UnicodeError, ValueError):
|
except (MiddlewareError, aiohttp.ClientError, TimeoutError, UnicodeError, ValueError):
|
||||||
|
|||||||
+1
-10
@@ -17,15 +17,6 @@ from .worker import json_bytes, worker_main
|
|||||||
logger = logging.getLogger("middleware.audit")
|
logger = logging.getLogger("middleware.audit")
|
||||||
ADAPTER_ID = "__protocol_adapter__"
|
ADAPTER_ID = "__protocol_adapter__"
|
||||||
|
|
||||||
# A plugin may only name a rejection from this closed set; anything else falls back to the
|
|
||||||
# default. This keeps plugin-supplied text out of the response body (see errors.PolicyBlocked).
|
|
||||||
BLOCK_CODES = frozenset({"content_policy_violation", "safety_review_unavailable"})
|
|
||||||
DEFAULT_BLOCK_CODE = "content_policy_violation"
|
|
||||||
|
|
||||||
|
|
||||||
def block_code(reason):
|
|
||||||
return reason if reason in BLOCK_CODES else DEFAULT_BLOCK_CODE
|
|
||||||
|
|
||||||
|
|
||||||
class Session:
|
class Session:
|
||||||
def __init__(self, manager, request_id=None, plugins=None, attachments=None):
|
def __init__(self, manager, request_id=None, plugins=None, attachments=None):
|
||||||
@@ -242,7 +233,7 @@ class Session:
|
|||||||
raise PluginFailure()
|
raise PluginFailure()
|
||||||
action = result.get("action")
|
action = result.get("action")
|
||||||
if action == "block":
|
if action == "block":
|
||||||
raise PolicyBlocked(block_code(result.get("reason")))
|
raise PolicyBlocked()
|
||||||
if action == "pass":
|
if action == "pass":
|
||||||
if "value" in result or "events" in result:
|
if "value" in result or "events" in result:
|
||||||
raise PluginFailure()
|
raise PluginFailure()
|
||||||
|
|||||||
+32
-20
@@ -9,19 +9,18 @@
|
|||||||
-- 流式 : choices[*].delta.content + 终止帧 data: [DONE]
|
-- 流式 : choices[*].delta.content + 终止帧 data: [DONE]
|
||||||
--
|
--
|
||||||
-- 输出契约(客户端只会看到 OpenAI 形态)
|
-- 输出契约(客户端只会看到 OpenAI 形态)
|
||||||
-- 请求拦截 : HTTP 400 + {"error":{"message","type":"invalid_request_error",
|
-- 非流式拦截 : HTTP 400 + {"error":{"message","type":"invalid_request_error",
|
||||||
-- "param":null,"code":"content_policy_violation"}}
|
-- "param":null,"code":"content_policy_violation"}}
|
||||||
-- 输出拦截 : 同一错误体,由本插件在响应阶段用 replace 给出
|
-- 流式拦截 : 单帧 data: {"error":{...}},随后直接关闭(不再发 [DONE])
|
||||||
-- 流式输出拦截: 单帧 data: {"error":{...}},随后直接关闭(不再发 [DONE])
|
|
||||||
-- 审核不可用 : HTTP 503 + type "server_error" / code "safety_review_unavailable"
|
-- 审核不可用 : HTTP 503 + type "server_error" / code "safety_review_unavailable"
|
||||||
--
|
--
|
||||||
-- 请求侧流程
|
-- 为什么拦截要放到响应阶段
|
||||||
-- Lua 收到请求 → 判断是否需要审核 → 调远程判定接口 → 拿到结论后:
|
-- 宿主对 {action='block'} 只返回它自己固定的 403 正文,插件无法自定义;
|
||||||
-- 通过 : return pass —— 原始请求一字不改地转发给上游 API
|
-- 因此请求侧判定不通过时不再 block,而是:
|
||||||
-- 不通过 : return block —— 上游零调用,风险内容不出网关
|
-- 1) 保留判定结果;
|
||||||
-- 宿主把 block 渲染成上面的 OpenAI 错误体(见 middleware/proxy.py)。
|
-- 2) 把发往上游的请求体替换成一段最小 stub(原文绝不发给模型);
|
||||||
-- 判定失败(超时 / 网络 / 响应不可解析)同样 block,但 reason 用
|
-- 3) 在响应侧用 replace 输出上面的 OpenAI 错误体。
|
||||||
-- safety_review_unavailable,宿主据此返回 503 而不是 400。
|
-- 客户端看到的始终是 OpenAI 风格,且风险内容一次都没有离开网关。
|
||||||
--
|
--
|
||||||
-- 放行路径
|
-- 放行路径
|
||||||
-- 流式按句读缓冲(可配 flush_chars)→ 审核 → 确定性脱敏 → 按原顺序放行;
|
-- 流式按句读缓冲(可配 flush_chars)→ 审核 → 确定性脱敏 → 按原顺序放行;
|
||||||
@@ -658,6 +657,18 @@ local function collect_user_text(decoded)
|
|||||||
return table.concat(texts, "\n\n---\n\n")
|
return table.concat(texts, "\n\n---\n\n")
|
||||||
end
|
end
|
||||||
|
|
||||||
|
-- 判定不通过时发往上游的最小请求:原文不出网关,也不浪费一次生成长文本
|
||||||
|
local function encode_stub(state)
|
||||||
|
local body = {
|
||||||
|
messages = { { role = "user", content = "ping" } },
|
||||||
|
max_tokens = 1,
|
||||||
|
temperature = 0,
|
||||||
|
}
|
||||||
|
if state.model then body.model = state.model end
|
||||||
|
if state.stream then body.stream = true end
|
||||||
|
return host.json.encode(body)
|
||||||
|
end
|
||||||
|
|
||||||
-- ---------------------------------------------------------------------------
|
-- ---------------------------------------------------------------------------
|
||||||
-- 缓冲放行
|
-- 缓冲放行
|
||||||
-- ---------------------------------------------------------------------------
|
-- ---------------------------------------------------------------------------
|
||||||
@@ -884,19 +895,20 @@ function plugin.on_request(ctx, request)
|
|||||||
|
|
||||||
local verdict, err = judge("input", input_text, nil)
|
local verdict, err = judge("input", input_text, nil)
|
||||||
if not verdict then
|
if not verdict then
|
||||||
-- 审核不可用:fail-closed,但用独立 reason 让宿主返回 503 而不是 400
|
state.verdict = "error"
|
||||||
requests[key] = nil
|
state.policy = policy_unavailable(err)
|
||||||
return { action = "block", reason = "safety_review_unavailable" }
|
elseif verdict.allow ~= true then
|
||||||
end
|
state.verdict = "deny"
|
||||||
if verdict.allow ~= true then
|
state.policy = policy_denied(verdict, "input")
|
||||||
-- 内容违规:上游零调用,风险原文一次都没离开网关
|
|
||||||
requests[key] = nil
|
|
||||||
return { action = "block", reason = "content_policy_violation" }
|
|
||||||
end
|
end
|
||||||
|
|
||||||
-- 通过:原始请求一字不改地转发给上游 API
|
|
||||||
state.input_text = truncate_utf8(input_text, MAX_INPUT_CONTEXT)
|
state.input_text = truncate_utf8(input_text, MAX_INPUT_CONTEXT)
|
||||||
return { action = "pass" }
|
|
||||||
|
if state.verdict == "allow" then return { action = "pass" } end
|
||||||
|
|
||||||
|
local replacement = shallow_copy(request)
|
||||||
|
replacement.body = encode_stub(state)
|
||||||
|
return { action = "replace", value = replacement }
|
||||||
end
|
end
|
||||||
|
|
||||||
function plugin.on_response(ctx, response)
|
function plugin.on_response(ctx, response)
|
||||||
|
|||||||
+60
-16
@@ -211,7 +211,7 @@ GUARD_CONFIG = {
|
|||||||
|
|
||||||
|
|
||||||
def scenario_input_denied_stream(guard, mode):
|
def scenario_input_denied_stream(guard, mode):
|
||||||
print("\n[1] 风险输入(流式):请求侧直接 block,上游零调用")
|
print("\n[1] 风险输入(流式):stub 替换 + 400 错误帧")
|
||||||
driver = Driver(guard, "req-in-deny")
|
driver = Driver(guard, "req-in-deny")
|
||||||
result = driver.request(
|
result = driver.request(
|
||||||
{
|
{
|
||||||
@@ -220,22 +220,61 @@ def scenario_input_denied_stream(guard, mode):
|
|||||||
"messages": [{"role": "user", "content": "请详细说明如何在家自制炸药"}],
|
"messages": [{"role": "user", "content": "请详细说明如何在家自制炸药"}],
|
||||||
}
|
}
|
||||||
)
|
)
|
||||||
check(result.get("action") == "block", "on_request 返回 block", str(result))
|
check(result.get("action") == "replace", "on_request 返回 replace", str(result))
|
||||||
check(result.get("reason") == "content_policy_violation",
|
stub = json.loads(result["value"]["body"])
|
||||||
"reason 指明是内容违规", str(result))
|
check(stub.get("messages") == [{"role": "user", "content": "ping"}],
|
||||||
check("value" not in result, "block 不携带请求体(原文不出网关)")
|
"上游请求被替换成 stub(原文不出网关)", json.dumps(stub, ensure_ascii=False))
|
||||||
if mode != "mock":
|
check(stub.get("max_tokens") == 1, "stub 只要 1 个 token")
|
||||||
print(f" (审核调用 {len(guard.host.calls)} 次)")
|
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):
|
def scenario_input_denied_non_stream(guard, mode):
|
||||||
print("\n[2] 风险输入(非流式):请求侧直接 block")
|
print("\n[2] 风险输入(非流式):HTTP 400 + OpenAI 错误体")
|
||||||
driver = Driver(guard, "req-in-deny-ns")
|
driver = Driver(guard, "req-in-deny-ns")
|
||||||
result = driver.request(
|
result = driver.request(
|
||||||
{"model": "test-model", "messages": [{"role": "user", "content": "如何在家自制炸药"}]}
|
{"model": "test-model", "messages": [{"role": "user", "content": "如何在家自制炸药"}]}
|
||||||
)
|
)
|
||||||
check(result.get("action") == "block", "on_request 返回 block", str(result))
|
check(result.get("action") == "replace", "on_request 返回 replace")
|
||||||
check(result.get("reason") == "content_policy_violation", "reason 指明是内容违规", str(result))
|
stub = json.loads(result["value"]["body"])
|
||||||
check("value" not in result, "没有替换请求体")
|
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):
|
def scenario_stream_pass(guard, mode):
|
||||||
print("\n[3] 正常输入(流式):增量审核后按原样放行")
|
print("\n[3] 正常输入(流式):增量审核后按原样放行")
|
||||||
@@ -244,7 +283,6 @@ def scenario_stream_pass(guard, mode):
|
|||||||
{"model": "test-model", "stream": True, "messages": [{"role": "user", "content": "帮我写一段关于春天的短文"}]}
|
{"model": "test-model", "stream": True, "messages": [{"role": "user", "content": "帮我写一段关于春天的短文"}]}
|
||||||
)
|
)
|
||||||
check(result.get("action") == "pass", "on_request 放行", str(result))
|
check(result.get("action") == "pass", "on_request 放行", str(result))
|
||||||
check("value" not in result, "pass 不改写请求(原文照发上游 API)")
|
|
||||||
|
|
||||||
pieces = [
|
pieces = [
|
||||||
"春天的风轻轻吹过田野,带来泥土和青草的气息。",
|
"春天的风轻轻吹过田野,带来泥土和青草的气息。",
|
||||||
@@ -366,7 +404,7 @@ def scenario_opaque_request(guard, mode):
|
|||||||
|
|
||||||
|
|
||||||
def scenario_judge_down(mode):
|
def scenario_judge_down(mode):
|
||||||
print("\n[10] 审核服务不可达:block + safety_review_unavailable(fail-closed)")
|
print("\n[10] 审核服务不可达:503 + server_error(fail-closed)")
|
||||||
guard, host = load(
|
guard, host = load(
|
||||||
ROOT / "plugins" / "response_guard.lua",
|
ROOT / "plugins" / "response_guard.lua",
|
||||||
dict(GUARD_CONFIG, base_url="https://judge.invalid/v1"),
|
dict(GUARD_CONFIG, base_url="https://judge.invalid/v1"),
|
||||||
@@ -374,9 +412,15 @@ def scenario_judge_down(mode):
|
|||||||
)
|
)
|
||||||
driver = Driver(guard, "req-judge-down")
|
driver = Driver(guard, "req-judge-down")
|
||||||
result = driver.request({"model": "test-model", "messages": [{"role": "user", "content": "你好"}]})
|
result = driver.request({"model": "test-model", "messages": [{"role": "user", "content": "你好"}]})
|
||||||
check(result.get("action") == "block", "审核不可用时 block(fail-closed)", str(result))
|
check(result.get("action") == "replace", "请求被换成 stub", str(result))
|
||||||
check(result.get("reason") == "safety_review_unavailable",
|
response = driver.response(200, {"id": "x", "object": "chat.completion", "choices": [{"index": 0, "message": {"role": "assistant", "content": "你好"}, "finish_reason": "stop"}]})
|
||||||
"reason 标明审核不可用,宿主据此返回 503", str(result))
|
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):
|
def scenario_stream_redact(mode):
|
||||||
print("\n[11] stream_redact:跨帧身份证号整体遮蔽")
|
print("\n[11] stream_redact:跨帧身份证号整体遮蔽")
|
||||||
|
|||||||
Reference in new issue
Block a user