12.10 Security Operations, Incident Response and the Safety Checklist
Lessons 12.1 to 12.9 built the defences: threat models, injection and jailbreak controls, PII handling, guardrails, permission brokers, supply-chain checks, a red-team harness and responsible-AI practice. Defences are necessary but not sufficient. A security control you never watch is a hope, not a control; an incident you have never rehearsed is a surprise you will handle badly at 3 a.m.; and a checklist nobody fills in is decoration. This lesson is the operational layer that makes the rest of the module real: monitoring and detection engineering for security and abuse signals, abuse prevention and enforcement, incident response for the failure modes LLM systems actually have, security embedded in the software development lifecycle, vulnerability management and disclosure, and finally the Safety & Security checklist — a one-page launch gate, a maturity model and a 30/60/90-day hardening plan — plus the module wrap-up that consolidates llm_guard_kit.
What you'll learn
- What to log for security (and what not to), and the catalogue of alerts worth building: detector hits, canary triggers, refusal spikes, tool-call anomalies, cross-tenant denials, PII and secret detections, spend anomalies, probing patterns, exfiltration indicators and guardrail bypass
- Detection engineering for LLM systems: rules as code, thresholds and windows, sampling for human review, SIEM integration, and keeping security logs themselves private
- Abuse prevention: authentication tiers, quotas, per-user safety identifiers for providers, progressive enforcement, CAPTCHA and account-level abuse workflows
- How provider-side abuse systems work — OpenAI's safety identifiers and enforcement notifications, Anthropic's Safeguards warnings and appeals — and how to cooperate with them
- Incident response for LLM-specific incidents: prompt injection, PII exposure, API key leaks, viral harmful output, runaway agents, supply-chain compromise and provider incidents, with severity ratings, evidence preservation, communication templates and three full tabletop exercises
- How security gates fit into the SDLC: threat modelling at design review, secure coding checklists for LLM glue code, CI scanning, kill switches, configuration baselines and security champions
- Vulnerability intake and disclosure:
security.txt, triage SLAs, coordinated disclosure with providers and open-source maintainers, and responsible reporting of model-level vulnerabilities - The one-page Safety & Security checklist usable as a launch gate, a maturity model from level 0 to 4, and a 30/60/90-day hardening plan
- Decision tables routing each alert to its playbook, a failure gallery of security-operations failure modes, and the metrics (MTTD, MTTR, alert precision, detection coverage) that prove detection works
- The consolidated
llm_guard_kitpackage and what this module — and the field — still hasn't solved
What you don't need
- API keys or model calls. Every sample in this lesson is pure Python on fixtures you can generate yourself; nothing touches a provider, a database or a network. The monitoring and alerting code runs entirely on local JSON Lines fixtures.
- A SOC, a SIEM product or an on-call rotation. You will learn the patterns that SIEMs implement, and how to write the detection rules yourself in plain Python. If your organisation already runs Splunk, Elastic or Microsoft Sentinel, the same rules port to it.
- Legal training. Regulatory references (GDPR breach clocks, the EU AI Act timeline) are awareness-level orientation, dated and cited; they are not legal advice. Lesson 12.9 owns the compliance depth.
- Incident-response experience in classic IT. The lifecycle is reviewed briefly and then specialised for LLM failure modes.
Setup
This lesson needs only Python 3.11+ and the standard library. If you are continuing the module's guardrails project (llm_guard_kit), create it once:
uv init guardrails --bare --python 3.13 && cd guardrails
uv add pydantic python-dotenv # only for the module's earlier files; secops.py itself needs neitherNo .env keys are needed — the samples below are offline. The one code file, secops.py, is shown in full (split across blocks) in Part 1.6, and appears in the module appendix's package table. Earlier module files it builds on — the canary-token helpers in injection.py (12.2) and the permission broker's audit log in permissions.py (12.6) — are pure Python and need no services.
What you must be able to do after this lesson#
- Decide what to log for security and what to leave out
- Write a detection rule with windows and per-actor baselines
- Apply a response ladder to an abuse case and pass safety_identifier to providers
- Run the incident playbook for prompt injection, PII exposure or a leaked key
- Use the one-page checklist as a launch gate
Why this matters for an AI engineer#
| You'll hear... | You'll understand it after... |
|---|---|
| "We have guardrails, so we're covered." | Part 1: a control nobody measures is a hope |
| "Alert when the injection detector fires." | 1.3 The detection catalogue and 1.4 Detection engineering |
| "Our logs contain the prompts — that's how we debug." | 1.5 Privacy of security logs |
| "Someone is hammering the API with near-identical prompts." | 2.2–2.4: quotas, progressive enforcement, safety identifiers |
| "OpenAI emailed us about policy violations on our org." | 2.3 Provider-side abuse systems |
| "A customer's screenshot of a bad answer is going viral." | 3.3 Playbook: harmful-output incident |
| "We leaked PII through a RAG answer — what now?" | 3.3 Playbook: data leak / PII exposure and the GDPR 72-hour clock in 3.5 |
| "The agent deleted records it shouldn't have." | 3.3 Playbook: agent misbehaviour |
| "Which severity is this?" | 3.2 The severity matrix |
| "Ship it — security review later." | Part 4: gates by phase, CI checks, kill switches |
| "A researcher emailed us a vulnerability." | Part 5: intake, SLAs, coordinated disclosure |
| "Is our security posture mature?" | 6.2 The maturity model and the checklist in 6.1 |
Part 1: Monitoring and detection engineering for security and abuse#
1.1 What earlier lessons already own#
Two modules already built the operational plumbing this lesson stands on:
- Module 11A owns observability itself: traces, spans and what to capture per call (its tracing lesson), metrics, SLOs, dashboards and operational alerting (its metrics lesson), cost monitoring, and the general incident lifecycle and runbook format (its operations lesson). If your team already has a tracing platform — Langfuse, LangSmith, Arize Phoenix, Datadog LLM Observability, Helicone, or OpenTelemetry GenAI spans — this lesson assumes it exists and adds the security-specific signals on top.
- Module 10A owns quality monitoring: online evaluation, sampling production traffic for judging, and detecting silent quality regressions. A safety incident is not a quality regression; the metrics are different and so are the responders.
- Lesson 03.10 owns the logging mechanics: structured JSON logs, correlation IDs, content redaction and what fields to record per call. Lesson 03.7 owns the cost records. This lesson consumes those fields; it does not re-teach how to emit them.
What this lesson adds is the security telemetry plane: which signals indicate attack or abuse rather than malfunction, how to turn them into alerts that a human can act on, and what to do when one fires. The mental model: availability alerts say "the system is broken"; security alerts say "someone may be doing this on purpose". They need different data, different thresholds and different responders.
1.2 The security event stream#
Detection engineering starts with events. Your application already emits most of them; the job is to make sure the fields needed for security analysis are present, then route them to somewhere you can query at incident time.
The canonical security event for an LLM call extends the log line 03.10 defines with security-relevant fields:
{
"ts": "2026-11-06T02:14:31.208Z",
"event": "llm.call",
"request_id": "req_8f21c0",
"trace_id": "4bf92f3577b34da6a3ce929d0e0e4736",
"feature": "support-copilot",
"user_ref": "u_a91f", // pseudonymous: HMAC per 03.2's scheme, never raw PII
"tenant": "acme-corp",
"model_key": "anthropic/claude-haiku-5-5",
"resolved_model": "claude-haiku-5-5-20261001", // illustrative snapshot id — format only, not a pinned model
"prompt_version": "v14",
"guardrails": {
"input_scan": "clean",
"injection_score": 0.03,
"moderation": "allow",
"pii_findings": 0,
"canary_hits": []
},
"tool_calls": [
{"name": "search_docs", "args_hash": "9c1f...", "risk_tier": "read", "approved": null}
],
"egress": {"urls_requested": [], "domains_allowed": true},
"outcome": "ok",
"finish_reason": "stop",
"refusal": false,
"usage": {"input_tokens": 1840, "output_tokens": 212, "cost_usd": 0.0011},
"latency_ms": 1840
}Every field earns its place in an investigation:
| Field | Security question it answers |
|---|---|
request_id, trace_id |
Correlate this call with the trace, the tool calls it spawned, and the guardrail decisions — the backbone of 03.10's correlation scheme |
user_ref, tenant |
Attribute abuse to an account without storing their identity in the security pipeline (pseudonymity per 03.2, 10.3); cross-tenant questions need tenant |
prompt_version, model_key, resolved_model |
"Did the new prompt or model change introduce this?" — the first question in every post-incident review |
guardrails.* |
Which controls saw this request and what they decided; a clean input scan followed by a canary hit is itself a signal (detector evasion) |
tool_calls with risk_tier and approved |
The 12.6 permission broker's audit trail: what the agent wanted to do, at what risk tier, and whether a human approved it. The broker's own AuditEvent records decision, approver and grant_id and keeps the tool arguments, so your normaliser sets risk_tier from the tool's RiskTier value (read, write, external, irreversible), sets approved when an approver or a session grant is present, and drops args (keeping only args_sha256) before the event enters the security path |
egress |
Whether the model (or an injected instruction) tried to reach outside — domains, counts, allow-list verdicts |
outcome, finish_reason, refusal |
Distinguishes attacks that succeeded from attempts that failed; refusal spikes are an abuse signal (12.3) |
usage.cost_usd |
Denial-of-wallet detection (12.5 covers prevention; here it's a detection input) |
Two deliberate omissions matter as much as the fields:
- No raw prompt or completion text in the security stream. Content lives in the tracing platform under its own access controls and retention (1.5); the security pipeline gets metadata, scores, hashes and canary identifiers. When an investigation needs content, it is fetched deliberately, access-logged, and time-boxed — not streamed to every dashboard.
- No secrets, ever. 12.7 owns key handling; the security event schema simply has no field that could carry one.
1.3 The detection catalogue#
This is the heart of the lesson: the signals worth alerting on, what each one means, and what to do when it fires. Signals fall into four families: attack indicators (someone is trying something), abuse indicators (a legitimate account doing illegitimate volume or pattern), control failures (a defence misfired or was bypassed), and business anomalies (cost/usage patterns that may be attack or may be growth — these need human judgement).
| # | Signal | What it detects | Typical source | First response |
|---|---|---|---|---|
| 1 | Canary-token trigger | System-prompt or document canary leaked into output, or canary URL/domain hit | 12.2 canary helpers; Thinkst-style tokens | Treat as confirmed exfiltration attempt: pull trace, identify channel, check blast radius |
| 2 | Injection/jailbreak detector hit | Input or output classifier flagged injection, jailbreak or policy-violating content | guards.py input/output scans; provider moderation; Llama Prompt Guard-class models |
Log + sample for review; correlate with user and outcome |
| 3 | Refusal spike | Sudden rise in refusal rate for a user, tenant or globally | finish_reason/refusal fields; provider safety-block signals |
Possible probing or policy-boundary exploration; review account |
| 4 | Tool-call anomaly | Tool outside the session's allow-list, argument outside semantic bounds, or unusual sequence (e.g. read→exfil→write) | permissions.py audit log; agent tracer |
Highest-severity class for agents: possible successful injection-driven action |
| 5 | Cross-tenant access denial | Repeated ACL/filter denials for one user or one query pattern | Retrieval ACL logs (06.6); permission broker | Enumeration attempt or broken ACL — verify which |
| 6 | PII/secret detection | PII scanner or secret scanner fired on input, output, trace or log | pii.py, supply_chain.py scanners |
Confirm redaction path ran; if output carried PII to a user, escalate toward incident |
| 7 | Spend/token anomaly | Cost or tokens per user/tenant/feature deviates sharply from baseline | cost_tracker records (03.7) |
Denial-of-wallet or runaway agent loop; throttle and inspect |
| 8 | Probing pattern | Many near-duplicate prompts, systematic boundary testing, encoding variations | Prompt-hash clustering in the security pipeline | Automated red-team or hostile user; correlate with account age |
| 9 | Exfiltration indicator | Model output or agent action referenced non-allow-listed domains/URLs, or outbound tool calls to unusual destinations | egress field; markdown/link sanitiser logs |
Possible successful injection exfil channel; check what left |
| 10 | Guardrail bypass signal | Guardrail denied, then a near-identical request succeeded; or detector score distribution shifts | Guardrail decision logs vs outcomes | Adaptive attack or detector drift; raise review sampling |
| 11 | Authentication/authorisation anomaly | Failed auth spikes, token reuse across tenants, impossible-travel-style session patterns | API gateway / IdP logs | Credential stuffing or token theft — classic AppSec, feeds the same queue |
| 12 | Abuse-report volume | Users reporting the bot (thumbs-down abuse reports, support tickets citing harmful output) | Product feedback pipeline | Harmful-output incident candidate; see 3.3 |
A few notes on reading the table like an engineer:
- Single signals are noisy; combinations are signal. One injection-detector hit on a support ticket that contains the phrase "ignore previous instructions" quoted in a bug report about prompt injection is a false positive. The same hit plus a canary trigger plus an outbound URL to an unknown domain is an incident. Build correlation rules, not just threshold alerts.
- Score everything, alert on the tail. Modern guardrails emit scores (injection probability, moderation categories). Log the score on every request — it's cheap — but alert on sustained high scores or score jumps, not single mid-range values, unless the consequence of a miss is severe.
- Baseline before you alert. "Refusal spike" only means something against that feature's normal refusal rate. A coding assistant that refuses 2% of requests alerting at >5% is different from a general chatbot at 15% baseline. Measure your own baselines during quiet periods and encode them as the alert thresholds.
- Sampling beats exhaustiveness for review. You cannot human-review every flagged event. Sample: 100% of canary triggers and tool anomalies (rare, high-severity), a few percent of detector hits (to measure false-positive rate), and everything above a severity score. 1.4 shows the mechanics.
1.4 Detection engineering: rules as code#
The craft of detection engineering is treating alerts as software: versioned, tested, reviewed and retired. The loop:
flowchart LR
subgraph sources ["Event sources"]
A["App security events<br/>(JSONL / OTel)"]
B["Guardrail decisions<br/>(guards.py, pii.py)"]
C["Permission broker audit<br/>(permissions.py)"]
D["Provider signals<br/>(moderation, safety blocks)"]
E["Infra/auth logs<br/>(gateway, IdP)"]
end
sources --> F["Normalise to<br/>security-event schema"]
F --> G["Rules engine<br/>windowed thresholds +<br/>correlation + baselines"]
G --> H{"Severity"}
H -->|"page-worthy"| I["Page on-call<br/>(PagerDuty/Opsgenie-class)"]
H -->|"queue"| J["SOC queue<br/>(SIEM case mgmt)"]
H -->|"sample"| K["Human review sample<br/>(weekly FP audit)"]
I --> L["Runbook<br/>(Part 3 playbooks)"]
J --> L
L --> M["Post-incident:<br/>new regression test<br/>(12.8, Module 10A)"]
M -.->|"tune or retire"| GRules as code. Write each detection as data, not as a one-off query: a name, a description, the event kinds it consumes, a window (e.g. "per user per 10 minutes"), a threshold, a severity, and a runbook link. Store them in version control beside the code they monitor, unit-test them against fixtures (the 1.6 engine does exactly this), and review them when the threat model changes. When you deploy to a SIEM — Splunk, Elastic Security, Datadog Security, or Microsoft Sentinel (which as of November 2026 lives in the Microsoft Defender portal; the Azure-portal experience retires in March 2027) — the same rule logic ports to the platform's query language, but the rule definition remains yours.
Thresholds and windows. Almost every LLM security signal is a rate, not an event: refusals per hour, detector hits per user per day, spend delta per hour. Encode the window explicitly (per user, rolling 10 minutes) so a burst and a slow drip produce different alerts — they are different attacks. For spend specifically, a z-score over the trailing baseline catches "3× normal spend" without hard-coding a dollar figure that rots as you grow.
Dedup and suppression. One attack generates hundreds of events. Group alerts by (rule, user_ref, tenant, window) so a probing run produces one case, not four hundred pages. Suppress re-alerts while a case is open, and always record that suppression happened — "we knew and chose not to re-page" is an auditable decision.
Human review sampling. For noisy detectors, route a random sample of non-alerting traffic and of low-severity hits to a review queue. The weekly question "of the events we didn't alert on, how many should we have?" is how you measure detector recall; the false-positive rate comes from reviewing the alerts themselves. Both numbers belong on the security dashboard next to the alert count.
Detection coverage review. Quarterly, walk the 12.1 threat model and ask of each threat: what event would tell us this is happening? If the answer is "nothing", that's a monitoring gap — often the most valuable output of a security review. Map each catalogue signal to the OWASP LLM Top 10 2026 entries it covers (see 6.6 for the current list).
The metrics that prove it works. Detection without measurement is faith. Four numbers turn "we have alerts" into "we know our detection works" — all computable from the event schema and alert records above:
| Metric | Definition | Where the number comes from |
|---|---|---|
| MTTD — mean time to detect | Elapsed time from the first malicious or abusive event's ts to the alert that surfaced it |
Security-event ts vs alert creation timestamp |
| MTTR — mean time to respond | Alert fired → containment action completed. Pick one endpoint (acknowledge, contain or recover), label it consistently, and keep it separate per severity | Alert timestamp vs the runbook action recorded in the audit log |
| Alert precision | Share of reviewed alerts confirmed as true positives — the complement of the false-positive rate | Verdicts from the human-review sampling described above |
| Detection coverage | Share of threat-model threats that have at least one live detection rule | The quarterly coverage review walked against the 12.1 threat model |
Track MTTD and MTTR per severity, not only globally — a fast SEV-1 response hiding a slow SEV-3 queue is exactly the kind of average that lies. Precision and coverage are the pair that tells you whether to add rules or tune them: perfect precision with 20% coverage means you're blind to most of the catalogue, and 100% coverage with 5% precision means your queue is noise. Both numbers belong on the security dashboard next to the alert count, reviewed on the same cadence as the coverage walk.
1.5 Privacy of security logs#
Security telemetry is itself sensitive: it records who did what, when, with which account — a targeting list for an attacker who breaches your logging pipeline. The controls:
- Pseudonymous identifiers.
user_refis an HMAC of the internal user ID under a peppered key, per 03.2, 10.3 — stable enough to correlate abuse across days, unlinkable to a person without the pepper. The pepper lives in the secret manager, never in the logging path. - No content in the security path. Scores, hashes, counts and canary IDs — not prompts, completions or retrieved documents. When investigation needs content, fetch it from the product path under access control and log that access.
- Retention limits. Security events need longer retention than product traces (you investigate breaches weeks later) but not infinite retention. Set an explicit schedule — 90 days hot, 1 year cold is a common pattern — and honour deletion requests across the security store too (12.4 owns the privacy mechanics).
- Access control and audit. Who can query the security pipeline is itself a security decision: role-based access, query logging, and no standing access for contractors. A SIEM analyst browsing raw events should leave a record.
- Encryption. In transit and at rest, like every other store holding user-linked data. The marginal cost is zero; the breach cost is not.
- Export control. The security event schema is a contract: adding a field requires the same review as adding a column to a database. A
prompt_textfield "just for debugging" is how PII ends up in the SIEM.
The boundary in one picture — what crosses from the product path into the security path, and where content is stripped:
flowchart TB
subgraph rt ["Application runtime"]
H["LLM call handler"]
G["Guardrails · permission broker · detectors"]
end
subgraph pp ["Product / ops path"]
T["Traces and logs:<br/>prompts, completions, retrieved docs —<br/>full fidelity, access-controlled"]
end
subgraph sp ["Security path"]
E["Security events:<br/>scores, hashes, counts, pseudonymous IDs<br/>(no content fields)"]
R["Rules engine → severity →<br/>on-call / SOC queue"]
E --> R
end
H -->|"full record"| T
H -->|"schema fields only —<br/>content stripped at emission"| E
G -->|"decisions, scores, audit entries"| E
T -.->|"content fetched deliberately:<br/>access-controlled + access-logged"| I["Investigator"]
R --> IThe trust boundary sits at event emission: the security event is built from the schema in 1.2, which has no field that could carry content, so nothing downstream — the rules engine, the SIEM, a dashboard, an export — can leak what was never admitted. Content still exists, but only on the product path, behind its own access controls, and reaches an investigator only through a deliberate, logged fetch.
1.6 Try it: an alert engine over a trace fixture#
Everything above is implementable in ~200 lines of standard-library Python. The file llm_guard_kit/secops.py defines the canonical event, a rule engine with windowed thresholds and z-score baselines, the detection catalogue as data, and a fixture generator that emits a realistic attack day. It runs with no network, no keys and no dependencies.
# secops.py — security-event schema, alert rules engine and a fixture day.
# Part of llm_guard_kit (Module 12). Stdlib only.
from __future__ import annotations
import hashlib
import hmac
import json
import statistics
from collections import defaultdict
from dataclasses import dataclass, field
from datetime import datetime, timedelta
from typing import Callable
# ---------------------------------------------------------------- events
@dataclass
class SecurityEvent:
"""One normalised security event. Content fields are deliberately absent:
the security pipeline carries metadata, scores and hashes only."""
ts: datetime
kind: str # e.g. "llm.call", "guardrail.decision", "tool.call"
request_id: str = ""
user_ref: str = "" # pseudonymous (HMAC), never a raw user id
tenant: str = ""
feature: str = ""
detail: dict = field(default_factory=dict)
@classmethod
def from_jsonl(cls, line: str) -> "SecurityEvent":
d = json.loads(line)
d["ts"] = datetime.fromisoformat(d["ts"].replace("Z", "+00:00"))
return cls(**d)
def prompt_hash(text: str, pepper: bytes) -> str:
"""Stable handle for near-duplicate detection. Keyed (HMAC), because a plain
hash lets anyone who steals the security store confirm a guessed prompt by
hashing it. Keep the pepper in the secret manager, like the user_ref pepper."""
return hmac.new(pepper, text.strip().lower().encode(), hashlib.sha256).hexdigest()[:16]
# ---------------------------------------------------------------- rules
@dataclass
class Alert:
rule: str
severity: str # "page" | "queue" | "info"
message: str
count: int
window: str
sample_refs: list = field(default_factory=list)
@dataclass
class Rule:
"""A detection rule: which events, over what window, above what threshold."""
name: str
severity: str
kinds: set[str]
predicate: Callable[[SecurityEvent], bool]
threshold: int
window_seconds: int
key: Callable[[SecurityEvent], str] = lambda e: e.user_ref or e.tenant or "global"
message: str = ""
def evaluate(self, events: list[SecurityEvent]) -> Alert | None:
"""Evaluate over the window ending at the newest event in the batch.
In production this runs continuously per arriving window; here the
batch stands in for 'now'."""
if not events:
# Silence from the event feed means the pipeline is down, not that
# all is well; make the caller handle it instead of "no alerts".
raise ValueError("no events to evaluate: check the event feed")
window = timedelta(seconds=self.window_seconds)
latest = max(e.ts for e in events)
in_window = [e for e in events
if e.kind in self.kinds and self.predicate(e)
and latest - e.ts <= window]
groups: dict[str, list[SecurityEvent]] = defaultdict(list)
for e in in_window:
groups[self.key(e)].append(e)
worst_key, worst = max(groups.items(), key=lambda kv: len(kv[1]), default=("", []))
if len(worst) < self.threshold:
return None
return Alert(
rule=self.name, severity=self.severity,
message=self.message or f"{self.name}: {len(worst)} events for {worst_key}",
count=len(worst), window=f"{self.window_seconds}s",
sample_refs=[e.request_id for e in worst[:3]],
)The catalogue from 1.3 maps to rules — each event's nested §1.2 schema fields arrive flattened into the event's detail dict. Here are the highest-value ones, written as data:
# The detection catalogue, expressed as rules. `detail` is the flattened
# form of the security-event schema in 1.2 — e.g. detail["canary_hits"]
# (from guardrails.canary_hits), detail["injection_score"]
# (from guardrails.injection_score), detail["cost_usd"] (from usage.cost_usd).
def _num(value: object) -> float:
"""A score as a float; anything that is not a real number counts as NaN,
which the rules above treat as 'over the threshold'."""
if isinstance(value, bool) or not isinstance(value, (int, float)):
return float("nan") if value is not None else 0.0
return float(value)
RULES: list[Rule] = [
Rule(
name="canary-trigger", severity="page",
kinds={"guardrail.decision"},
predicate=lambda e: bool(e.detail.get("canary_hits")),
threshold=1, window_seconds=3600, key=lambda e: e.user_ref or "global",
message="Canary token appeared in output — possible prompt-leak or exfiltration",
),
Rule(
name="injection-detector-cluster", severity="queue",
kinds={"guardrail.decision"},
# "not score < 0.8", not "score >= 0.8": a NaN from a broken detector must
# alert, not slide under the bar.
predicate=lambda e: not _num(e.detail.get("injection_score")) < 0.8,
threshold=3, window_seconds=600,
message="Repeated high injection scores — possible probing",
),
Rule(
name="refusal-spike", severity="queue",
kinds={"llm.call"},
predicate=lambda e: bool(e.detail.get("refusal")),
threshold=5, window_seconds=3600, key=lambda e: e.user_ref,
message="Refusal rate spike for one account — possible policy-boundary probing",
),
Rule(
name="unapproved-high-tier-tool", severity="page",
kinds={"tool.call"},
# Tier names are permissions.py's RiskTier values (12.6): "external" is the
# approval-required tier, "irreversible" the one that may be disabled outright.
# Case-folded tier, and "approved" must be a real True: the string "false"
# is truthy and "External" is not "external"; either would hide the call.
predicate=lambda e: (str(e.detail.get("risk_tier", "")).lower()
in {"external", "irreversible"}
and e.detail.get("approved") is not True),
threshold=1, window_seconds=3600,
message="High-risk tool call without recorded approval",
),
Rule(
name="cross-tenant-denial-burst", severity="queue",
kinds={"retrieval.acl_denied"},
predicate=lambda e: True,
threshold=20, window_seconds=600,
message="Burst of cross-tenant access denials — enumeration or broken ACL",
),
Rule(
name="pii-in-output", severity="page",
kinds={"guardrail.decision"},
predicate=lambda e: (e.detail.get("pii_findings") or 0) > 0
and e.detail.get("channel") == "output",
threshold=1, window_seconds=3600,
message="PII detected in model output — possible leakage",
),
Rule(
name="prohibited-egress-domain", severity="page",
kinds={"egress.attempt"},
# A missing "domain_allowed" is an unchecked egress, not an allowed one.
predicate=lambda e: e.detail.get("domain_allowed") is not True,
threshold=1, window_seconds=3600,
message="Outbound request to non-allow-listed domain",
),
]Two detectors don't fit the count-in-window shape and are implemented as functions over the whole batch:
# --- Spend anomaly: median/MAD against the actor's own baseline -------------
def spend_anomalies(events: list[SecurityEvent],
bucket_seconds: int = 300,
min_buckets: int = 4,
sigma: float = 3.0) -> list[Alert]:
"""Flag actors whose most recent cost bucket is >sigma MAD-scores above
their own baseline. Per-actor baselines avoid alerting on your biggest
customer; median/MAD resists the heavy tail of legitimate bursts."""
buckets: dict[str, dict[int, float]] = defaultdict(lambda: defaultdict(float))
alerts = []
bad_cost: list[str] = []
for e in events:
if e.kind != "llm.call" or "cost_usd" not in e.detail:
continue
cost = e.detail["cost_usd"]
# NaN, infinity, negatives and strings would poison a bucket (a NaN sum
# makes every later score NaN, and "nan > sigma" is False: no alert ever).
if (isinstance(cost, bool) or not isinstance(cost, (int, float))
or not 0 <= cost < float("inf")):
bad_cost.append(e.request_id)
continue
b = int(e.ts.timestamp() // bucket_seconds)
buckets[e.user_ref][b] += cost
if bad_cost:
alerts.append(Alert(
rule="spend-data-invalid", severity="queue",
message=f"{len(bad_cost)} llm.call events carry a cost that is not a "
"finite number >= 0: spend detection is blind for them",
count=len(bad_cost), window="batch", sample_refs=bad_cost[:3]))
for actor, series in buckets.items():
if len(series) < min_buckets:
continue
values = sorted(series.values())
med = statistics.median(values)
mad = statistics.median([abs(v - med) for v in values]) or 1e-9
latest_b = max(series)
score = (series[latest_b] - med) / (1.4826 * mad)
if score > sigma:
alerts.append(Alert(
rule="spend-anomaly", severity="queue",
message=f"Spend {score:.1f} MAD-scores above baseline "
f"(${series[latest_b]:.2f} vs median ${med:.2f}/"
f"{bucket_seconds}s)",
count=1, window=f"{bucket_seconds}s", sample_refs=[actor],
))
return alerts
# --- Probing pattern: near-duplicate prompts --------------------------------
def probing_clusters(events: list[SecurityEvent],
min_cluster: int = 8) -> list[Alert]:
"""Group llm.call events by prompt_hash per user; a large cluster of
*distinct request_ids* sharing one hash family is systematic probing.
(Exact-hash clusters catch retries and copy-paste probing; a prober who
varies one word needs normalisation or embedding clustering, as in Module 06 —
this catches the dumb version, which is most of it.)"""
clusters: dict[tuple[str, str], set[str]] = defaultdict(set)
for e in events:
if e.kind == "llm.call" and e.detail.get("prompt_hash"):
clusters[(e.user_ref, e.detail["prompt_hash"])].add(e.request_id)
return [Alert(
rule="probing-pattern", severity="queue",
message=f"{len(rids)} requests sharing prompt hash "
f"{ph[:8]}… for {user}",
count=len(rids), window="session",
sample_refs=sorted(rids)[:3],
) for (user, ph), rids in clusters.items() if len(rids) >= min_cluster]Now the fixture: one simulated day containing normal traffic, a probing account, a successful-looking injection attempt, and a cost anomaly. Run it and see which rules fire.
# fixture_day.py — emit a realistic JSONL security-event day (~55 min).
from datetime import datetime, timedelta, timezone
T0 = datetime(2026, 11, 5, 9, 0, tzinfo=timezone.utc)
def ev(offset_s, kind, user, **detail):
return {
"ts": (T0 + timedelta(seconds=offset_s)).isoformat().replace("+00:00", "Z"),
"kind": kind,
"request_id": f"req_{offset_s:06d}",
"user_ref": user,
"tenant": "acme-corp" if user.startswith("u_") else "internal",
"feature": "support-copilot",
"detail": detail,
}
def day() -> list[dict]:
events = []
# Normal morning traffic: three users, ordinary calls spread over ~40 min.
for i, user in enumerate(["u_a91f", "u_b22c", "u_c07d"]):
for j in range(30):
events.append(ev(i * 700 + j * 80, "llm.call", user,
prompt_hash=f"h{(i*30+j) % 97:04d}",
cost_usd=0.001 + 0.0004 * ((i + j) % 5),
refusal=False))
# u_flood baseline: normal-rate calls first (so the spike has a baseline to beat).
for j in range(30):
events.append(ev(100 + j * 70, "llm.call", "u_flood",
prompt_hash=f"hbase{j:03d}",
cost_usd=0.002, refusal=False))
# Probing account u_evil: 14 near-identical calls, refusals on every other one.
for j in range(14):
events.append(ev(2600 + j * 15, "llm.call", "u_evil",
prompt_hash="hprob",
cost_usd=0.002, refusal=(j % 2 == 0)))
events.append(ev(2601 + j * 15, "guardrail.decision", "u_evil",
injection_score=0.91 if j % 2 else 0.55))
# The probing turns into a real attempt: canary hit, bad egress, PII in output.
events.append(ev(2900, "guardrail.decision", "u_evil",
canary_hits=["canary-sys-7f3a"], injection_score=0.97))
events.append(ev(2901, "egress.attempt", "u_evil",
domain_allowed=False, domain="exfil.example.com"))
events.append(ev(2902, "guardrail.decision", "u_evil",
pii_findings=2, channel="output"))
# Denial-of-wallet: u_flood spikes to ~45x baseline spend in one bucket.
for j in range(60):
events.append(ev(3000 + j * 4, "llm.call", "u_flood",
prompt_hash=f"hflood{j % 20:02d}",
cost_usd=0.09, refusal=False))
# Unapproved irreversible tool call by an agent session.
events.append(ev(3300, "tool.call", "u_agent01",
risk_tier="irreversible", approved=False,
tool="delete_records"))
# Cross-tenant ACL denial burst (broken filter or enumeration).
for j in range(25):
events.append(ev(3400 + j * 4, "retrieval.acl_denied", "u_a91f",
tenant="other-tenant"))
return eventsAnd the runner that evaluates every rule plus the two function detectors over the fixture (run it from the project root with python -m llm_guard_kit.run_secops_demo — it lives inside the package and imports llm_guard_kit.*, so python llm_guard_kit/run_secops_demo.py fails):
# run_secops_demo.py — evaluate all rules over fixture_day() and print alerts.
import json
from llm_guard_kit.secops import (Alert, RULES, SecurityEvent,
probing_clusters, spend_anomalies)
from llm_guard_kit.fixture_day import day
def main() -> None:
raw = [json.dumps(e) for e in day()]
events = [SecurityEvent.from_jsonl(line) for line in raw]
print(f"evaluating {len(events)} events, {len(RULES)} rules\n")
alerts: list[Alert] = []
for rule in RULES:
a = rule.evaluate(events)
if a:
alerts.append(a)
alerts += spend_anomalies(events) + probing_clusters(events)
for a in sorted(alerts, key=lambda x: {"page": 0, "queue": 1, "info": 2}[x.severity]):
print(f"[{a.severity.upper():5}] {a.rule:28} x{a.count:<3} "
f"({a.window}) {a.message}")
for ref in a.sample_refs:
print(f" e.g. {ref}")
if __name__ == "__main__":
main()Output (real — ran locally; pure standard library, deterministic — yours will match):
evaluating 237 events, 7 rules
[PAGE ] canary-trigger x1 (3600s) Canary token appeared in output — possible prompt-leak or exfiltration
e.g. req_002900
[PAGE ] unapproved-high-tier-tool x1 (3600s) High-risk tool call without recorded approval
e.g. req_003300
[PAGE ] pii-in-output x1 (3600s) PII detected in model output — possible leakage
e.g. req_002902
[PAGE ] prohibited-egress-domain x1 (3600s) Outbound request to non-allow-listed domain
e.g. req_002901
[QUEUE] refusal-spike x7 (3600s) Refusal rate spike for one account — possible policy-boundary probing
e.g. req_002600
e.g. req_002630
e.g. req_002660
[QUEUE] cross-tenant-denial-burst x25 (600s) Burst of cross-tenant access denials — enumeration or broken ACL
e.g. req_003400
e.g. req_003404
e.g. req_003408
[QUEUE] spend-anomaly x1 (300s) Spend 1818.4 MAD-scores above baseline ($5.40 vs median $0.01/300s)
e.g. u_flood
[QUEUE] probing-pattern x14 (session) 14 requests sharing prompt hash hprob… for u_evil
e.g. req_002600
e.g. req_002615
e.g. req_002630Read the output like an investigator. Four page-severity alerts fired on the attempted exfiltration chain: the canary appeared in output, the model tried a non-allow-listed domain, PII reached the output channel, and an agent attempted an irreversible tool call with no recorded approval. Those four together describe one coherent attack story — which is why correlation beats counting. The queue items are the supporting evidence: the refusal spike and probing cluster fingerprint u_evil as a systematic tester, the ACL-denial burst flags u_a91f's session as either enumeration or a broken filter (a defender bug masquerading as an attack — always check which), and the spend anomaly catches u_flood's denial-of-wallet attempt.
Two rules deliberately did not fire, and that's instructive. injection-detector-cluster needs ≥3 high-score decisions inside 10 minutes of "now"; the fixture's scores were spread thinly enough that only the canary event qualified — density matters, so tune window_seconds and threshold against your own traffic, not this toy. And every alert above is only as good as the events feeding it: an egress.attempt event can only exist if your output handler records attempted outbound references — which loops back to 12.5's sanitiser emitting the event in the first place.
Test the rules against evasion, not only against the fixture day. A detection rule fails silently: no alert looks exactly like no attack. These four tests cover events that hid an attack from earlier versions of the rules: a risk tier written External and an approval recorded as the string "false" (truthy), an egress event with no domain verdict, a NaN injection score (nan >= 0.8 is false, so the old comparison never fired) and a NaN cost that poisoned a spend bucket. Save as test_secops.py:
# test_secops.py — events that would have hidden an attack from earlier rules.
# Run from the project root: python3 -m unittest test_secops -v
import unittest
from datetime import datetime, timezone
from llm_guard_kit.secops import RULES, SecurityEvent, spend_anomalies
NOW = datetime(2026, 11, 12, 9, 0, tzinfo=timezone.utc)
def event(kind: str, **detail) -> SecurityEvent:
return SecurityEvent(NOW, kind, request_id="req_1", user_ref="u_1", detail=detail)
def fired(*events: SecurityEvent) -> set[str]:
return {rule.name for rule in RULES if rule.evaluate(list(events))}
class RuleEvasionTests(unittest.TestCase):
def test_a_tier_name_in_another_case_or_a_string_approval_still_alerts(self):
self.assertIn("unapproved-high-tier-tool",
fired(event("tool.call", risk_tier="External", approved="false")))
self.assertNotIn("unapproved-high-tier-tool",
fired(event("tool.call", risk_tier="external", approved=True)))
def test_an_egress_event_without_a_verdict_is_not_treated_as_allowed(self):
self.assertIn("prohibited-egress-domain", fired(event("egress.attempt")))
def test_a_nan_injection_score_counts_as_over_the_threshold(self):
nan = float("nan")
self.assertIn("injection-detector-cluster",
fired(*[event("guardrail.decision", injection_score=nan)] * 3))
def test_a_nan_cost_is_reported_not_swallowed(self):
rules = [a.rule for a in spend_anomalies([event("llm.call", cost_usd=float("nan"))])]
self.assertEqual(rules, ["spend-data-invalid"])
if __name__ == "__main__":
unittest.main()Run python3 -m unittest test_secops -v and you get real output:
....
----------------------------------------------------------------------
Ran 4 tests in 0.000s
OKWhat the rules still do not do: spend_anomalies needs at least four buckets of history per account, so a brand-new account that floods spend from its first minute is caught by a per-account quota (12.5, Part 8), not by this rule; probing_clusters matches exact prompt hashes only; and every rule trusts the fields the application writes into the event, so a bug that stops writing a field is itself a blind spot to alert on.
Part 2: Abuse prevention and response#
2.1 Abuse is different from an incident#
Everything in Part 1 assumed an adversary attacking your system. Abuse is the mirror image: an adversary using your system as designed for purposes you didn't intend. The distinction matters operationally:
| Security incident | Abuse case | |
|---|---|---|
| What happened | A control failed or was bypassed | Controls worked; the purpose was illegitimate |
| Evidence | Traces, canaries, detector hits | Usage patterns, account metadata, user reports |
| Response | Contain, eradicate, recover, review | Enforce: warn, throttle, suspend, ban |
| Timescale | Minutes to hours matter | Days; the abuse is already succeeding slowly |
| Who acts | On-call engineer | Trust & safety / support / account team |
| Legal exposure | Breach notification clocks | Terms-of-service enforcement, possibly LE requests |
A denial-of-wallet attack sits in both worlds: it can be an incident (someone stole a key — 3.3) or abuse (a legitimate account running an unauthorized scraping job). Your detection pipeline feeds both queues; the difference is which runbook you open.
The economics are also different. Incidents are rare and expensive; abuse is continuous and cheap per event. You can't page a human for every abuse signal — you need automated enforcement tiers backed by human review for edge cases. That's what this part builds.
2.2 The layers between you and abuse#
Abuse defence is defence in depth applied to usage, not payloads. Each layer assumes the one above it will be probed:
flowchart TB
subgraph edge ["Edge: who are you?"]
A["Authentication<br/>API key / JWT / session"]
B["Tiered access<br/>anonymous / verified / paid / enterprise"]
end
subgraph quota ["Quota: how much may you use?"]
C["Rate limits<br/>requests & tokens per minute"]
D["Spend caps<br/>per user, per tenant, per feature"]
E["Feature gates<br/>expensive capabilities need higher tier"]
end
subgraph signal ["Signal: what are you doing?"]
F["Safety identifiers<br/>to providers (hashed user id)"]
G["Behavioural detection<br/>probing, refusal spikes, anomalies"]
H["Human review<br/>sampled + escalated cases"]
end
subgraph enforce ["Enforcement: what happens?"]
I["Warn → throttle →<br/>suspend → ban"]
J["Appeals & reinstatement"]
end
edge --> quota --> signal --> enforceAuthentication tiers. Not every caller deserves the same access. A three-tier model covers most products:
- Anonymous: rate-limited hard, no persistent features, no tools that cost money, CAPTCHA-gated signup. Fine for a demo or a public playground — and a magnet for abuse, so keep the blast radius tiny.
- Verified (email/phone/OAuth confirmed): normal quotas, persistent history, the features you actually sell.
- Paid/enterprise: higher quotas, SLAs, possibly dedicated capacity — and correspondingly more monitoring, because a compromised enterprise account is a bigger breach.
The tier is a security control, not just a pricing artefact: it determines which abuse responses are available (you can't "warn" an anonymous abuser — there's no one to warn).
Rate and quota limits. 03.8 and 03.9 own the mechanics of rate limiting and retries; 03.7 owns cost tracking. For abuse you add three things on top:
- Limits per identity and per tenant. Per-user limits stop one account; per-tenant limits stop one customer org from running 10,000 employee accounts as a scraping farm. Both, always.
- Token-aware limits, not just request limits. A 10,000-token prompt costs ~100× a 100-token one; limit on tokens (and dollars, via the cost tracker) as well as request count.
- Feature-specific limits. Image generation, long-context calls, batch endpoints and tool-heavy agent runs each get their own quota — the expensive paths are where denial-of-wallet lives (12.5 covers the prevention side).
Safety identifiers to providers. This is the piece most teams miss. Providers run their own abuse detection, but it only works if they can attribute suspicious traffic to your end users. 03.2, 9.1 has the full parameter map: OpenAI's safety_identifier (Responses, Chat Completions, Images; Realtime via the OpenAI-Safety-Identifier header), Anthropic's metadata.user_id, Gemini's labels["safety_identifier"], OpenRouter's user. Pass a stable, hashed per-user ID on every request — the HMAC scheme from 03.2, 10.3 — so the provider's abuse systems can group requests without ever seeing who the user is. Without it, provider-side enforcement degrades to blocking your whole org for one abuser's behaviour, and you lose the attribution that makes their warnings actionable.
CAPTCHA and proof-of-work. For anonymous or high-risk flows (signup, first API call, bulk export), a CAPTCHA or a small proof-of-work challenge raises the cost of automation. Use it sparingly: it punishes legitimate users too, and sophisticated abuse rotates residential IPs anyway. It's a speed bump, not a wall — pair it with the quotas above.
2.3 Provider-side abuse systems#
Your provider is also watching, and as of November 2026 each of the four has a documented enforcement pipeline you should understand and cooperate with.
OpenAI. OpenAI runs server-side safety classifiers on requests to its frontier models. Per its safety-checks documentation: organisations that repeatedly hit high-risk thresholds receive errors and a warning email; if the violating requests continue past a stated window (the docs describe "usually seven days"), OpenAI stops the org's access to that model. Two details matter for you:
- OpenAI offers safety enforcement notifications — a way to route those warning/deactivation notices to your investigation workflow rather than a general inbox. Set this up before you need it.
- The classifiers work per organisation, and
safety_identifierexists precisely so enforcement can target the abusive end user instead of your whole account. Passing it is the difference between "we'll warn user_123" and "we'll warn your company".
OpenAI also runs a public bug bounty (managed through Bugcrowd, with a separate safety bounties track) and publishes a security.txt at openai.com/.well-known/security.txt plus a coordinated vulnerability disclosure policy — the same intake pattern Part 5 teaches you to implement yourself.
Anthropic. Anthropic's Safeguards Team enforces its Usage Policy with graduated actions — warn, throttle, suspend, terminate — and its Transparency Hub publishes enforcement statistics (as of November 2026: ~11B.1 million banned accounts and ~398k appeals in January–June 2026, with ~42k overturns — evidence that appeals genuinely work). For API customers, policy warnings are tied to ongoing thresholds of violative behaviour across the API account, reported to usersafety@anthropic.com; account-level bans carry an appeal form. The lesson for you: Anthropic's enforcement is account-scoped, so your own per-user attribution (metadata.user_id) is what lets you act before they have to.
Gemini. Google's enforcement details are less publicly documented at the API level; the verified mechanism you control is the labels["safety_identifier"] convention (03.2, 9.1) for abuse attribution, plus Google Cloud's standard abuse-reporting channels for the cloud side. Treat provider enforcement as a black box you feed good identifiers into, and keep your own detection as the primary control.
OpenRouter. As an aggregator, OpenRouter sits between you and upstream providers: it passes through user/safety_identifier-style fields where the endpoint supports them, applies its own rate limits and fraud controls, and its observability features see the routed traffic. If you route through OpenRouter, your abuse signals may need to be correlated across both your logs and OpenRouter's analytics — and remember that a policy violation upstream can surface as an OpenRouter error, not a provider email.
2.4 Progressive enforcement and account workflows#
When your detection pipeline flags abuse, the response should be a ladder, not a guillotine. Instant bans for first offences generate support tickets, false-positive harm and community backlash; doing nothing generates losses. The standard ladder:
| Stage | Trigger | Action | Human in loop? |
|---|---|---|---|
| 1. Warn | First policy-violating pattern, low severity | In-product warning + email; behaviour logged | No (automated) |
| 2. Throttle | Repeat within window, or severity moderate | Rate/quota reduced (e.g. 10× lower), expensive features gated | No |
| 3. Suspend | Sustained abuse, or high-severity single event | Account suspended pending review; data preserved | Yes — reviewer decides |
| 4. Ban | Confirmed malicious abuse, fraud, or repeat after suspension | Account banned; credentials revoked; data handled per policy | Yes — documented decision |
| 5. Reinstate | Successful appeal | Restore at prior tier, or lower with conditions | Yes |
Design rules for the ladder:
- Every stage is logged and appealable. The enforcement decision, its trigger events and the rule version belong in the audit log (12.6 owns the audit machinery). An unexplainable ban is a support nightmare and, in some jurisdictions, a legal problem.
- Warn ≠ block for borderline content. 12.3 covers refusal-vs-safe-completion policy; abuse enforcement is the same shape — a user probing boundaries gets warnings and throttles before bans, because legitimate users do probe (developers testing limits, security researchers, the merely curious).
- Speed matters at the top. The difference between stage 3 and stage 4 is human review time; for active fraud or denial-of-wallet, don't wait for the review queue — cut the spend cap immediately (a throttle is reversible; a breach isn't).
- Reinstatement is part of the design. False positives are inevitable; a working appeals path (2.5) is what keeps the ladder honest.
Account-level abuse workflows. For B2B products, abuse is often inside a customer org: one employee scraping, one team exceeding quota. Your tooling needs org-level views (per-tenant aggregation from Part 1's tenant field), the ability to contact the customer's admin, and clear terms about acceptable use. For consumer products, the workflow is the ladder above plus a report-abuse channel users can find — a thumbs-down that routes to abuse review, not just quality feedback.
2.5 Appeals, reporting and provider cooperation#
Appeals. Every enforcement action needs a path back. Minimum viable appeals: an in-product form, a published SLA ("we respond within N business days"), a human reviewer who didn't make the original decision, and a documented outcome. Anthropic's public data — ~10% of appeals overturned in the first half of 2026 — shows appeals catch real false positives at scale. Track your own overturn rate; a near-zero overturn rate usually means your appeals process is broken, not that you're always right.
Reporting channels. Give users three doors: in-product feedback (thumbs-down with a reason picker that includes "harmful/abusive"), a security@/abuse@ contact for anything sensitive, and the provider's own reporting where relevant. Route abuse reports into the same triage queue as detection alerts — user reports are high-precision signals your detectors can't see (a user reporting "the bot gave me dangerous instructions" is ground truth).
Provider cooperation. When a provider warns you about abuse on your org, treat it as an incident-lite: identify the end user via your safety_identifier mapping, review their traces, enforce at your layer, and document the response. When you detect abuse your provider can't see (your app-level abuse that never trips their classifiers), there's no obligation to report it — but patterns of provider-policy violations you do see are worth feeding back through their abuse channels; it's how the ecosystem's thresholds get calibrated.
Takedown and law-enforcement awareness. Two flows you'll eventually meet, at awareness level:
- Content takedown / user data requests. A user asks you to delete their data (GDPR erasure — 12.4 owns the mechanics) or a rights-holder demands removal of generated content. You need a documented intake, an identity-verification step, and a deletion pipeline that reaches logs, traces, caches and backups — not just the primary store.
- Law-enforcement and legal requests. Subpoenas, court orders, national-security letters. Have a named contact (usually legal), a policy for verifying authenticity, a log of every disclosure, and never hand over more than the order requires. Most LLM-relevant requests are ordinary legal process; the LLM-specific wrinkle is that "the data" may live in provider-side logs you don't control — know your provider's legal-process policy before you need it. 12.9 covers the regulatory landscape; this is operational awareness only — not legal advice.
Part 3: Incident response for LLM-specific incidents#
3.1 The lifecycle, adapted#
Classic incident response follows a lifecycle you already half-know: NIST SP 800-61 (the current revision is r3, published April 2025, which reframes incident response as recommendations across the six functions of the NIST Cybersecurity Framework 2.0 — Govern, Identify, Protect, Detect, Respond, Recover), ISO/IEC 27035-1:2023 (Plan/Prepare → Detect/Report → Assess/Decide → Respond → Learn Lessons), and the practitioner shorthand SANS PICERL (Preparation, Identification, Containment, Eradication, Recovery, Lessons Learned). Module 11C's operations lesson owns the general runbook format and blameless postmortem template; this part adds what changes when the compromised system is a probabilistic model in the middle of your stack.
What changes for LLM incidents:
- "Eradicate" is rarely "patch the code." A prompt-injection incident's root cause is architectural (untrusted content reaching a privileged context), not a bug in a function. The fix is usually a control change — remove a tool, tighten an allow-list, split a privileged context — not a code patch. Plan for configuration and architecture remediation, and verify it with a red-team retest (12.8).
- The blast radius includes generated content. A harmful output isn't just a log line — it's text that may have been screenshotted, copied, quoted and amplified. Evidence preservation means capturing the exact output, the prompt version, the model version and the trace before anything changes.
- Non-determinism complicates reproduction. You cannot always "replay" the incident: the same inputs may not produce the same output (02.5 owns determinism). Investigation relies on the recorded trace and stored outputs, not on re-running the attack — though red-team retests after fixes are deterministic-ish enough to verify a control works.
- Two clocks run at once. The technical clock (contain before more damage) and the legal/communications clock (breach notification, customer comms, regulator deadlines). GDPR's Article 33 gives 72 hours from awareness to notify the supervisory authority for personal-data breaches likely to pose risk (Article 34 adds data-subject notification for high risk); other jurisdictions differ. Know your obligations before the incident — this is awareness, not legal advice, and 12.9 owns the regulatory detail.
The adapted lifecycle:
flowchart LR
A["Detect<br/>(alert / user report /<br/>provider notice)"] --> B["Triage &<br/>severity (3.2)"]
B --> C["Contain<br/>(kill switch, revoke,<br/>disable tools/egress)"]
C --> D["Investigate<br/>(traces, audit log,<br/>blast radius)"]
D --> E["Eradicate &<br/>recover (fix +<br/>verify + restore)"]
E --> F["Communicate<br/>(internal, customers,<br/>regulators, providers)"]
F --> G["Post-incident<br/>(review + regression<br/>tests + rule tuning)"]
G -.->|"detection gaps found"| ANote that containment comes before investigation for LLM incidents: an active exfiltration channel or a runaway agent does more damage every minute it runs. Preserve evidence while containing — snapshot logs and traces to immutable storage first, then pull the levers.
3.2 The severity matrix#
Severity decides who gets paged, how fast, and who must be told. For LLM systems, score on three axes: blast radius (how many users/tenants/data classes affected), exploitability (was it attempted, suspected, or confirmed successful), and sensitivity (PII, credentials, regulated data, physical-safety-adjacent outputs raise the tier automatically).
| Severity | Definition | Examples | Response |
|---|---|---|---|
| SEV-1 | Confirmed or highly likely: active data exfiltration, PII/credential exposure at scale, harmful output causing real-world harm, agent actions causing irreversible damage | Canary hit + egress to external domain; cross-tenant data returned to wrong user; agent deleted production records; leaked API key actively billing | Page immediately; commander assigned; containment within minutes; comms lead opened; regulator clock started if personal data involved |
| SEV-2 | Confirmed security failure with limited blast radius, or credible threat of SEV-1 | Successful injection that leaked system-prompt content (no PII); single-tenant ACL bypass; key exposed in a private repo (not yet used); harmful output reported by users | Same-day response; senior engineer + security lead; containment within hours |
| SEV-3 | Attempted attack blocked by controls, detector false-positive pattern revealing a gap, or abuse at policy-violating but non-harmful scale | Injection attempts all blocked; canary planted but not triggered; denial-of-wallet attempt capped by budget; jailbreak probes with no success | Queue for review within 24–48h; tune detection; no customer comms unless pattern emerges |
| SEV-4 | Informational: research disclosure, near-miss, policy question | A researcher reports a theoretical injection vector; a red-team finding from 12.8 | Track, assess, fix in normal cycle |
Two LLM-specific severity rules:
- Suspected PII exposure is SEV-1 until proven otherwise. The cost of over-reacting (a needless notification) is far lower than under-reacting (a missed 72-hour clock).
- Agent incidents inherit the worst tool's tier. A runaway agent that only read documents is SEV-3; the same loop with a
delete_recordstool in scope is SEV-1 — blast radius is set by what the agent could reach, per 12.6's risk tiers.
3.3 Playbooks: seven LLM-specific incident types#
Each playbook follows the same skeleton — detect → contain → investigate → eradicate/recover → communicate → review — with the LLM-specific levers filled in. These extend the generic templates in Module 11C; keep both: the generic one for "provider is down", these for "someone is attacking us".
Playbook A: Prompt-injection incident (suspected or confirmed)
Detect. Canary trigger, injection-detector cluster, unusual tool-call sequence, or user report of the bot obeying document/email content.
Contain — fast levers, in order:
- Disable the exfiltration channel first. If the injection reached a context with outbound tools (web fetch, email send, HTTP request), revoke/disable those tools for the affected feature now — a read-only agent can't exfiltrate. This is the lethal-trifecta lesson (12.1, 12.2) applied under pressure.
- Freeze the feature or tenant. Feature flag off for the affected surface, or rate-limit/quarantine the specific tenant/user if the attack is targeted.
- Rotate anything the injected context could have seen. If the model had access to secrets, API keys or session tokens in context, rotate them — assume the injection read them.
- Preserve evidence. Snapshot the security event stream, traces, guardrail decisions and the offending documents before you clean anything.
Investigate. Pull the trace for the affected request(s): which untrusted content entered context, which instruction it carried, what the model did, what left the system. Identify the injection vector (retrieved document? user upload? tool output? email?) — the vector determines the fix.
Eradicate/recover. The fix is architectural, per 12.2: remove the tool from the untrusted context, add egress allow-lists, tighten document sanitisation at ingestion, split privileged/quarantined roles. Not "add 'ignore injections' to the system prompt" — that ship sailed. Verify with a red-team retest using the same benign payload class (12.8).
Communicate/review. Internal postmortem; customer comms only if user data or outputs were affected; convert the payload into a permanent regression test.
Playbook B: Data leak / PII exposure
Detect. PII-in-output alert, user report of another user's data, cross-tenant retrieval anomaly, or discovery during investigation.
Contain. Kill the leaking path immediately (disable feature, revoke the mis-scoped credential, fix the ACL filter). If the leak is ongoing, preserve evidence while stopping the flow — you need both.
Investigate — scope the blast radius. This is the hard part: whose data, how much, for how long. Use the trace/audit logs to enumerate every request that could have returned the data: which tenants, which users, which document IDs. The tenant and user_ref fields from Part 1 are what make this answerable. Check caches (11B.3) — a leaked answer may persist in a response cache keyed wrong.
Eradicate/recover. Fix the root cause (ACL propagation drift, missing tenant filter, cache key missing tenant scope — 06.6). Then purge: caches, indexes if poisoned, any exported copies you control. Deletion across backups and provider-side retention follows 12.4's retention machinery.
Communicate — the clock matters. If personal data was exposed to unauthorised parties, GDPR Article 33's 72-hour supervisory-authority clock (and Article 34's data-subject notification for high-risk cases) may be running from the moment you became aware — confirm obligations with legal, and start the clock conservatively. Customer comms follow the severity-appropriate template in 3.5.
Playbook C: API key / secret leak
Detect. Secret-scanner hit in logs/traces/prompts, provider usage anomaly (spend spike on a key), GitHub push-protection or public-repo alert, employee report.
Contain — revoke first, investigate second. The single most important rule: revoke/rotate the credential before you finish scoping the damage. A leaked key is a live weapon; every minute it remains valid is exposure. 03.1, 3.7 owns the first-hour mechanics; 12.7 owns the full key-security treatment.
Investigate. Scope the window: when was the key exposed, where (repo, log, screenshot, prompt), and what was done with it? Check provider usage dashboards for calls you didn't make — unusual models, unusual volume, unusual source IPs. The provider's own logs are your best evidence of what the attacker did with it.
Eradicate/recover. Rotate to a new key, update secret stores, purge the exposed copy from git history (or accept that it's public and rely on revocation), review whether the leaked key had broader scope than needed (it should have been least-privilege — 12.7). If the key was used to access user data, this incident becomes Playbook B.
Communicate/review. Notify affected users if their data was accessed; notify the provider if the abuse came through their platform; postmortem on why the secret-scanning/CI controls didn't catch it (Part 4).
Playbook D: Harmful-output incident (viral bad answer)
Detect. User reports at unusual volume, social-media pickup, thumbs-down abuse spike, or a screenshot reaching support.
Contain. Kill switch first: disable the feature or feature-flag it off while you investigate — a harmful output that's still being served is still causing harm. Preserve the exact output, the prompt version, model version and trace. Do not delete the evidence while "cleaning up".
Investigate. Reconstruct: what prompt produced it, what context was in scope, was it a jailbreak/injection, a model failure, a guardrail miss, or a policy gap? Check whether the same output pattern appears elsewhere (batch-scan recent outputs for the category). Determine blast radius: how many users saw it, for how long.
Eradicate/recover. Fix by layer: prompt/policy fix for a one-off, guardrail threshold for a class, model/prompt version rollback if a deploy caused it, or feature redesign if the capability itself is the problem. Communicate transparently — users forgive bugs, not cover-ups.
Communicate. This is the most reputation-sensitive playbook: acknowledge fast, explain plainly, say what you're doing. Template in 3.5. If the output harmed a specific person or group, legal may need to be involved immediately.
Playbook E: Agent misbehaviour (runaway actions)
Detect. Unusual tool-call volume, actions outside expected patterns, cost spike on agent runs, user report of unexpected changes, or a loop-detector alert.
Contain. Stop the agent, not just the request. Cancel the run, revoke the agent's credentials/tokens, disable the affected tools. For durable agents (08A.14 owns agent ops), checkpoint and freeze state before restarting — you need the trajectory for forensics. If actions touched external systems (emails sent, records deleted, payments made), enumerate them now — rollback/compensation is time-critical.
Investigate. Replay the trajectory: what did the agent see (was a tool output or retrieved document injected?), what did it decide, what did it touch? The 12.6 audit log is your primary evidence — every tool call with args, approval state and result.
Eradicate/recover. Fix the cause: tighten tool permissions, add approval gates for the action class, fix the injection vector, add loop/budget limits. Compensate for external effects where possible (undo sends, restore records) and document what can't be undone.
Communicate/review. Users affected by agent actions need specific notification ("your records X, Y were modified — here's the rollback"); the postmortem focuses on why the permission model allowed it.
Playbook F: Supply-chain compromise
Detect. Dependency scanner alert, anomalous package behaviour, provider/model-file integrity failure, or a public advisory (CVE/GHSA) affecting your stack.
Contain. Pin/rollback to the last-known-good version immediately; if a compromised package is in production, treat every secret it could reach as exposed (rotate). For model files, verify hashes/signatures before loading (12.7 owns model-file safety).
Investigate. Determine scope: which environments ran the bad version, what did it do (the two 2026 LiteLLM compromises — March, 03.11, and October, both detailed in 12.7, Part 5.1 — are the canonical examples: a compromised release that exfiltrated keys). Check your lockfile, image digests and CI logs for the blast radius: which builds resolved the bad version inside the exposure window, on laptops as well as servers. Remember that both payloads rode on a .pth file, so removing the package does not remove the payload: search site-packages for unexpected .pth and sitecustomize.py files, and avoid launching pip from an environment you believe is infected (a .pth runs on every interpreter start) — use a clean machine for the cleanup and for rotating credentials.
Eradicate/recover. Rebuild clean images from a clean base (not by patching a running container), rotate all reachable secrets from a clean machine, update to the patched version, re-run your security tests, and then add the control that would have shortened the window — a dependency cooldown and hash-pinned lockfile (12.7, 5.2). Notify customers if their data was exposed; notify upstream if you found a variant.
Communicate/review. Public incidents need transparent postmortems; internal ones need the dependency-hygiene review (Part 4.3).
Playbook G: Model/provider incident
Detect. Provider status page, error-rate spike on one provider, quality regression across all users of a model, or provider security notification.
This is mostly Module 11C's territory — its fallbacks/gateways lesson owns provider-outage response. The security overlay: if the provider incident involves their security (a breach on their side, a model-safety failure), you may have notification obligations to your users if their data was in scope. Monitor provider trust centres and security bulletins as part of your vendor management (12.9).
3.4 Evidence preservation#
LLM incidents are unusual in that the "evidence" is partly probabilistic — you can't always regenerate what the model did. Preservation rules:
- Snapshot before you clean. Export the security event stream, traces, guardrail decisions, tool-call audit log and the exact outputs involved to immutable storage (object lock / write-once) before remediation. Hash them so integrity is provable.
- Capture the four-version tuple. For any model output:
prompt_version+model_key+resolved_model+ the trace/span IDs. Without all four you cannot reconstruct or defend the incident later. - Chain of custody. Who accessed the evidence, when, why — logged. Investigations into security incidents are themselves sensitive; treat evidence access like evidence access in a legal matter.
- Don't over-preserve. Content in evidence is still PII under your retention rules. Preserve what's needed for the investigation and the legal tail, then apply normal retention — evidence isn't a justification for indefinite hoarding.
- Redact for the postmortem. The blameless review (Module 11A) needs enough detail to learn from, not raw user content. Use the PII-safe patterns from 12.4.
3.5 Communication templates and the regulatory clock#
Three audiences, three registers. Keep a document with filled-in placeholders; writing them during an incident is how bad comms happen.
Internal (engineering + leadership), first 30 minutes:
[SEV-X] [Feature] — [one-line what happened] Detected: [time, source]. Containment: [action taken / in progress]. Blast radius: [known so far]. Commander: [name]. Comms lead: [name]. Next update: [time]. Bridge: [link].
Customers (only when their data or experience was affected):
We identified a security issue affecting [feature] between [dates]. [What happened, in plain language — no jargon]. [What data, if any, was involved]. [What we've done]. [What you should do, if anything]. [How to contact us]. We will share updates at [channel].
Regulators / supervisory authority (awareness — confirm with legal):
GDPR Article 33 requires notification "without undue delay and, where feasible, not later than 72 hours" after becoming aware of a personal-data breach likely to risk individuals' rights. Article 34 adds data-subject notification for high-risk cases. Other regimes have their own clocks: US state breach laws, sector rules, NIS2 (an early warning within 24 hours for significant incidents in covered sectors) and, once the high-risk regime applies, EU AI Act Article 73 serious-incident reports (12.9, 6.5). The 72-hour window makes "when did we become aware?" a documented decision — timestamp it.
Providers. If the incident involves a provider-side issue or you'd like their abuse team aware, use their security/disclosure channel (Part 5 covers coordinated disclosure).
3.6 Tabletop exercises: three scenarios#
A tabletop is a facilitated discussion, not a drill: you walk a scenario, decide out loud, and find the gaps before a real incident finds them. Run these with your team; each takes 30–60 minutes. The injects are surprises the facilitator drops mid-scenario.
Scenario 1 — The poisoned support ticket. Your RAG support bot retrieves a ticket containing hidden instructions; the bot's answer includes a link to exfil.example.com that renders as an image in the chat UI. Injects: (a) halfway through, you learn the bot did have a web-fetch tool enabled in that context; (b) a second team reports the same payload in a different tenant's corpus; (c) legal asks "are we within the GDPR clock?" Decisions to make: severity, first three containment actions, who owns comms, whether this is one incident or two.
Scenario 2 — The leaked key in a prompt trace. A developer pastes an API key into a prompt while debugging; it lands in the trace store, the SIEM and a screenshot in a support ticket. Injects: (a) the key was a production key with spend authority; (b) provider dashboard shows 40× normal calls from an unusual region in the last 6 hours; (c) the trace store has 30-day retention and the SIEM 90-day. Decisions to make: revoke order, blast-radius scoping, which stores need purging, whether users must be notified.
Scenario 3 — The viral harmful answer. A user's screenshot of your assistant giving dangerous instructions is trending; 50k impressions in 2 hours. Injects: (a) the answer came from a fine-tuned community model, not your main one; (b) a journalist emails for comment within the hour; (c) your safety team says the same prompt works on two other features you forgot exist. Decisions to make: kill-switch scope (one feature or all?), comms timing and wording, who speaks to press, what the postmortem must answer.
After each tabletop, write down: what you decided, what you didn't know, which runbook was missing or wrong, and which detection rule would have caught it sooner. Those become Part 4 backlog items and 12.8 regression tests.
3.7 Post-incident: turning incidents into tests#
The most valuable output of an incident is a permanent test. For every SEV-1/2:
- Convert the attack into a red-team case. The exact benign payload class that worked becomes a fixture in your 12.8 suite — with the defence expected to catch it, not just the attack reproduced.
- Add the detection gap as a rule. If you found out from a user report rather than an alert, the detection rule you should have had gets written, tested on the incident's trace fixture, and deployed — this is the feedback loop in Part 1's diagram.
- Update the threat model. If the incident revealed an asset or trust boundary you hadn't mapped, 12.1's model gets amended.
- Blameless review. Focus on why the system allowed it — missing control, missing detection, missing process — not on who clicked what. Module 11C owns the postmortem template.
Part 4: Security in the SDLC#
Deep-dive
Incidents are cheaper to prevent than to respond to. Security-by-design for LLM features means the controls from lessons 12.1–12.9 are requirements with owners and gates, not aspirations. This part is the engineering-process layer.
4.1 Gates by phase#
| Phase | Security activity | Owner of the detail |
|---|---|---|
| Design | Threat model the feature before building: assets, actors, trust boundaries, data flows (12.1); derive security requirements ("the model can never delete records without approval") | 12.1 |
| Design review | Walk the threat table with security + product; check the lethal-trifecta legs; confirm data-classification rules for what may be sent to which provider (12.4) | 12.1, 12.4 |
| Build | Secure coding for LLM glue code (below); use llm_guard_kit components rather than rolling your own |
this lesson + 12.2–12.7 |
| Code review | LLM-feature review checklist (below); reviewer checks prompt construction, output handling, tool permissions, logging | this lesson |
| CI | Secret scanning, dependency scanning, lockfile hash checks, guardrail/red-team regression suites (12.7, 12.8) | 12.7, 12.8 |
| Pre-launch | Security review + red-team gate; fill the 6.1 checklist; kill switches verified | 12.8, this lesson |
| Post-launch | Detection rules live and tested (Part 1); abuse ladder armed (Part 2); tabletop scheduled (3.6) | this lesson |
flowchart LR
subgraph design ["Design"]
D1["Threat model<br/>(12.1)"] --> D2{"Security<br/>requirements<br/>signed off?"}
end
subgraph build ["Build & CI"]
B1["Secure glue code<br/>+ guardrails"] --> B2["CI gates:<br/>secrets, deps,<br/>red-team suite"]
end
subgraph launch ["Launch"]
L1["Pre-launch<br/>security review"] --> L2{"Checklist<br/>complete?"}
L2 -->|no| B1
L2 -->|yes| L3["Ship +<br/>kill switches live"]
end
subgraph operate ["Operate"]
O1["Detection rules<br/>+ abuse ladder"] --> O2["Tabletops<br/>& audits"]
O2 -.->|"new threats"| D1
end
design --> build --> launch --> operate4.2 Secure coding for LLM glue code#
The code around the model is ordinary software and gets ordinary secure-coding review, plus LLM-specific checks:
- Prompt construction: no string-concatenated user input into system/developer positions; untrusted content goes through the delimit/spotlight helpers (12.2); no secrets in prompts ever.
- Output handling: model output treated as untrusted input — validated against schema, sanitised before render/execution, never rendered as raw HTML or executed (12.5).
- Tool permissions: every tool call passes the permission broker; high-risk tiers require approval; arguments validated semantically (12.6).
- Logging: security events emitted per the Part 1 schema; content only in the product path with redaction;
safety_identifierpassed on every provider call. - Failure modes: fail closed on security checks for high-risk features; guardrail outages degrade gracefully but visibly (alert, don't silently bypass).
Code review checklist for LLM features (steal this into your PR template):
- Threat-model delta reviewed for this change (new data source? new tool? new audience?)
- Untrusted inputs identified and routed through sanitisation/delimiting
- Model output validated + sanitised before use/render/execute
- Tool calls permissioned; risk tiers correct; approvals where required
- No secrets/PII in prompts, logs, traces or error messages
-
safety_identifier/ user attribution passed to provider - Security events emitted for new detection surface
- Kill switch / feature flag exists for the capability
- Rate/quota limits cover the new expensive path
- Regression test added for any security fix
4.3 CI security controls#
12.7 owns the dependency/supply-chain detail; the CI wiring belongs here:
- Secret scanning on every commit and PR (gitleaks/trufflehog/detect-secrets class tools; verify current versions before pinning — 12.7 covers them).
- Dependency scanning (
pip-audit,osv-scannerclass) plus lockfile-with-hashes enforcement (uv.lock). - Red-team regression gate: the 12.8 suite runs in CI on changes to prompts, guardrails, tools or model config — a security-relevant diff that fails the suite blocks merge.
- A dependency cooldown (uv
exclude-newer, Dependabotcooldown, RenovateminimumReleaseAge) so CI does not resolve to a release published hours ago — both 2026 LiteLLM compromises were live for hours (12.7, 5.2). - A hardened pipeline: actions pinned to full commit SHAs (your security scanners included — a compromised Trivy action is how one 2026 publish token was reportedly stolen), job-level least-privilege
permissions, OIDC instead of stored cloud keys, no checkout of untrusted PR code underpull_request_target(12.7, 5.3). - Image scanning + signing for anything containerised.
- No secrets in CI logs or fork PRs — the standard AppSec rules apply doubly when your CI has provider keys.
4.4 Kill switches, feature flags and safe degradation#
Every high-risk capability needs a kill switch: an externally-controlled off-ramp that doesn't depend on the feature's own code path. 08A.14 owns the agent-level mechanics (canary releases, kill switches); for security you need them at every layer:
| Switch | Scope | Use when |
|---|---|---|
| Feature flag off | One feature | Harmful output, injection incident, provider issue |
| Tool disable | One tool/agent | Tool being abused or misbehaving |
| Tenant/user quarantine | One account | Targeted attack or confirmed abuse |
| Egress lockdown | All outbound tools | Active exfiltration channel |
| Model fallback/rollback | One model_key | Model regression or provider safety event |
| Global read-only mode | Everything | SEV-1 unknown-cause incident |
Design rules: switches must be testable (exercise them in staging/tabletops), fast (seconds, not deploys), audited (who flipped what, when, why), and fail-safe — a switch that itself depends on the compromised component is useless. Module 11C owns feature-flag infrastructure; the security requirement is that security flags exist for every high-risk capability and are in the incident runbooks.
4.5 Security champions, training and baselines#
- Security champions: one engineer per team who owns security review depth, runs the module's checklists, and is the first call for LLM-security questions. Cheap to start, compounds.
- Training: every engineer touching LLM features should do the module's red-team exercise (12.8) once — attacking your own app teaches the threat model faster than any doc.
- Configuration baselines: a documented secure-default config (which tools are enabled, which providers, which data classes allowed, which guardrails on) that new features copy. Drift from baseline is a review flag.
- Maturity: track progress on the 6.2 model; revisit quarterly.
Part 5: Vulnerability management and disclosure#
Deep-dive
5.1 Intake: make it easy to report#
You cannot fix what you never hear about. The intake surface:
security.txt— the IETF standard (RFC 9116, April 2022): a machine-readable file at/.well-known/security.txt(or/security.txt) with the requiredContact:andExpires:fields, plus optional fields from the IANA registry —Policy:,Acknowledgments:,Canonical:,Encryption:,Hiring:,Preferred-Languages:,CSAF:andBug-Bounty:. It's the security equivalent ofrobots.txt— tell researchers exactly where to report. OpenAI publishes one atopenai.com/.well-known/security.txt; you should too.- A monitored
security@alias (or web form) that reaches a human, with a published response expectation. - A vulnerability disclosure policy — even a short one: scope, safe-harbour language, response timeline, disclosure coordination. CERT's Guide to Coordinated Vulnerability Disclosure is the canonical reference; the security.txt
Policy:field points at yours. - Bug bounty — optional at your scale; start with a VDP and a
security.txt, add bounties when volume justifies (OpenAI's program, managed via Bugcrowd with a separate safety track, is the reference point for what's possible at scale).
5.2 Triage and SLAs#
Route every intake into the same severity matrix as incidents (3.2):
| Report type | Initial response | Triage target |
|---|---|---|
| Confirmed exploitable vulnerability (injection, data leak, key exposure) | Acknowledge within 24–48h | SEV-1/2 severity assessment within 72h |
| Suspected vulnerability needing reproduction | Acknowledge + request details | Reproduce in your own environment (never against prod blindly) |
| General security question / policy | Route to security@ | Best-effort |
Keep reporters informed — silence is the #1 driver of public disclosure. A simple "we're investigating, expect an update by X" prevents the "researcher went public because nobody answered" failure mode.
5.3 Coordinated disclosure#
When you find a vulnerability — in your own stack, in a provider, in an open-source dependency, in a model:
- Verify first. Reproduce in a safe environment; confirm scope and impact.
- Notify the right owner privately. Provider security teams, package maintainers (GitHub Security Advisories / GHSA), or your own team — never a public issue first.
- Agree on a timeline. Coordinated disclosure means: fix privately, disclose together after patch. Standard embargoes run ~90 days; agree explicitly.
- Credit the reporter (with permission) in advisories and release notes.
- Publish the advisory — GHSA for OSS dependencies, your own security page for product issues — with enough detail to help users assess exposure without handing attackers a recipe.
CVE/GHSA awareness. CVEs are assigned by CNAs (including OpenAI, which publishes a CVE Assignment Policy); GHSAs are GitHub's advisory format. Your dependency-scanning tools (12.7) surface these; the operational habit is checking whether any open advisory affects your pinned versions this week — LLM-stack dependencies move fast and advisories lag reality.
5.4 Model-level vulnerabilities#
A vulnerability in the model itself (a jailbreak class, an extraction technique, a safety bypass) is different: you can't patch weights. The responsible path:
- Verify it's real and in scope — reproduce against your own deployment or the provider's documented testing policy; never probe third-party production systems.
- Report to the provider's security/disclosure channel — OpenAI's coordinated disclosure policy and safety bug bounty are the documented paths; other providers have equivalent security contacts (check their trust centres).
- Defend at your layer meanwhile — your guardrails, permission broker and detection rules are your mitigation until the provider ships a fix.
- Publish responsibly — after disclosure windows, so others can defend.
Part 6: The Safety & Security checklist, maturity and wrap-up#
6.1 The one-page Safety & Security checklist#
This is the launch gate. A feature doesn't ship until every applicable box is checked — "applicable" meaning the threat model says the risk exists; N/A needs a reason, not a shrug. Grouped to mirror the module:
Threat model & governance
- Threat model completed and reviewed (12.1)
- Security requirements derived and owned
- Data classification: what may go to which provider (12.4)
Prompt injection & untrusted content
- All untrusted inputs identified (user, retrieved docs, tool outputs, files, memory, agent messages)
- Delimiting/spotlighting applied; instruction hierarchy where supported (12.2)
- Canary tokens planted in system prompts and high-value documents
- Egress channels allow-listed; no outbound tools in untrusted contexts
Jailbreaks & policy
- Content policy defined with categories, thresholds, refusal style (12.3)
- Refusal/over-refusal test set exists and passes
- Abuse identifiers (
safety_identifier/equivalent) passed to providers
Privacy & data protection
- PII detection + vault/redaction in place (12.4)
- Tenant isolation tested; ACLs enforced below the model (06.6)
- Retention/deletion path covers logs, traces, caches, vector store, backups
Guardrails & output handling
- Output validated (schema) and sanitised (HTML/SQL/shell/SSRF) before use (12.5)
- Streaming output checked or buffered per risk tier
- Denial-of-wallet controls: token/spend caps per user/tenant/feature
Tools, agents & MCP
- Tool risk tiers assigned; high-risk requires approval (12.6)
- Least-privilege credentials; no ambient authority
- MCP servers pinned, allow-listed, change-detected
- Agent loops have step/budget limits
RAG data & supply chain
- Ingestion sanitisation + source trust tiers (12.7)
- Dependencies pinned with hashes, a dependency cooldown configured; secret scanning in CI; CI actions (scanners included) pinned by commit SHA
- Model files verified (safetensors, hashes, provenance)
Testing & red team
- Red-team suite run against this feature; findings triaged (12.8)
- Every prior incident for this feature has a regression test
Monitoring & incident response
- Security events emitted per the event schema (Part 1)
- Detection rules for this feature's top threats are live
- Runbook exists for this feature's likely incidents (Part 3)
- Kill switches tested
Responsible AI & compliance
- Acceptable-use policy published; appeals path exists
- Regulatory obligations identified per market — AI-use disclosure, chatbot/companion rules, sector law (awareness; 12.9, 6.7)
- Human oversight defined for high-risk outputs
Governance
- Owner named; security champion consulted
-
security.txt+ disclosure contact live (Part 5)
6.2 The maturity model (levels 0–4)#
| Level | Name | Characteristics |
|---|---|---|
| 0 — Ad hoc | "We prompt carefully" | No threat model; security = system prompt + hope; no detection; incidents handled by whoever notices; keys in env vars on laptops |
| 1 — Aware | "We have a checklist" | Threat model exists; OWASP LLM Top 10 known; basic rate limits; some logging; incidents have a runbook; secrets in a manager |
| 2 — Managed | "We test and monitor" | Red-team suite in CI; detection rules live; kill switches; abuse ladder; severity matrix; tabletop done; security.txt published |
| 3 — Measured | "We measure security" | Detection coverage reviewed quarterly vs threat model; false-positive/negative rates tracked; incident→regression-test loop closed; maturity reviewed per feature |
| 4 — Optimised | "Security is a feature" | Security SLOs; automated containment; threat-informed detection (threat intel feeds); cross-team security champions; public security posture (disclosure policy, transparency reporting) |
Most teams sit at 1–2. The jump from 2→3 is the one that matters: it's the difference between having controls and knowing they work.
6.3 The 30/60/90-day hardening plan#
A pragmatic ramp for a team at level 1–2:
Days 1–30 — see and stop the bleeding:
- Inventory every LLM feature, its tools, its data classes, its provider keys
- Turn on the security event schema (Part 1) on your highest-risk feature
- Deploy the top 5 detection rules from the catalogue (canary, injection cluster, unapproved-tool, PII-in-output, spend anomaly)
- Rotate any keys that have ever been in a prompt, log or repo
- Write
security.txt+ disclosure policy - Pin CI actions to commit SHAs and turn on a dependency cooldown (an afternoon of work that would have shortened both 2026 LiteLLM exposures)
- Run one tabletop (Scenario 1)
Days 31–60 — build the defences:
- Threat-model your top 3 features; derive security requirements
- Implement the permission broker on agent/tool paths (12.6)
- Deploy kill switches for every high-risk capability; test them
- Stand up the abuse ladder (warn→throttle→suspend) for your worst abuse vector
- Add red-team regression suite to CI (12.8)
Days 61–90 — measure and institutionalise:
- Detection coverage review vs threat model; fill gaps
- Second + third tabletops; write runbooks for your top 3 incident types
- Maturity assessment; pick the level-3 goals for next quarter
- Security-champion rotation; onboarding module for new engineers
- First public disclosure-policy review; first transparency note if warranted
6.4 Decision tables#
Two routing tables that compress the lesson into "when this happens, do that".
Signal → response. When an alert fires, severity decides the clock and the signal decides the playbook:
| Detection signal (1.3) | Typical severity | First response | Owning playbook |
|---|---|---|---|
| Canary trigger in output | SEV-1 | Pull the trace; identify what left and through which channel; check blast radius | Playbook A — injection/exfiltration |
| PII or secret in output | SEV-1 until proven otherwise | Kill the leaking path; preserve evidence in parallel; start blast-radius scoping | Playbook B — data leak |
| Unapproved high-tier tool call | SEV-1/2 | Stop the agent run; revoke its credentials; enumerate external effects | Playbook E — agent misbehaviour |
| Non-allow-listed egress domain | SEV-1/2 | Disable outbound tools for the feature immediately | Playbook A |
| Spend/token anomaly | SEV-2 if a stolen key, SEV-3 if abuse | Cut spend caps first; then decide incident vs abuse | Playbook C or the enforcement ladder |
| Injection cluster, refusal spike, probing pattern | SEV-3 (queue) | Sample for review; correlate the account; tune thresholds | Abuse ladder (Part 2) |
| Cross-tenant denial burst | SEV-3 | Determine enumeration vs broken ACL before escalating | Investigation; escalate toward Playbook B if the ACL failed open |
| User reports of harmful output | SEV-2/3 | Kill-switch the feature; preserve the exact output and versions | Playbook D — harmful output |
Incident type → playbook. The seven playbooks share one skeleton (detect → contain → investigate → eradicate/recover → communicate → review); this is the index:
| Incident | Playbook | First containment lever | Clock that may be running |
|---|---|---|---|
| Prompt injection | A | Disable outbound tools, then freeze feature or tenant | None — unless PII was touched |
| PII / data leak | B | Kill the leaking path; preserve evidence in parallel | GDPR Art. 33: 72 hours from awareness |
| API key / secret leak | C | Revoke/rotate before finishing the scope | Provider abuse window if the key was misused |
| Harmful output going viral | D | Kill switch / feature flag | Reputational — comms within the hour |
| Agent misbehaviour | E | Stop the agent; revoke credentials; freeze state | External effects are time-critical |
| Supply-chain compromise | F | Pin/rollback; rotate every reachable secret | Customer notice if data was exposed |
| Model/provider incident | G | Module 11C failover patterns + provider comms | Provider-side obligations |
6.5 The failure gallery#
The recurring ways security operations fail — each is an ops failure rather than a payload failure, and each has a control that prevents it:
| Failure | What happened | The control that prevents it |
|---|---|---|
| Alert fatigue | Every detector hit pages on-call; the queue drowns and the real canary alert is missed in the flood | Windowed thresholds, severity tiers, dedup/grouping and sampling (1.3, 1.4) |
| Evidence destroyed during cleanup | The responder remediates first and deletes traces and logs "to tidy up" — the incident can no longer be reconstructed or defended | Evidence preservation runs in parallel with containment: snapshot to immutable storage before cleaning anything (3.4) |
| Runbooks that drifted | The runbook says "disable the fetch tool", but the tool was renamed last sprint; the responder improvises at 3 a.m. | Tabletop exercises surface stale steps; every runbook has an owner and a review date (3.6) |
| Untested kill switches | The switch exists on paper; nobody has ever flipped it; it fails silently during the SEV-1 that needs it | Switches exercised in staging and tabletops; fail-safe design with no dependency on the compromised component (4.4) |
| Dual-pipeline collapse | "Simplify": security events start carrying raw prompts so investigators skip a second lookup — now every dashboard user can read user content | The two-path rule: the security path is metadata-only by schema; content is fetched deliberately under access control (1.2, 1.5) |
| Provider enforcement blindsiding | The warning email sits unread in a shared inbox; a week later the org's model access is stopped mid-incident-response | Safety-enforcement notifications routed to the on-call workflow before they're needed; per-user safety_identifier so enforcement lands on the abuser, not the org (2.3) |
| Post-incident amnesia | The incident closes, lessons go into a doc nobody reads, and the same attack succeeds next quarter | Every SEV-1/2 produces a red-team regression test and — if detection missed it — a new rule (3.7) |
| Checklist decay | The launch checklist was filled once at ship time; six months of feature drift later it is fiction | Maturity reviews, quarterly detection-coverage walks and the 30/60/90 plan (6.2, 6.3) |
Read the gallery as a detection problem too: most of these failures are themselves detectable — untested switches show up as missing test records, runbook drift shows up in tabletop findings, alert fatigue shows up as falling precision. The ops layer gets measured like everything else in this lesson.
6.6 Module wrap-up: what is and isn't solved#
The consolidated llm_guard_kit. This module built one package across ten lessons. The appendix below lists every module and what it provides; the pieces plug into the running examples (docs_qa from Module 07, the support agent from Module 08A, llm_service from Modules 11A to 11C) as composable wrappers: detectors before the model, validators after it, permissions around tools, redaction in logs, rules over the resulting event stream.
What this module did not solve — stay humble:
- Prompt injection has no complete defence. Every lesson assumed it succeeds and limited blast radius; the field's open problem is provable isolation between instructions and data.
- Jailbreak robustness is an arms race. New techniques appear constantly; no model is jailbreak-proof; your defences are layers, not walls.
- Agent security is immature. Permission models, approval UX and audit trails are improving but not settled; expect the tooling to change.
- Safety evaluation is unsolved. Measuring harmfulness, bias and over-refusal reliably at scale remains an open research problem (Module 10A owns the eval side).
- The threat landscape moves. New models, new modalities (audio/video injection), new agent patterns create new surfaces — the detection catalogue and OWASP lists are living documents.
Stay current — sources to follow:
- OWASP GenAI Security Project (genai.owasp.org) — the LLM Top 10 (2026 edition, August 2026) and Agentic Top 10; cheat sheets; the AI Bill of Materials initiative.
- MITRE ATLAS (atlas.mitre.org) — adversary TTPs against AI systems; monthly content releases.
- NIST — AI RMF + GenAI Profile (AI 600-1), SP 800-61r3 incident guidance, CSF 2.0.
- Provider security channels — OpenAI's safety/best-practices docs and disclosure policy, Anthropic's Transparency Hub and Usage Policy, Google DeepMind safety publications, OpenRouter's docs.
- AI Incident Database (incidentdatabase.ai) — real-world AI harm events; incident IDs run past 1,800 as of November 2026.
- Research venues — IEEE S&P, USENIX Security, ACM CCS, NeurIPS/ICML safety workshops; arXiv cs.CR/cs.LG.
Where next. Module 12 gave you the defensive engineering layer; Module 13A: Product Engineering, UX and Decision Frameworks turns it into products — AI UX and product architecture — and Module 13B: Capstones integrates everything you've built. Module 14B: Career Appendix helps you talk about all of it.
Appendix: the consolidated llm_guard_kit package#
One package, built across the module, each module pure-Python and composable:
| Module | File | Provides |
|---|---|---|
| 12.1 | threatmodel.py |
Capability-file checker: lethal-trifecta, rule-of-two, unapproved-consequential-tool, egress-with-private-data and secrets-in-context findings |
| 12.2 | injection.py |
Spotlighting/datamarking helpers, canary-token generator + detector, heuristic injection scanner, markdown/URL exfil sanitiser, dual-LLM skeleton (ScriptedModel) |
| 12.3 | policy.py |
Declarative content policy → thresholds → actions, refusal templates, escalation tracker |
| 12.4 | pii.py |
PII validators/detectors, Presidio-style analyser interface, PiiVault tokenise/restore, scrub-for-logging, fixture evaluator |
| 12.5 | guards.py |
Guard protocol, input/output pipelines, schema/URL/markdown/HTML sanitisers, SQL read-only validator, streaming checker, action matrix |
| 12.6 | permissions.py |
PermissionBroker (risk tiers, scoped creds, approval tokens), ToolPinning, audit log |
| 12.7 | supply_chain.py |
Secret-pattern and entropy scanner (also a file-scanning CLI: python -m llm_guard_kit.supply_chain FILE), requirements and uv.lock hash auditors, model-file safety checker (pickletools) |
| 12.8 | redteam.py (+ the agent_example.py and http_target.py sketches in 12.8) |
Red-team harness, target adapters, token/regex/action/judge oracles, a state-oracle pattern for agents, report generator, YAML case schema |
| 12.9 | responsible.py |
Counterfactual fairness runner, system-card/impact-assessment generator |
| 12.10 | secops.py |
SecurityEvent schema, Rule/Alert engine, detection catalogue, spend_anomalies, probing_clusters, fixture day |
Typical wiring for a RAG feature: injection.py scan on retrieved docs → guards.py input pipeline → model call → guards.py output pipeline → pii.py scrub before logging → permissions.py on any tool call → secops.py rules over the emitted events → redteam.py suite in CI.
Common misconceptions#
| Misconception | Reality |
|---|---|
| "We have guardrails, so we're covered." | Guardrails are one layer. Coverage means measured detection (Part 1), tested defences (12.8) and a rehearsed response (Part 3) — not just controls that exist. |
| "The system prompt keeps the model safe." | It's a trained tendency, not a security boundary (12.2). Detection and blast-radius limits are the real controls. |
| "We'll know if we're attacked — users will tell us." | Sophisticated abuse is silent by design. Detection engineering exists precisely because you can't rely on reports. |
| "More logging = more security." | More security-relevant logging, minus content. A SIEM full of raw prompts is a breach waiting to happen (1.5). |
| "An incident means we failed." | Incidents are how you learn where the model's assumptions break. The failure is not having a runbook, evidence or a regression test afterwards. |
| "Banning abusers is the enforcement strategy." | Progressive enforcement (warn→throttle→suspend) with working appeals catches abuse and preserves trust; instant bans generate false-positive harm and bad PR. |
| "The provider handles abuse for us." | Providers enforce at the org level. Without safety_identifier and your own per-user detection, one abuser can cost you the whole account. |
| "Security is a launch checklist item." | It's a lifecycle: threat model at design, gates in CI, detection in production, tabletop in operations, review after every incident. |
| "We can wait for a breach before writing the runbook." | Tabletop exercises exist because the first time you use a runbook should not be during an incident. |
| "Open-source models are the security risk; APIs are safe." | The API boundary adds provider-side safety but also adds your responsibility for what you send and do with outputs. Neither is "safe" — both are managed risk. |
| "Once the checklist is done, security is done." | The checklist is a snapshot. The maturity model and 30/60/90 plan exist because security posture decays without maintenance. |
Key takeaways#
- Detection is a layer, not an afterthought. The security event schema (metadata + scores + hashes, never content) feeds rules-as-code: windowed thresholds, per-actor baselines, severity routing, human-review sampling.
secops.pyimplements the whole loop in ~200 stdlib lines. - Alert on combinations, not single signals. Canary + egress + PII-in-output is an incident; any one alone might be noise. Correlation beats counting.
- Abuse ≠ incident. Abuse uses the system as designed for illegitimate ends; respond with progressive enforcement (warn→throttle→suspend→ban) and working appeals, backed by quotas, spend caps and provider
safety_identifiers. - Provider abuse systems are a backstop, not a sensor. OpenAI's safety classifiers warn then restrict orgs; Anthropic's Safeguards warn/throttle/suspend; your own detection must act first.
- LLM incidents need LLM runbooks. Contain by cutting tools/egress/secrets before investigating; eradicate architecturally (not "fix the prompt"); preserve the four-version tuple (prompt/model/trace) as evidence; expect non-determinism to complicate reproduction.
- Two clocks run in every breach. The technical clock (contain fast) and the legal clock (GDPR's 72-hour awareness deadline) — know your obligations before you need them.
- Security lives in the SDLC. Threat model at design, secure-glue-code review, CI gates (secrets/deps/red-team), kill switches for every high-risk capability, security champions for culture.
- Disclosure is a feature.
security.txt(RFC 9116), a monitoredsecurity@, triage SLAs and coordinated disclosure turn external researchers into allies. - The checklist is a launch gate, not a destination. Use the one-pager to ship, the maturity model (0–4) to locate yourself, and the 30/60/90 plan to climb — security posture decays without maintenance.
- Module 12's honest bottom line: prompt injection has no complete defence, jailbreaks are an arms race, agent security is immature, and safety evaluation is unsolved. The module's answer is layered, measured, rehearsed defence — and staying current via OWASP, MITRE ATLAS, NIST, provider channels and the AI Incident Database.
Terms introduced in this lesson#
| Term | One-line definition |
|---|---|
| Security event | A normalised, content-free record of a security-relevant action (call, guardrail decision, tool call, egress attempt) |
| Detection engineering | Writing, testing and maintaining alert rules as versioned code rather than ad-hoc queries |
| Rules as code | Detection rules stored as data (name, predicate, window, threshold, severity) in version control |
| Windowed threshold | An alert condition evaluated over a rolling time window (e.g. ≥5 events per user per hour) |
| MAD (median absolute deviation) | A robust spread measure that resists outliers, used for spend-anomaly baselines |
| Probing pattern | Systematic near-duplicate or boundary-testing requests from one account |
| Exfiltration indicator | Evidence an actor tried to move data out (non-allow-listed domain, unusual outbound tool call) |
| Guardrail bypass signal | A pattern suggesting a detector was evaded or drifted (denied-then-succeeded, score shifts) |
| Abuse case | Illegitimate use of a system working as designed, vs a security incident where a control failed |
| Progressive enforcement | The warn→throttle→suspend→ban ladder for abuse, with appeals |
| Denial-of-wallet | An attack or failure that burns money via unbounded model spend |
| Incident severity (SEV-1..4) | Blast-radius × exploitability × sensitivity rating for triage and response |
| Tabletop exercise | A facilitated walkthrough of an incident scenario to find gaps before a real incident |
| Evidence preservation | Snapshotting traces, events and outputs immutably before remediation |
| Chain of custody | The logged record of who accessed incident evidence and why |
| Blameless postmortem | A review focused on systemic causes, not individual blame |
| Coordinated disclosure | Privately reporting a vulnerability to the owner, agreeing a fix+disclose timeline |
security.txt |
RFC 9116 machine-readable file advertising your vulnerability-disclosure contact |
| Vulnerability disclosure policy (VDP) | Your published rules for receiving and handling vulnerability reports |
| Bug bounty | A programme paying reporters for qualifying vulnerabilities |
| Security champion | A designated engineer per team who owns security-review depth |
| Configuration baseline | A documented secure-default configuration new features copy |
| Maturity model | A 0–4 scale rating security-programme sophistication |
| llm_guard_kit | The module's consolidated pure-Python guardrail/security package |
Two terms this lesson uses but does not introduce keep their earlier definitions: safety identifier (the provider-facing hashed user ID, introduced in 03.2; this lesson adds the abuse-attribution purpose in 2.2) and kill switch (introduced in 08A.14; this lesson adds the security-layer switch table in 4.4).
All terms are also collected in the glossary.
Exercises#
- Run the detector. Assemble
secops.py,fixture_day.pyandrun_secops_demo.pyfrom the code blocks in 1.6 intollm_guard_kit/(with an empty__init__.py), then from the project root runpython -m llm_guard_kit.run_secops_demo— a plainpython llm_guard_kit/run_secops_demo.pyfails because the runner imports the package by name. Then modify the fixture: add aguardrail.decisionwithpii_findings=0, channel="input"(should not firepii-in-output) and three decisions withinjection_score=0.9from the same user, placed after offset 2900 so they fall within 10 minutes of the newest event (should fireinjection-detector-cluster; the window ends at the newest event in the batch). Explain the difference between input-side and output-side PII signals. - Tune a threshold. Change
refusal-spike'sthresholdto 20 and re-run. Which alerts disappear? Now changewindow_secondsto 600. What does the window do to recall vs noise? Write down the trade-off. - Tabletop Scenario 1. Run the poisoned-support-ticket tabletop with a colleague. Time-box containment decisions to 10 minutes. Afterwards, list which detection rules from Part 1 would have fired earliest and which were missing.
- Fill the checklist. Take a real feature you've built (or the Module 07
docs_qabot) and fill the 6.1 checklist honestly — mark N/A only with a reason. Identify your three biggest gaps. - Write a runbook. Draft a one-page runbook for your most likely incident type using the Playbook A–G skeleton. Include: detection signals, first three containment actions, evidence to preserve, comms template, and the regression test you'll add.
- Threat-model delta. For a proposed feature change (new tool, new data source, new audience), write the security-requirements delta: what new untrusted inputs appear, what new exfiltration channels, what detection rules are needed.
- Maturity assessment. Score yourself on the 6.2 model for a project you know. Defend the level with evidence; name the single control that would move you up one level.
Check yourself#
- What's the difference between a security event and a product/ops log line, and why does the security path exclude content?Security events carry metadata, scores, hashes and IDs — not prompts, completions or documents — so the security pipeline can be broadly accessible and long-retained without becoming a PII/content store; content stays in the access-controlled product path.
- Name four families of detection signal and give one example each.Attack indicators (canary triggers, injection-detector hits), abuse indicators (probing patterns, refusal spikes), control failures (unapproved tool calls, guardrail bypass), business anomalies (spend/token anomalies).
- Why do detection rules use windowed thresholds and per-actor baselines rather than simple counts?Single events are noisy; rates over windows separate bursts from background. Per-actor baselines stop your biggest legitimate user from setting the threshold for everyone.
- What's the difference between an incident and an abuse case, and which response ladder applies to each?An incident is a control failure or bypass; abuse is legitimate-use-for-illegitimate-ends. Incidents get contain/eradicate/recover; abuse gets the progressive-enforcement ladder.
- Why must you pass
safety_identifier(or equivalent) to providers, and what happens if you don't?So providers can attribute abuse to your end users instead of your whole org — and so you can map their warnings back to accounts. Without it, enforcement degrades to org-level blocks and you lose attribution. - What are OpenAI's documented abuse-enforcement steps, and what should you set up before you need it?Safety classifiers flag high-risk requests; repeated threshold hits → errors + warning email; continued violations (~7 days) → access stopped. Set up safety-enforcement notifications routing to your workflow.
- In a prompt-injection incident, why do you disable outbound tools before investigating?Because an active exfiltration channel does damage every minute it runs; containment precedes investigation. A read-only context can't exfiltrate.
- What four pieces of information must you preserve for any model output involved in an incident?
prompt_version,model_key,resolved_model, and the trace/span IDs — without all four you can't reconstruct or defend what happened. - What is GDPR's notification clock for personal-data breaches, and from when does it run?72 hours from becoming aware (GDPR Art. 33), with Art. 34 adding data-subject notification for high-risk cases. "Aware" is a documented decision — timestamp it.
- What's the difference between a kill switch and a feature flag in a security context?A kill switch is a fast, external, security-critical off-ramp tested in incident scenarios; a feature flag is general rollout machinery. Security needs switches that work even when the feature's own systems are compromised.
- Name three CI security controls every LLM project should have.Secret scanning, dependency/vulnerability scanning with lockfile hashes, and a red-team regression gate on security-relevant changes.
- What does
security.txtdo, and which RFC defines it?It advertises your vulnerability-disclosure contact in a standard machine-readable format at/.well-known/security.txt; defined by RFC 9116 (April 2022). - What's the difference between coordinated disclosure and a bug bounty?Coordinated disclosure is privately reporting a vuln to its owner and agreeing a fix+disclose timeline; a bug bounty is a paid programme incentivising the same reports at scale.
- Which maturity level describes "we have controls but don't know if they work"?Level 2 — "Managed": controls exist and are tested, but detection coverage and effectiveness aren't yet measured (that's level 3).
- What's the module's honest bottom line on prompt injection?It has no complete defence today — the module's answer is layered, measured, rehearsed defence that assumes injection will sometimes succeed and limits what it can do.
Further resources#
- OWASP GenAI Security Project — Top 10 for LLM Applications 2026 (August 2026) and Top 10 for Agentic Applications (December 2025); the project home at genai.owasp.org.
- MITRE ATLAS — atlas.mitre.org and the atlas-data repository: adversary tactics/techniques against AI systems, monthly content updates.
- NIST — AI RMF 1.0 and AI 600-1 GenAI Profile; SP 800-61r3 incident response (April 2025); CSF 2.0 six functions.
- ISO — ISO/IEC 42001:2023 (AI management systems); ISO/IEC 27035-1:2023 (incident management).
- GDPR — Article 33 breach notification (72 hours); Article 34 data-subject notification.
- security.txt — RFC 9116 and the IANA field registry; CISA's security.txt guidance.
- Canarytokens — canarytokens.org / canarytokens.com: free digital tripwires (Thinkst).
- AI Incident Database — incidentdatabase.ai: real-world AI harm events (incident IDs run past 1,800 as of November 2026).
- Provider security docs — OpenAI safety checks and coordinated disclosure policy; Anthropic Usage Policy, Transparency Hub enforcement statistics and Safeguards warnings/appeals; OpenAI security.txt.
- SIEM/observability — Microsoft Sentinel in the Defender portal (Microsoft's page says Sentinel is supported in the Azure portal only until 31 March 2027); Splunk, Elastic Security and Datadog Security at their official docs.
- CERT — The CERT Guide to Coordinated Vulnerability Disclosure (living web edition; original report CMU/SEI-2017-SR-022, SEI library copy).
← 12.9 — Responsible AI, Policy and Compliance | Module 12 overview | Module 13A: Product Engineering, UX and Decision Frameworks →