Spaces:
Running

WorkPilot-AI / core /observability /injection.py
Aynkhn's picture
Deploy WorkPilot demo
fd5dd94 verified
Raw History Blame Contribute Delete
3.5 kB
"""Cheap heuristic prompt-injection detector for inbound untrusted text (Phase 15).
It is a SIGNAL, never a control:
* it never grants a permission and never removes one - the gateway's Cedar policy, taint
checks and approvals decide every side effect whatever this says;
* it is recorded (``security_signals``, the run span, ``RunState["signals"]``) so graphs may
route a flagged message to a human sooner, and so the alert sweep can see spikes;
* false negatives are expected (paraphrases, other languages, encodings); the defense is the
quarantine extractor having no tools, not this list.
Rules are regexes over a lower-cased, whitespace-collapsed copy of the text, in English and
Roman Urdu, plus structural tells (fake role tags, our own prompt delimiters).
"""
from __future__ import annotations
import re
from dataclasses import dataclass
RULES: dict[str, re.Pattern[str]] = {
"ignore_instructions": re.compile(
r"\b(ignore|disregard|forget|override|bypass)\b.{0,40}\b(previous|prior|above|earlier|"
r"all|any|your|the)\b.{0,20}\b(instructions?|rules?|prompts?|guidelines?|directions?)"
),
"role_override": re.compile(
r"\b(you are now|from now on you|act as|pretend to be|roleplay as|new persona|"
r"developer mode|dan mode|jailbreak)\b"
),
"system_prompt_probe": re.compile(
r"\b(system prompt|hidden instructions?|initial instructions?|reveal your (prompt|"
r"instructions|rules)|print your (prompt|instructions))\b"
),
"fake_role_tag": re.compile(
r"(<\s*/?\s*(system|assistant|developer|instructions?)\s*>|\[\s*(system|inst)\s*\]|"
r"^\s*(system|assistant)\s*:|###\s*(system|instruction))",
re.MULTILINE,
),
"delimiter_escape": re.compile(r"</?\s*untrusted_message|</?\s*tool_(call|result)"),
"exfiltration": re.compile(
r"\b(send|forward|email|export|upload|share|leak)\b.{0,60}\b(all|every|entire|full)\b"
r".{0,30}\b(customers?|orders?|contacts?|data|database|list|records?|passwords?|keys?)"
),
"credential_request": re.compile(
r"\b(api[ _-]?key|access token|secret key|password|otp|cnic)\b.{0,40}\b(send|share|"
r"give|tell|reply|bhej|batao|do)\b"
),
"tool_coercion": re.compile(
r"\b(call|invoke|execute|run|use)\b.{0,20}\b(the )?(tool|function|refund|"
r"issue_refund|send_email|api)\b.{0,40}\b(now|immediately|without (approval|asking))"
),
"roman_urdu_override": re.compile(
r"\b(pichl[ie]|pehl[ae]|saari|sari|tamam)\b.{0,30}\b(hidayat|hidayaat|instructions?|"
r"baatein|rules?)\b.{0,30}\b(bhool|bhul|ignore|nazar ?andaz|chor|chhor)"
),
}
@dataclass(frozen=True)
class InjectionSignal:
score: int # number of distinct rules that matched
rules: tuple[str, ...]
@property
def flagged(self) -> bool:
return self.score > 0
def as_dict(self) -> dict[str, object]:
return {"score": self.score, "rules": list(self.rules), "flagged": self.flagged}
MAX_SCAN_CHARS = 20_000
def detect(text: str | None) -> InjectionSignal:
if not text:
return InjectionSignal(0, ())
t = re.sub(r"\s+", " ", text[:MAX_SCAN_CHARS].lower())
raw = text[:MAX_SCAN_CHARS].lower()
hits = tuple(
name for name, rx in RULES.items() if rx.search(raw if name == "fake_role_tag" else t)
)
return InjectionSignal(len(hits), hits)