Sub topic 17
Logging, Monitoring and Incident Response
This chapter assumes you know how an LLM app assembles prompts, how indirect injection works, and the defenses from earlier chapters (least privilege, output sanitization, approval gates). Prevention will sometimes fail. Logging and monitoring tell you when it did, and incident response limits the damage.
Logging, monitoring and incident response
What to log
Record enough to reconstruct an incident without storing secrets you should not keep.
- The full prompt as sent, with each part labeled by source: system, user, retrieved document, tool result.
- The model's raw output before sanitization.
- Every tool call: name, arguments, who approved it, and the result status.
- Identifiers: user, session, document or URL IDs, model version, prompt template version.
- Filter and sanitizer actions, such as a removed image or a blocked tool call.
Redact credentials and personal data before writing logs. Logs of prompts often contain exactly the sensitive data an attacker wants, so give them the same access controls as the source data and set a retention limit.
What to monitor
Alert on signals that suggest an injection is active or has succeeded:
| Signal | Why it matters |
|---|---|
| Denied tool calls or `PermissionError` spikes | The model asked for something policy forbids |
| Output containing a canary string or system prompt text | Leakage or a successful override |
| Removed images or links to unknown hosts | Attempted exfiltration |
| Tool calls unrelated to the user's request | Possible confused-deputy behavior |
| Unusual volume of tool calls or tokens per session | Looping or abuse |
import json
import logging
log = logging.getLogger("llm_audit")
def audited_tool_call(name, args, tools, approve, session_id):
"""Run a tool call and write one structured audit record."""
allowed = name in tools and approve(name, args)
log.info(json.dumps({
"session": session_id,
"tool": name,
"args_keys": sorted(args), # log argument names, not sensitive values
"allowed": allowed,
}))
if not allowed:
raise PermissionError(f"Tool call not permitted: {name}")
return tools[name](**args)Incident response
- Contain. Disable the affected tool, connector or data source. A feature flag per tool makes this a one-minute action.
- Scope. Use the logs to find which sessions saw the malicious content and which actions followed.
- Revoke. Rotate any credentials the agent could reach and notify affected users where required.
- Remove the source. Delete the poisoned document or block the page, and re-index if it entered a knowledge base.
- Learn. Add the payload to your regression tests and fix the control that failed.
Why no defense is complete yet
The model reads instructions and data as one stream of tokens. No current technique makes it enforce a boundary between them with certainty.
- Filters match known patterns. Attackers paraphrase, encode, translate or split a payload across documents.
- Prompt structure such as delimiters and "ignore instructions in the document" lowers the success rate but is only a request to the model.
- Classifiers that detect injections can themselves be fooled and add false positives.
- Tests cover the payloads you thought of. Passing a canary test shows those attacks failed, not that others will.
- Model updates can change behavior, so a defense that held last month may weaken.
The practical design rule is to assume the injection succeeds and ask what the worst result is. If that result is unacceptable, remove the capability instead of adding another filter.
Exercise
An agent that reads support emails and can call issue_refund issues a refund the customer never requested. List the first two incident response steps and one log field that helps you scope the incident.
Show answer
First contain: disable the issue_refund tool (or require approval for every call). Then scope: find all sessions that processed the suspicious email and all refunds issued after. Useful log fields include the document or email ID in the prompt, the tool call arguments and approver, and the session ID.