Home
Why Sandlock
How It Works Use Cases Comparison Security Model
Docs
Documentation Home Getting Started CLI Reference Python SDK Sandbox Reference FAQ
Products
Overview Sandbox HTTP API Sandbox Scheduler
GitHub Schedule a Demo
Sandlock / Docs /Prompt Guard

Prompt Injection Guard

Prompt injection is untrusted text that an agent mistakes for instructions. Sandlock answers it in layers: keep the text away from privileged stages, confine whatever does read it, and optionally scan it before it reaches a model.

Updated

What it defends against

Retrieved pages, documents, dataset cells, and tool output can all carry instructions. An agent that treats them as authority may change its task or turn its tools against you. No single control fixes that, and none makes a model's reading of arbitrary text trustworthy, so each layer below is built to hold when the one before it fails.

The layers

LayerWhat it doesWhat it does not do
Separate planning from dataThe XOA pipeline gives the planner the task and the model endpoint but no data, and the executor the data but no networkFeeding raw records or executor output back into a privileged model reopens the boundary
Confine the agentFilesystem grants, network rules, HTTP ACLs, a clean environment, and resource limits bound what an injected instruction can reachAn allowed destination can still receive sensitive data
Keep credentials outsideCredential injection attaches a secret in the proxy after the ACL check, so the agent never holds itThe agent can still misuse an operation its policy permits
Review persistent changesBranchAction.DEFER holds file changes until a trusted caller calls commit() or abort()It does not roll back network requests or writes outside the COW workdir
Decide at runtimeA trusted policy_fn approves or denies held operations from application stateA model's claim that a user approved something is not approval
Inspect the textPromptGuard rejects text that matches known injection patterns before a model reads itA passed scan does not establish trustworthy intent

The rest of this page covers the last layer. It is the weakest on its own and is meant to sit in front of the others, never to replace them.

Install

The scanner is a separate package, sandlock-guard, written against the Python standard library with no LLM and no native dependencies. Install it from a checkout of the Sandlock repository, next to the Python SDK:

shell
$ pip install sandlock ./python/guard

The same names are importable from two places. sandlock_guard is the standalone scanner and does not need Sandlock at all. sandlock.guard re-exports it and adds stage(), the pipeline integration.

Scanning text

python
from sandlock_guard import PromptGuard, ScanError

try:
    report = PromptGuard().scan(text)
except ScanError as exc:
    print("inspection incomplete:", exc.code)   # treat as a rejection
else:
    if report.flagged:
        print("rejected:", [f.rule_id for f in report.findings])

The scanner takes a Unicode string of HTML, Markdown, CSV, JSON, or plain text. Fetching, binary document extraction, and browser rendering are out of scope, so scan the text that will actually reach the model, including tool output introduced later. A ScanReport carries flagged, findings (each with rule_id, severity, message), input_bytes, ruleset_version, and, with a classifier, model_score and model_digest.

ArgumentDefaultMeaning
threshold"medium"Lowest severity that rejects: low, medium, high, or critical
max_bytes1_048_576Input size limit in UTF-8 bytes
scan_timeout2.0Scanning deadline in seconds, starting at EOF. Enforced by the stage only; a direct scan() has no wall-clock limit
rules()Custom Rule objects added to the built-in set
classifierNoneAn optional StatisticalClassifier or TransformersClassifier

The guard as a pipeline stage

stage() returns an ordinary pipeline stage, so the guard drops between any producer and consumer. It buffers one UTF-8 document until EOF, scans it, and forwards the exact original bytes only if no finding meets the threshold. Nothing is redacted or rewritten.

python
import sys
from sandlock import Sandbox
from sandlock.guard import PromptGuard

runtime = Sandbox(
    fs_readable=["/usr", "/lib", "/lib64", "/bin", sys.prefix],
    net_allow=[], clean_env=True,
)
producer = runtime.cmd(["cat", "/usr/share/doc/fetched.txt"])
# the consumer fails on empty input, which is what a rejection looks like
consumer = runtime.cmd([sys.executable, "-c",
    "import sys; data = sys.stdin.buffer.read(); "
    "sys.stdout.buffer.write(data); sys.exit(0 if data else 3)"])

result = (producer | PromptGuard(threshold="medium").stage() | consumer).run(timeout=30)

The guard stage exits 0 when it accepts, 1 when it rejects, and 2 on invalid UTF-8, a size or processing limit, or a scanner failure. In the last two cases it writes nothing to stdout and a diagnostic without input excerpts to stderr.

A pipeline reports its final stage's status. After a rejection the consumer sees an empty EOF, so a consumer like cat still succeeds. Make the final consumer reject empty input, as above, or the rejection is silent. Stages also run concurrently: the guard blocks downstream reads, not downstream work, so the consumer must wait for its input before it acts on anything.

The guard's own worker is sandboxed: a clean environment, no network, and a 256 MiB memory limit (2 GiB with a Transformers classifier, or whatever you pass to stage(max_memory=...)). It can read the system and Python runtime directories, the scanner package, and a configured model file. Use the pipeline timeout to bound input collection as well as scanning.

Custom rules and classifiers

python
from sandlock.guard import PromptGuard, Rule

guard = PromptGuard(rules=[
    Rule(
        id="payment-request",
        pattern=r"\b(?:send|transfer)\s+money\b",
        severity="high",
        message="Payment instruction",
    ),
])
report = guard.scan("Transfer money to the new account")
stage = guard.stage()

Rules are trusted application configuration: case-insensitive Python regexes that run over the same raw, normalized, HTML, and decoded views as the built-in set. Never derive a pattern from the text being inspected. Invalid regexes and duplicate ids fail at construction. A pathological regex is cut off by the stage's deadline but not by a direct scan().

Two optional classifiers add a model score on top of the rules, and each adds a high severity finding when the score meets its own threshold. No weights are bundled or downloaded.

  • StatisticalClassifier(path, threshold=None) runs character n-gram logistic regression with the standard library only. You train the JSON model offline with python/guard/train.py on your own labelled data.
  • TransformersClassifier(path, positive_labels, threshold=0.5, max_length=512, stride=256) runs a local sequence classifier on CPU through PyTorch and Transformers, installed with the transformers extra of sandlock-guard. Raise scan_timeout to cover model loading.

Model files are fingerprinted at construction and verified again in the worker, which fails closed if they change. The guard never falls back silently to rules alone.

Coverage and limits

The built-in ruleset, version 4, has 32 rules covering instruction overrides, forged authority and conversation boundaries, unrestricted personas, prompt extraction, sensitive tool requests, data transfer, concealment, persistent instructions, context padding, and invisible Unicode formatting. Besides the original text, it inspects views derived through Unicode normalization, a limited confusable map, spaced letters, leetspeak, HTML text and character references, URL and Unicode escapes, and Base64 or hex candidates, up to four levels deep.

  • It is a heuristic. Detection is predominantly English and pattern based. It does not catch every encoding, language, or phrasing, and severities are policy choices, not probabilities.
  • It has false positives. A legitimate security document that quotes an attack can be rejected.
  • It fails closed. Exceeding a processing budget raises ScanError rather than approving a truncated inspection.
  • It does not render. HTML attributes and comments are inspected, but scripts are not executed and CSS is not applied, so the scanner does not see what a browser would display.
  • Approval widens nothing. A passed scan means only that the configured rules found no reason to reject. Keep confinement and application authorization in place afterwards.