The fastest, cheapest, most efficient open-source agent harness. Run more than 500 agents on a $10 VPS.
prompt_injection
Centralized, deterministic prompt-injection screening. Given a user-provided prompt and a small enforcement context, it normalizes the text, scores it against a set of regex rules plus a couple of heuristics, and returns a verdict (Allow / Review / Block) and a corresponding enforcement action. Callers run this before any model or tool execution path, so adversarial prompts (instruction overrides, role hijacks, system-prompt or credential exfiltration, tool-abuse coercion) are caught up front. There is no persisted state, no RPC surface, and no event subscriber; it is a pure synchronous analysis library exposed via a single function.
Responsibilities
- Normalize incoming prompts to defeat common obfuscation: lowercasing, leet-speak (
0too,1toi,@toa, and similar), Cyrillic homoglyph folding, fullwidth-ASCII folding, zero-width, bidi, and formatting-character stripping, and whitespace collapse (plus a whitespace-strippedcompactvariant). - Score the prompt against deterministic
DETECTION_RULES(compiled once into a singleRegexSetDFA, matched across thelowered/collapsed/compactvariants) and two inline heuristics (has_instruction_override,has_exfiltration_intent). - Optionally apply an env-gated
HeuristicClassifierthat adds a small bounded score for suspicious trait combinations. - Map the summed score to a verdict via fixed thresholds:
Blockat 0.70 or above,Reviewat 0.55 or above, elseAllow. - Produce a
PromptEnforcementDecisioncarrying the verdict, score, reason codes and messages, action, a SHA-256 prompt hash, and prompt char count, and emit a structuredtracing::info!audit line that is PII-safe: it logs the hash, not the prompt text.
Key files
| File | Role |
|---|---|
crates/openhuman-core/src/security/prompt_injection/mod.rs |
Module docstring and re-exports of the public surface. No logic. |
crates/openhuman-core/src/security/prompt_injection/detector.rs |
All logic: types, normalization, detection rules plus RegexSet, heuristics, optional classifier, scoring and thresholds, and the enforce_prompt_input entry point. |
crates/openhuman-core/src/security/prompt_injection/prompt_injection_tests.rs |
#[cfg(test)] suite (around 24 cases) covering allow/review/block verdicts, obfuscation handling, and known false-positive regressions (TAURI-140, issue #1940). |
Public surface
Re-exported from mod.rs (all defined in detector.rs):
enforce_prompt_input(input: &str, context: PromptEnforcementContext) -> PromptEnforcementDecision: the entry point for user-facing prompts.scan_tool_definition(field: &str, text: &str) -> Option<ToolDefinitionScanHit>: same rules applied to remote MCP tool descriptions and titles; any non-Allowverdict is a hit and the registry rejects the tool.PromptEnforcementContext<'a>: borrowedsourceplus optionalrequest_id/user_id/session_idfor the audit log.PromptEnforcementDecision:{ verdict, score: f32, reasons, action, prompt_hash: String, prompt_chars: usize }.PromptEnforcementAction:Allow/Blocked/ReviewBlocked.PromptInjectionVerdict:Allow/Block/Review(serdelowercase).PromptInjectionReason:{ code: String, message: String }.
Internal-only (not exported): DetectionRule, NormalizedPrompt, HeuristicClassifier, OptionalClassifier, analyze_prompt, normalize_prompt, prompt_hash.
Configuration
OPENHUMAN_PROMPT_INJECTION_CLASSIFIER(env): resolved once viaLazy."heuristic"enablesHeuristicClassifier; anything else (default"off") disables the optional classifier. The active choice is logged atdebug.
Persistence
None. The module is stateless aside from Lazy statics (compiled regexes, the classifier selection).
Dependencies
No crate::* or crate::core::* dependencies; the module is self-contained. External crates only:
regex(Regex,RegexSet) for pattern matching and batched DFA matching.once_cell::sync::Lazyfor compile-once statics.serdefor deriving on the verdict/reason types.sha2andhexfor SHA-256 prompt hashing for audit logs.tracingfor structured audit and debug logging.std::envfor classifier selection.
Used by
Consumers call enforce_prompt_input and treat any non-Allow action as a rejection (returning a user-facing guard message):
crates/openhuman-core/src/agent/session_host/runtime.rs: gates agent session turns; emitsprompt_injection_blocked.crates/openhuman-core/src/agent/bus.rs: screens inbound prompts on the agent event path.crates/openhuman-core/src/agent/tinyagents/host/security_gate.rs:screen_inputstage of the tinyagents security gate.crates/openhuman-core/src/mcp/registry/mod.rs:scan_tool_definitionon remote tool metadata at registration.crates/openhuman-core/src/web_chat/: screens chat payloads at the web channel ingress (start_chat).crates/openhuman-core/src/inference/local/ops.rs: rejects injected prompts before local-AI runtime execution.crates/openhuman-core/src/platform/about_app/catalog.rs: surfaces theconversation.prompt_injection_guardcapability entry.crates/openhuman-core/src/core/observability.rs: classifiesprompt_injection_blockederror messages for telemetry (string-based, not a code dependency).
Notes and gotchas
- Three-variant matching is load-bearing: rules are matched against
lowered,collapsed, and the whitespace-strippedcompactstrings, so spacing-obfuscated attacks (j a i l b r e a k,j w t) still contribute to score and reasons. - Threshold history is encoded in comments:
Reviewwas tuned from 0.45 to 0.50 to 0.55, and the obfuscated-instruction signal was bumped to 0.56 to eliminate a false-positive band while keeping spaced-out overrides at Review level (TAURI-140). - The verb list for exfiltration intent is deliberately conservative:
exfiltrate.credentials_with_intentexcludes high-false-positive verbs (show,give,tell,fetch,return,output) and requires a determiner within a bounded window, so benign technical questions ("show me the password reset flow", "reveal how to set my api key") do not trip it (issue #1940). is_obfuscation_charis the single source of truth shared between thehad_zwspflag and the stripping step, to prevent drift.ReviewandBlockboth yield non-Allowactions. Every current caller treats them identically as a rejection, so the distinction is informational and audit-only at the call sites.