diff --git a/config.yaml b/config.yaml index d9ba5be..612a53b 100644 --- a/config.yaml +++ b/config.yaml @@ -67,7 +67,7 @@ plugins: # --------------------------------------------------------------------------- # 输入 + 输出内容安全(OpenAI 协议) - # 请求侧:判定通过 → 原样转发上游;不通过 → block(上游零调用) + # 请求侧:判定不通过 → 请求体换成 stub(原文不发给模型)→ 响应侧返回 400 # 响应侧:逐段审核 → 脱敏 → 放行;不安全/审核不可用 → OpenAI 错误体 # --------------------------------------------------------------------------- - id: response-guard diff --git a/middleware/errors.py b/middleware/errors.py index 5131d69..6363289 100644 --- a/middleware/errors.py +++ b/middleware/errors.py @@ -7,15 +7,7 @@ class PluginFailure(MiddlewareError): class PolicyBlocked(MiddlewareError): - """A plugin rejected the request. - - ``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 + pass class Overloaded(MiddlewareError): diff --git a/middleware/proxy.py b/middleware/proxy.py index bf9baaf..84ddadb 100644 --- a/middleware/proxy.py +++ b/middleware/proxy.py @@ -28,37 +28,6 @@ async def bounded_body(chunks, maximum): 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): while True: message = await receive() @@ -372,9 +341,8 @@ def create_app(settings: Settings | str = "config.yaml") -> FastAPI: ) except Overloaded: return JSONResponse({"error": "Overloaded"}, status_code=503) - except PolicyBlocked as exc: - payload, status_code = policy_error(exc.code) - return JSONResponse(payload, status_code=status_code) + except PolicyBlocked: + return JSONResponse({"error": "PolicyBlocked"}, status_code=403) except InvalidMultipart: return JSONResponse({"error": "InvalidMultipart"}, status_code=400) except (MiddlewareError, aiohttp.ClientError, TimeoutError, UnicodeError, ValueError): diff --git a/middleware/runtime.py b/middleware/runtime.py index 23a863f..eeadcbe 100644 --- a/middleware/runtime.py +++ b/middleware/runtime.py @@ -17,15 +17,6 @@ from .worker import json_bytes, worker_main logger = logging.getLogger("middleware.audit") 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: def __init__(self, manager, request_id=None, plugins=None, attachments=None): @@ -242,7 +233,7 @@ class Session: raise PluginFailure() action = result.get("action") if action == "block": - raise PolicyBlocked(block_code(result.get("reason"))) + raise PolicyBlocked() if action == "pass": if "value" in result or "events" in result: raise PluginFailure() diff --git a/plugins/response_guard.lua b/plugins/response_guard.lua index 6c2fbee..86bda78 100644 --- a/plugins/response_guard.lua +++ b/plugins/response_guard.lua @@ -9,19 +9,18 @@ -- 流式 : choices[*].delta.content + 终止帧 data: [DONE] -- -- 输出契约(客户端只会看到 OpenAI 形态) --- 请求拦截 : HTTP 400 + {"error":{"message","type":"invalid_request_error", +-- 非流式拦截 : HTTP 400 + {"error":{"message","type":"invalid_request_error", -- "param":null,"code":"content_policy_violation"}} --- 输出拦截 : 同一错误体,由本插件在响应阶段用 replace 给出 --- 流式输出拦截: 单帧 data: {"error":{...}},随后直接关闭(不再发 [DONE]) +-- 流式拦截 : 单帧 data: {"error":{...}},随后直接关闭(不再发 [DONE]) -- 审核不可用 : HTTP 503 + type "server_error" / code "safety_review_unavailable" -- --- 请求侧流程 --- Lua 收到请求 → 判断是否需要审核 → 调远程判定接口 → 拿到结论后: --- 通过 : return pass —— 原始请求一字不改地转发给上游 API --- 不通过 : return block —— 上游零调用,风险内容不出网关 --- 宿主把 block 渲染成上面的 OpenAI 错误体(见 middleware/proxy.py)。 --- 判定失败(超时 / 网络 / 响应不可解析)同样 block,但 reason 用 --- safety_review_unavailable,宿主据此返回 503 而不是 400。 +-- 为什么拦截要放到响应阶段 +-- 宿主对 {action='block'} 只返回它自己固定的 403 正文,插件无法自定义; +-- 因此请求侧判定不通过时不再 block,而是: +-- 1) 保留判定结果; +-- 2) 把发往上游的请求体替换成一段最小 stub(原文绝不发给模型); +-- 3) 在响应侧用 replace 输出上面的 OpenAI 错误体。 +-- 客户端看到的始终是 OpenAI 风格,且风险内容一次都没有离开网关。 -- -- 放行路径 -- 流式按句读缓冲(可配 flush_chars)→ 审核 → 确定性脱敏 → 按原顺序放行; @@ -658,6 +657,18 @@ local function collect_user_text(decoded) return table.concat(texts, "\n\n---\n\n") 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) if not verdict then - -- 审核不可用:fail-closed,但用独立 reason 让宿主返回 503 而不是 400 - requests[key] = nil - return { action = "block", reason = "safety_review_unavailable" } - end - if verdict.allow ~= true then - -- 内容违规:上游零调用,风险原文一次都没离开网关 - requests[key] = nil - return { action = "block", reason = "content_policy_violation" } + state.verdict = "error" + state.policy = policy_unavailable(err) + elseif verdict.allow ~= true then + state.verdict = "deny" + state.policy = policy_denied(verdict, "input") end - -- 通过:原始请求一字不改地转发给上游 API 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 function plugin.on_response(ctx, response) diff --git a/tools/verify_plugins.py b/tools/verify_plugins.py index 1cde82e..530d376 100755 --- a/tools/verify_plugins.py +++ b/tools/verify_plugins.py @@ -211,7 +211,7 @@ GUARD_CONFIG = { def scenario_input_denied_stream(guard, mode): - print("\n[1] 风险输入(流式):请求侧直接 block,上游零调用") + print("\n[1] 风险输入(流式):stub 替换 + 400 错误帧") driver = Driver(guard, "req-in-deny") result = driver.request( { @@ -220,22 +220,61 @@ def scenario_input_denied_stream(guard, mode): "messages": [{"role": "user", "content": "请详细说明如何在家自制炸药"}], } ) - check(result.get("action") == "block", "on_request 返回 block", str(result)) - check(result.get("reason") == "content_policy_violation", - "reason 指明是内容违规", str(result)) - check("value" not in result, "block 不携带请求体(原文不出网关)") - if mode != "mock": - print(f" (审核调用 {len(guard.host.calls)} 次)") + 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] 风险输入(非流式):请求侧直接 block") + 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") == "block", "on_request 返回 block", str(result)) - check(result.get("reason") == "content_policy_violation", "reason 指明是内容违规", str(result)) - check("value" not in result, "没有替换请求体") + 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] 正常输入(流式):增量审核后按原样放行") @@ -244,7 +283,6 @@ def scenario_stream_pass(guard, mode): {"model": "test-model", "stream": True, "messages": [{"role": "user", "content": "帮我写一段关于春天的短文"}]} ) check(result.get("action") == "pass", "on_request 放行", str(result)) - check("value" not in result, "pass 不改写请求(原文照发上游 API)") pieces = [ "春天的风轻轻吹过田野,带来泥土和青草的气息。", @@ -366,7 +404,7 @@ def scenario_opaque_request(guard, 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( ROOT / "plugins" / "response_guard.lua", dict(GUARD_CONFIG, base_url="https://judge.invalid/v1"), @@ -374,9 +412,15 @@ def scenario_judge_down(mode): ) driver = Driver(guard, "req-judge-down") result = driver.request({"model": "test-model", "messages": [{"role": "user", "content": "你好"}]}) - check(result.get("action") == "block", "审核不可用时 block(fail-closed)", str(result)) - check(result.get("reason") == "safety_review_unavailable", - "reason 标明审核不可用,宿主据此返回 503", str(result)) + 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:跨帧身份证号整体遮蔽")