Vigil-Harbor/Petasos
GitHub: Vigil-Harbor/Petasos
面向 Python AI agent 的可插拔内容安全 pipeline,统一集成多个开源扫描器实现 prompt injection 拦截、PII 检测、会话级频率追踪与工具调用守卫。
Stars: 7 | Forks: 0
MinimalScanner:始终可用,零依赖
源自生产威胁数据的 22 条 regex 规则,涵盖五个家族:注入、角色切换、结构探测(JSON 深度、二进制内容)、编码攻击(不可见字符、文本中的 base64、同形异义字、RTL 重写)以及混淆的破坏性命令。运行时间不到 5ms。这是安全底线:它随每次安装一起提供,即使在加载 ML 后端时也会运行。 ``` from petasos import MinimalScanner scanner = MinimalScanner() result = await scanner.scan("ignore previous instructions", direction="inbound") # result.findings → (ScanFinding(rule_id='petasos.syntactic.injection.ignore-previous', ...),) ```LlmGuardScanner:DeBERTa-v3 语义分析
封装了 [LLM Guard](https://github.com/protectai/llm-guard) 以实现基于 ML 的 prompt injection、毒性、禁止主题、不可见文本和密钥检测。在首次扫描时延迟加载模型。 ``` pip install "petasos[llm-guard]" ``` ``` from petasos.scanners import LlmGuardScanner scanner = LlmGuardScanner() result = await scanner.scan(user_message, direction="inbound") ```LlamaFirewallScanner:Meta 的 PromptGuard 2 + CodeShield
封装了 [LlamaFirewall](https://github.com/meta-llama/PurpleLlama/tree/main/LlamaFirewall) 并提供按组件的归因分析。PromptGuard 用于注入,AlignmentCheck 用于指令遵循,CodeShield 用于代码安全。每个组件均可独立切换:PromptGuard 默认开启;AlignmentCheck 和 CodeShield 为可选启用。 ``` pip install "petasos[llamafirewall]" ``` ``` from petasos.scanners import LlamaFirewallScanner scanner = LlamaFirewallScanner(enable_prompt_guard=True, enable_code_shield=True) result = await scanner.scan(agent_output, direction="outbound") ```PresidioScanner:PII 检测 + 匿名化
封装了 [Microsoft Presidio](https://github.com/microsoft/presidio) 以进行带有内置匿名化的 PII 检测。支持脱敏、掩码和 HMAC-SHA256 哈希处理(用于审计关联而不会暴露原始 PII)。 ``` pip install "petasos[presidio]" ``` ``` from petasos.scanners import PresidioScanner scanner = PresidioScanner() result = await scanner.scan(text, direction="outbound") # result.findings → (ScanFinding(rule_id='petasos.presidio.email_address', ...),) ```频率跟踪:基于会话的指数衰减评分
每个会话都会根据违规历史累积频率评分。最近的违规权重更大(指数衰减)。跟踪器负责处理速率限制、基于 TTL 的会话过期,以及用于限制内存使用的 LRU 驱逐。 ``` from petasos import PetasosConfig config = PetasosConfig( frequency_enabled=True, # default session_ttl_seconds=3600.0, # 1-hour sessions ) ```3 级升级:对重复违规的自动响应
| 级别 | 触发条件(默认) | 行动 | 守卫的操作 | |------|-----------------------|--------|---------------------| | **1 级** | 评分 ≥ 15.0 | `deep_inspect` | 允许工具调用,但会带有警告标记 | | **2 级** | 评分 ≥ 30.0 | `enhanced_scrutiny` | 阻止所有工具调用 | | **3 级** | 评分 ≥ 50.0 | `terminate` | 永久终止会话 | 3 级拥有硬编码的下限值 30.0:`tier3_threshold` 不能设置为低于此值,且 3 级无法被禁用。一个独立的安全网也会在出现 ≥3 次 CRITICAL 发现时触发 3 级,而无论频率状态如何。工具调用守卫:在执行前检查工具名称和参数
`ToolCallGuard` 会对工具名称进行归一化处理(NFKC、同形异义字映射、大小写转换、命名空间/CamelCase/`_tool` 折叠、别名解析),推导出会话的升级层级,并扫描工具参数中是否存在注入和危险命令的 payload。它**在升级时会直接阻止**(2 级阻止所有工具调用,3 级终止会话),否则会**暴露**参数扫描的结果,由调用方去执行。参考插件将其与出口范围的 PII 策略相配合:PII 仅在数据渗出接收端(电子邮件、webhooks、HTTP、剪贴板)阻止,而绝不会在 agent 自身的本地文件写入时阻止。 `evaluate` 接收 `(tool_name, params, session_id)` 并返回一个 `GuardResult`,其中包含 `allowed`、`reason`、`findings`、`tier` 和 `param_scan_unsafe`。 ``` from petasos import ToolCallGuard guard = ToolCallGuard(pipeline, frequency_tracker, config) result = await guard.evaluate("exec", {"command": "rm -rf /"}, "session-001") result.allowed # False once the session escalates to Tier 2/3 result.param_scan_unsafe # True: a command/injection pattern was found in params result.reason # e.g. "tier2: tool calls blocked", "allowed" result.findings # the ScanFindings from the parameter scan ```配置文件:可调的安全姿态
五个内置配置文件(general、customer_service、code_generation、research、admin),支持针对特定配置文件的严重性覆盖、工具别名映射和抑制规则集。自定义配置文件通过字典合并叠加在其上。配置文件是冻结的:内置配置文件无法被覆盖。 `resolve()` 接受内置配置文件名称或字典(合并到 `general` 基础之上)。`pipeline.inspect()` 也支持直接将 `profile=` 作为名称、字典或已解析的配置文件传入。 ``` from petasos import ProfileResolver resolver = ProfileResolver() profile = resolver.resolve("code_generation") # a built-in, by name custom = resolver.resolve({"confidence_floor": 0.8}) # a dict, merged onto `general` result = await pipeline.inspect(text, profile=profile) # 或者完全跳过 resolver: result = await pipeline.inspect(text, profile="code_generation") ```审计 + 警报:安全事件的可观测性
`AuditEmitter` 以可配置的详细程度(minimal / standard / verbose)记录每一个 pipeline 决策。`AlertManager` 评估 5 个内置规则(层级升级、高严重性、连发、跨会话爆发、PII 数量激增),并提供针对每个规则的冷却时间和速率限制。两者都接受同步回调,且都进行了异常隔离。 ``` pipeline = Pipeline( config=config, scanners=scanners, host_id="my-agent", on_audit=lambda event: logger.info(event), on_alert=lambda alert: pagerduty.trigger(alert), ) ```PetasosConfig 参考
所有配置都位于一个单一的 frozen dataclass 中。支持 JSON 序列化,方便进行前端绑定。 ``` from petasos import PetasosConfig config = PetasosConfig( # Fail mode: "open" | "closed" | "degraded" (default) fail_mode="degraded", # Normalization (all default True) normalize_nfkc=True, strip_zero_width=True, map_homoglyphs=True, detect_rtl_override=True, # PII anonymization anonymize=True, pii_entities=["PERSON", "EMAIL_ADDRESS", "PHONE_NUMBER", "CREDIT_CARD"], redaction_mode="hash", # "redact" | "hash" | "mask" | "replace" hash_key="your-hmac-key", # required when redaction_mode="hash" # Session features (all default True) frequency_enabled=True, escalation_enabled=True, tool_guard_enabled=True, audit_enabled=True, alert_enabled=True, # Escalation thresholds tier1_threshold=15.0, tier2_threshold=30.0, tier3_threshold=50.0, # floor: 30.0 # Scanner timeout + circuit breaker scanner_timeout_seconds=10.0, # max 60 scanner_circuit_breaker_threshold=3, scanner_circuit_breaker_cooldown_seconds=30.0, ) ```构建、lint、测试
``` pip install -e ".[dev]" # install with dev dependencies ruff check . # lint ruff format . # format mypy --strict . # type check pytest # run all tests pytest --cov # coverage report ``` CI 会在 Python 3.11、3.12 和 3.13 上运行 lint、类型检查和测试。标签:IaC 扫描, Naabu, Python, 内容安全, 提示词注入防护, 数据泄露防护, 无后门, 网络探测, 逆向工具