---
title: "Pre-Inference Guardrails & Prompt DLP: Stopping PII, Secrets & Prompt Injection Before Your LLM"
published: true
description: "How we built a sub-millisecond, zero-bypass Guardrails & Prompt DLP engine in Sarrera with 23 checksum-verified detectors, Cloudflare AI Guardrails taxonomy, Global > User > Group precedence, and SHA-256 SIEM auditing."
tags: ai, security, llm, opensource
When engineering teams adopt AI coding assistants (VS Code Continue, Cline, Roo Code, Cursor) and internal chat portals (Open WebUI), security teams almost always ask the same terrifying question:
"What happens the day a developer pastes a production
.envfile, a customer IBAN, a database URI with credentials, or a real SQL dump into a prompt?"
Even if you self-host your LLMs on-premise, post-hoc auditing is too late:
- The raw secret or PII has already entered the model context window.
- It has already been persisted in observability traces (Langfuse) and object storage (MinIO).
- You now have a GDPR / LOPDGDD / PCI-DSS / NIS2 / DORA compliance incident on your hands.
To solve this at the root, we built a Pre-Inference Guardrails & Prompt DLP (Data Loss Prevention) Engine directly into Sarrera — our open-source, self-hosted Enterprise AI Inference Gateway.
In this post, I'll walk through how the engine works, how we avoid false positives in source code using real mathematical checksums, how policy precedence is enforced (Global > User > Group), and how every incident is logged to a tamper-evident SHA-256 SIEM chain without ever storing raw PII.
Zero-Bypass Edge Architecture
Most gateway guardrails only protect /v1/chat/completions—leaving Open WebUI, /v1/embeddings, or /v1/responses as accidental bypass paths.
In Sarrera, every single inference path flows through the Guardrails Gatekeeper before it touches LiteLLM, Ollama, or Langfuse:
[ VS Code / Cline / Cursor / curl ] [ Open WebUI (Chat Portal) ]
│ │
▼ (HTTPS :443) ▼ (OPENAI_API_BASE_URL)
┌─────────────────┐ │
│ Caddy Edge │─────────────────────────────┤
└─────────────────┘ ▼
┌──────────────────────────────────────┐
│ Sarrera Guardrails & DLP Engine │
│ (Sub-millisecond Pre-Inference) │
│ │
│ 1. Resolve Identity (Key / SSO) │
│ 2. Evaluate Global > User > Group │
│ 3. Run 23 Checksum + AI Detectors │
│ 4. Enforce: BLOCK | REDACT | AUDIT │
└──────┬──────────────────────┬────────┘
│ │ (Async, masked preview only)
┌────────────────────┴──────────┐ ▼
▼ (BLOCK: HTTP 400, 0 GPU) ▼ ┌──────────────────────────┐
[ Immediate Error ] [ Clean Prompt ]│ SHA-256 SIEM Chain (CEF) │
│ └──────────────────────────┘
▼
[ LiteLLM → Ollama → Langfuse ]
Because inspection happens pre-inference:
-
Blocked prompts return an OpenAI-compatible HTTP
400(guardrails_violation) in under a millisecond—consuming zero GPU slots and zero tokens. -
Redacted prompts replace sensitive spans in-place (
[REDACTED:AWS_KEY],[REDACTED:FIN_IBAN]) acrossmessages,prompt, andinputso developers keep working without interruption, while neither the LLM nor Langfuse ever sees the raw secret.
23 Built-In Detectors (With Mathematical Checksums)
Naive regex-only DLP engines are notorious for crying wolf on source code—flagging random 16-digit constants as credit cards or arbitrary strings as IDs.
Sarrera combines Cloudflare Zero Trust DLP Predefined Profiles, Cloudflare AI Gateway Guardrails (P1 + S1–S14), and real mathematical checksum validation to keep false positives near zero:
| Category | Built-In Detectors | Validation & Standards |
|---|---|---|
| National IDs & Health / PHI |
es_dni_nie, es_cif, es_nss, cf_eu_us_national_id, cf_health_phi, pii_email, pii_phone
|
Spanish DNI/NIF & NIE (modulo-23 check letter), CIF control digit, Social Security (NSS) mod-97, US SSN, EU passports, medical/PHI records (GDPR Art. 9 / HIPAA), allowlist-aware emails & phones. |
| Financial (PCI-DSS / DORA) |
fin_iban, fin_credit_card, cf_swift_bic
|
Spanish & SEPA IBAN (ISO 7064 MOD-97), Visa/Mastercard/Amex/Discover (Luhn algorithm), SWIFT/BIC & ABA routing codes. |
| Developer Secrets (OWASP LLM02) |
secret_cloud_api_keys, secret_private_keys, secret_jwt_bearer, secret_db_uri
|
AWS (AKIA/ASIA), Azure SAS/Storage, GCP (AIza), Cloudflare API tokens, GitHub (ghp_/github_pat_), GitLab, Slack, Stripe, OpenAI/Anthropic (sk-), PEM/SSH private keys, JWT/Bearer tokens, DB URIs with embedded passwords. |
AI Guardrails (P1 / S1–S14) |
sec_prompt_injection, sec_obfuscation, cf_safety_harmful, cf_s6_specialized_advice
|
P1 Prompt Injection & Jailbreak (EN & ES), S14 Code Interpreter Abuse / reverse shells / destructive commands & Unicode smuggling, S1–S11 malware/phishing/harmful content, S6 regulated medical/legal/financial advice. |
| Corporate IP & Abuse Limits |
infra_private_ip, corp_confidential_markers, corp_sql_dump, cf_s8_intellectual_property, limit_prompt_size
|
RFC 1918 internal IPs/domains, confidentiality headers, production INSERT INTO SQL dumps, S8 license/DRM bypass markers, and max prompt size caps (Denial of Wallet protection). |
Deterministic Policy Precedence: Global > User > Group
Enterprise security teams often need two operating modes:
- Corporate Lockdown Mode: One strict global policy applies to everyone, everywhere.
- Delegated Mode: Different departments (e.g., Finance, Platform Engineering, R&D) or individual power users have tailored rules.
Sarrera enforces a strict, deterministic precedence hierarchy:
Is Global Policy ACTIVE (`global_policy.enabled == true`)?
├── YES ──▶ Enforce ONLY the Global Policy (User & Group policies are overridden)
└── NO ──▶ Delegated Mode:
1. Does the User have an active policy? ──▶ Enforce User Policy
2. Else, does any of their Groups have an active policy?
──▶ Merge active Group policies using most-restrictive action:
block > redact > audit
3. Otherwise ──▶ Pass-through
Even when Global Policy is active, administrators can still pre-configure User and Group policies in the portal—they display a clear OVERRIDDEN BY GLOBAL indicator so teams can prepare delegated rules safely without weakening corporate enforcement.
Identity (user_id, user_email, groups) is resolved automatically from LiteLLM Virtual API Keys (/key/info + /user/info) and Sarrera SSO headers (X-User-Email, X-User-Groups).
⚡ 3 Enforcement Actions
Every policy defines a default action and supports per-rule overrides:
| Action | Behavior | Best For |
|---|---|---|
block |
Rejects the request immediately with HTTP 400 and a clear explanation. Zero tokens or GPU slots used. |
Secrets, private keys, prompt injection, strict GDPR/PCI-DSS boundaries. |
redact |
Masks sensitive spans in-place ([REDACTED:FIN_IBAN]) before forwarding to LiteLLM, with an optional subtle stream notice. |
Uninterrupted developer flow with automatic PII scrubbing. |
audit |
Lets the request through while logging a masked preview to the incident log and SIEM chain. | Dry-run rollouts and tuning before enforcing blocks. |
Interactive Governance Console & Live DLP Playground
The Sarrera Admin Portal includes a dedicated Guardrails & DLP section (now organized cleanly in the collapsible left sidebar) with four specialized views:
-
Global Policy: Toggle global enforcement, apply 4 one-click Cloudflare/Enterprise Preset Profiles, fine-tune any built-in rule in-place (
min_matchesthresholds, extra regexes, extra keywords, per-rule exceptions, custom redaction tags), create custom rules with a full CRUD editor, and Import/Export policies as JSON. - Group & User Policies: Manage delegated policies per company group or individual user with real-time precedence badges.
-
Live DLP Playground: Test any prompt against a simulated
user_id,group, andmodelwith 1-click realistic test payloads (DNI, IBAN, AWS Key, Prompt Injection, SQL Dump) and inspect the exact effective policy, matched rules, and redacted output before rolling out to production. -
Incident History & KPIs: Real-time counters for blocks, redactions, and audit alerts, with direct deep-linking to Sarrera's SIEM SHA-256 Chain (
/certificates?tab=siem).
Tamper-Evident SHA-256 SIEM Logging (Zero Raw PII Stored)
Every block, redact, or audit event is forwarded asynchronously to POST /auth/compliance/internal-event and appended to Sarrera's cryptographically hash-chained SHA-256 CEF:0 SIEM audit log (prev_hash → entry_hash).
Crucially, raw sensitive values are never stored in logs—only safe masked previews (e.g., 12****78Z or AKIA****MPLE) and rule metadata, keeping your audit trail compliant with GDPR, NIS2, DORA, and ISO 27001.
Built for Scale: Ready for Standalone Extraction
Today, the engine runs in-process inside services/discovery/guardrails_engine.py with sub-millisecond latency and zero extra RAM footprint, persisting policies in a dedicated discovery_data Docker volume.
Need heavy ML/NLP scanners like Microsoft Presidio or ProtectAI LLM Guard down the road? Sarrera already exposes a GUARDRAILS_URL (external_guardrails_url) hook so you can offload scanning to a dedicated ai-guardrails microservice without touching a single line of gateway routing.
Try Sarrera Yourself
Sarrera is 100% open source and runs on Docker Compose:
- GitHub Repository: https://github.com/Sarrera/sarrera
- Guardrails & DLP Documentation: docs/governance-rbac/guardrails-dlp.md
-
Docker Hub (Multi-Arch
amd64/arm64):cloudresources/sarrera-portal:latest,cloudresources/sarrera-discovery:latest,cloudresources/sarrera-auth:latest
How are you protecting against prompt data leakage and secret exposure in your AI coding workflows today? Would love to hear your thoughts and detector ideas in the comments!
Top comments (4)
The note that matters for an agent rarely comes from the person typing. In the triage agent I run it arrives inside a Cypress failure message, as a tool result.
Over 56 runs (
42501583888to46459395874), ministral-3-3b followed the note in 159 of 168 triages. None of it got out. Of 249 outbound calls, 129 were blocked and 120 found no answer for the name, and all 268run_shellcalls were refused by walls that sit after the model, where no detector has to be right.Does the Gatekeeper scan
role: "tool"messages on the way back in, or only what the user sent?Checking for PII, secrets and injection before the prompt ever leaves is the right place for it, since once it's in the provider's logs it's out of your hands. How do you handle false positives on secrets, like a test key in a code snippet someone is asking about?
This is the part of LLM security most teams discover too late. The point about post-hoc auditing being useless really landed for me — once a secret is in the context window and persisted in traces, the incident has already happened, no matter how good the audit logs are.
I especially liked the checksum validation detail. Regex-only DLP is unusable in real codebases precisely because it flags every 16-digit number, and teams just end up turning it off. Validating IBANs with MOD-97 and cards with Luhn is the kind of boring-but-correct engineering that makes a guardrail actually stay enabled.
One thing I'm curious about: with the redact action, does the developer get any signal that their prompt was modified? I can see both sides — silent redaction keeps the flow smooth, but a subtle notice (you mentioned an optional stream notice) seems important so people don't wonder why the model gave a strange answer. Great write-up, and the zero-bypass point about embeddings and /v1/responses is something a lot of gateways miss.
a blocked prompt costing zero gpu and zero tokens is the detail that sells it. most guardrails charge you to say no.