配置 AI 安全护栏与敏感信息保护
本文介绍如何在 API7 AI 网关层实现分层安全控制。通过 ai-prompt-guard、内容审核插件和 ai-request-rewrite,你可以在模型调用前后统一执行策略,降低提示词注入、敏感信息泄露和不合规输出风险。
分层安全模型
安全护栏通常包括三层:
- 提示词过滤:在模型调用前拦截提示词注入和违规指令。
- 内容审核:识别暴力、仇恨、色情、违法等高风险内容。
- 敏感信息处理:在请求发送给模型前屏蔽或改写身份证号、手机号、邮箱等敏感信息。
配置提示词防护
以下示例使用 PCRE 正则表达式限制允许的问题类型,并阻断常见绕过指令。
- Admin API
- ADC
curl "http://127.0.0.1:7080/apisix/admin/routes?gateway_group_id=default" -X PUT \
-H "X-API-KEY: $ADMIN_API_KEY" \
-d '{
"id": "ai-guardrails",
"service_id": "'"$SERVICE_ID"'",
"paths": ["/ai/chat"],
"plugins": {
"ai-prompt-guard": {
"allow_patterns": ["(?i)^(what|how|why|explain|summarize|translate)\\b"],
"deny_patterns": ["(?i)(ignore\\s+all\\s+previous\\s+instructions|reveal\\s+system\\s+prompt|bypass\\s+guardrails)"],
"match_all_roles": false,
"match_all_conversation_history": false
},
"ai-proxy": {
"provider": "openai",
"auth": { "header": { "Authorization": "Bearer '"$OPENAI_API_KEY"'" } },
"options": { "model": "gpt-4o" }
}
}
}'
adc.yaml
services:
- name: AI Guardrails Service
routes:
- name: ai-guardrails
uris:
- /ai/chat
plugins:
ai-prompt-guard:
allow_patterns:
- (?i)^(what|how|why|explain|summarize|translate)\b
deny_patterns:
- (?i)(ignore\s+all\s+previous\s+instructions|reveal\s+system\s+prompt|bypass\s+guardrails)
match_all_roles: false
match_all_conversation_history: false
ai-proxy:
provider: openai
auth:
header:
Authorization: Bearer ${OPENAI_API_KEY}
options:
model: gpt-4o
内容审核
可以结合 ai-aws-content-moderation 或 ai-aliyun-content-moderation 对输入内容执行审核。建议将审核结果记录到日志中,并根据业务风险设置拒绝、降级或人工复核策略。
敏感信息处理
对于可能包含个人信息或业务敏感数据的请求,可以使用 ai-request-rewrite 在网关层改写或脱敏内容,再转发给模型服务。
运行建议
- 先从高风险入口启用护栏,例如外部用户输入、客服机器人和公开问答。
- 将策略命中情况写入审计日志,便于安全团队复盘。
- 对误拦截率进行持续评估,避免影响正常业务请求。
- 不要把安全策略只放在应用层,网关层可以提供跨团队的一致控制点。