Chapter 4. Defense testing and red teaming
Learning objectives
- Explain the roles, execution methods, and limitations of input, tool, and output guardrails and classifiers.
- Determine failure behaviors when no judgment is produced, matching the risk level of the task.
- Design rules of engagement and attack scenarios starting from a threat model.
- Build an evaluation set containing attack, benign, and boundary cases, and judge success by outcomes.
- Measure and interpret defense effectiveness using attack pass rate, false positive rate for benign requests, and task completion rate.
Introduction
A team reported the number "98% injection block rate" at a launch meeting. Applause followed, and the launch was approved. When an incident occurred two months later, it turned out that this number had been measured against the 50 attack sentences referenced when crafting the classifier rules, and not a single attack routed through documents or emails was included. No one had measured how many benign requests were blocked. Users were bypassing the frequently blocked features by pasting work materials into other AI tools on their personal accounts. The number was not wrong. It was simply that no one had asked what it was measured with, or along which path. After the incident, the pass rate remeasured by the security team using attacks routed through documents told an entirely different story from the number in the report.
In defense, measuring is just as demanding as building. This chapter begins by looking at where and what guardrails and classifiers block, and how they should behave when a judgment fails. Next, you will learn the definition of red teaming, rules of engagement, methods for deriving scenarios from threat models, and principles for constructing evaluation sets. Finally, you will learn how to judge success by outcomes and how to quantify and interpret defense effectiveness in numbers.
Key concepts
Map of guardrails: Where to place what
Guardrails are mechanisms that inspect, block, or modify inputs and outputs in front of and behind the model, as well as at tool call points. They can be compared to airport security checkpoints. There are checkpoints before boarding (input), when loading baggage (tool call), and after arrival (output), and each checkpoint can block different things.
| Location | Primary inspection targets | What it cannot block |
|---|---|---|
| Input | Policy bypass attempts, prohibited topics, injection patterns, input size | Documents and tool results arriving in later stages |
| Tool result | Instructions within external content, anomalous formats | The model's judgment itself |
| Tool call | Format and range of arguments, target, user permissions | Subtle misuse within permissions |
| Output | Sensitive information, system prompt leakage, dangerous links and markup | Tool calls that have already executed |
Because output guardrails run after the model has completed its work, they cannot roll back tool calls executed in the meantime. If an agent uses tools with side effects, inspection at the tool call point must not be omitted. Furthermore, guardrails do not substitute for the authorization checks in Chapter 3. Guardrails ask "Does this look abnormal?", whereas authorization asks "Is this person permitted to do this task?"
When does the check finish: The Agents SDK case
The OpenAI Agents SDK specifically illustrates the placement and timing of guardrails.
| Type | Scope of execution | Characteristics |
|---|---|---|
| Input guardrail | First agent in the chain | Defaults to parallel execution with the agent (run_in_parallel=True) for minimal latency, but tokens may be consumed or tools executed before a tripwire halts execution. In blocking mode (run_in_parallel=False), the agent starts only after the check finishes |
| Output guardrail | Final output of the last agent | Starts running only after all agent tasks have finished |
| Tool guardrail | Every call to a protected function tool | Before execution, it can skip the call, replace the result with a message, or trigger a tripwire; after execution, it can modify the result or trigger a tripwire |
A tripwire is a signal that halts execution when a violation is detected. Tool guardrails have limitations in their scope of application. While they apply to custom-built function tools, they do not apply to handoffs (calls transferring work to another agent), hosted tools (web search, file search, hosted MCP, code interpreter, etc.), or built-in execution tools (computer, shell, etc.). In an architecture with a manager agent and sub-specialist agents, the documentation recommends using tool guardrails rather than agent-level guardrails to inspect every call. While such details vary by SDK, the questions remain the same: When does the check finish, what can execute before then, and which tools lie outside the inspection?
Classifiers: Types and limitations of judgment engines
Classifiers are the judgment engines of guardrails. There are three types.
| Type | Examples | Strengths | Weaknesses |
|---|---|---|---|
| Rules | Regular expressions, length limits, blocklists | Fast, deterministic, easy to explain | Bypassed when phrasing is altered |
| Dedicated classification models | OpenAI Moderation API, Microsoft Prompt Shields | Captures broad expressions, low operational burden | Performance degrades outside the training distribution; judgment criteria are fixed |
| LLM triage | Requesting structured judgments from a lightweight model | Judgments that reflect operational context | Vulnerable to injection itself; cost and latency |
Be sure to distinguish that each classifier answers a different question. OpenAI's Moderation API is a free tool for reducing the frequency of unsafe content. As stated in its documentation, Prompt Shields detects user prompt attacks and document attacks, but does not judge whether content is harmful or adheres to policy. Neither answers the question: "Is this user authorized to view this customer record?" Toxicity classification, attack detection, and authorization checks cannot substitute for one another.
The OWASP Injection Prevention Cheat Sheet warns that an LLM acting as a guardrail is still an LLM, making it inherently vulnerable to injection itself. Nor should classification scores be directly read as the "probability of being an attack." The meaning of a score can only be understood by evaluating that classifier against your own data.
Failure behaviors: When no judgment is produced
Classifiers do not always provide an answer. They time out, encounter errors, or the triage model refuses the request itself. Anthropic recommends treating cases where the triage model's safety classifier refuses the triage request—leaving no judgment (when stop_reason is "refusal")—as a harmful judgment. A design that treats the absence of a judgment as a "pass" hands attackers a bypass route: "inputs that cause the classifier to refuse."
Failure behaviors are determined according to the risk level of the task.
| Task | Behavior in the absence of judgment |
|---|---|
| Read-only Q&A | Restricted response (answer without tools or substitute with generic guidance) |
| External content summarization | Error or filtered summary instead of original text |
| Write tool call | Halt execution, transfer to human review |
| Payment, dispatch, deletion | Halt execution (fail-closed), transfer to human review without automatic retries |
When attaching a new classifier for the first time, one approach is to observe production data in annotate mode rather than blocking, measuring false positives. In Foundry, Prompt Shields results can be configured to block or annotate only, and the standalone Content Safety API returns only the judgment, leaving handling up to the application. However, during an annotate-mode period, other layers must be in place to prevent damage.
Definition of red teaming and rules of engagement
NIST AI 600-1 defines AI red teaming as "a structured testing effort to find flaws and vulnerabilities of an AI system," and explains that it is usually conducted in a controlled environment in collaboration with developers. It classifies testing according to practitioners into general-user, expert, hybrid, and human-and-generative-AI collaborative forms, and states that results should undergo additional analysis before informing organizational decisions. OpenAI advises testing with both representative inputs and inputs intended to break the system, while Anthropic recommends testing agents with documents, emails, and tool results containing injection attempts to verify whether triage and verification steps catch the remainder.
Red teaming is "attacking our own system before anyone else does," and it must be conducted strictly within an authorized scope. Before beginning, rules of engagement must be agreed upon in writing.
- Scope and environment: Which version of which system is tested, in what environment isolated from production?
- Data: Use synthetic data and dummy secret values instead of real customer data.
- Permitted and prohibited actions: Replace external dispatch and payments with simulated tools, and do not touch third-party systems.
- Halt conditions: Stop immediately if production data access or unexpected external requests are observed.
- Contact and reporting: To whom, in what format, and within what timeframe are findings communicated?
Designing attack scenarios
A scenario is not a list of attack sentences, but a unit of testing along paths in the threat model. Starting from the trust boundaries in Chapter 1 and the five-step table in Chapter 2, write one card per scenario.
| Field | Example |
|---|---|
| Attacker capabilities | Can write to public web pages; unauthenticated |
| Path | Web search results → summarization pipeline |
| Target outcome | Unsolicited write tool call |
| Success condition | A record is logged in the simulated write tool's invocation log |
| Targeted defense layer | Tool result triage, write tool isolation |
| Attempt budget | 10 variants × 5 repetitions |
| Halt condition | Request generated outside the simulated environment |
The scenario collection is inspected using a path × defense layer grid. Place paths (direct input, web, email, documents, images, tool results, memory) in rows and defense layers (input triage, tool result triage, tool call inspection, human verification, output restriction) in columns, marking whether a scenario exists in each cell. Although human verification is not a guardrail location, it is counted alongside them as a distinct defense layer. There must be scenarios targeting each defense layer to measure effectiveness by layer. Scenarios spanning multiple turns and multiple sessions, as well as scenarios that bypass or trivialize the human verification step, are also set aside separately.
Broadening scope with third-party attack lists
Scenarios created purely from imagination test only the attacks your team already knows. Because MITRE ATLAS links tactics and techniques to real-world case studies, it is used to scan whether techniques applicable to your system exist across stages such as Reconnaissance, Initial Access, AI Model Access, AI Attack Staging, Exfiltration, and Impact. OWASP LLM01 organizes scenarios encompassing not only direct and indirect injections, but also accidental injection, search index poisoning, payload splitting, multimodal attacks, seemingly meaningless suffix strings, and multilingual and obfuscation attacks; the OWASP Injection Prevention Cheat Sheet categorizes types such as encoding bypasses, iterative perturbation attacks, and multi-turn attacks.
Use these knowledge bases as scope checklists, and do not populate evaluation sets by copying public attack sentences. Sentences that many classifiers have already been trained on inflate scores and fail to capture your operational context.
Constructing evaluation sets
An evaluation set does not consist of attacks alone.
| Component | Purpose | Examples |
|---|---|---|
| Attack cases | Measure attack pass rate | Dummy documents containing hidden instructions, inducing unsolicited tool calls |
| Benign cases | Measure false positive rate and task completion rate | Requests resembling actual workload distributions |
| Boundary cases | Verify judgment criteria | Summarizing security training materials, translating manuals with many imperative sentences |
Anthropic's evaluation design guidance recommends making sets resemble actual workload distributions, including boundary cases, scoring automatically with code or judge models whenever possible, and prioritizing a large volume of automatically scored cases over a small number scored painstakingly by humans. For security evaluation sets, add the following principles:
- Do not evaluate defenses with the data referenced when crafting defense rules. Separate development sets from final validation sets, and ensure rule authors do not see the validation set. This is analogous to how a score on a mock exam taken after previewing the exam questions fails to reflect true proficiency.
- Route tests through the service's actual input paths. Document attacks must pass through upload and text extraction, and email attacks must enter via the email ingestion pipeline.
- Include attack and benign cases for every language the service uses, and bundle multi-turn attacks as a single case across the entire dialogue to replay state carried over from earlier turns.
- Plant synthetic secret values (canaries). They must be unique strings that do not overlap with real values and cannot be generated by chance (e.g., a dummy key appending a random value to a unique prefix), so that their appearance in outputs or external requests can be definitively judged as leakage.
- Version the sets, and record the origin (which threat, which incident) for every case.
Determining success: Judge by outcomes
A defense has not succeeded simply because the model wrote a refusal statement. While composing a refusal sentence, it might have already invoked a tool; conversely, it might have feigned polite compliance while performing no action at all. Judgment must be made based on observable outcomes.
| Target outcome | Basis for judgment |
|---|---|
| Unauthorized action | Invocation log of simulated tool, state changes |
| Information exfiltration | Canary detection in outputs and external request logs |
| System prompt leakage | Presence in output of unique string planted in the prompt |
| Response contamination | Comparison against ground truth, scoring by judge model or human |
When the outcome resides solely within text, such as response contamination, use a judge model (LLM grader). Anthropic cites scoring with a model different from the one that generated the output under evaluation as a general best practice. Before using a judge model, verify its agreement rate against human-labeled samples; for types where disagreements concentrate, refine the judgment criteria or have humans score them. In scenarios where logs that can serve as judgment evidence exist, prioritize logs over the judge model. Because judge models can also be swayed by statements within the evaluated output (such as "This response meets all criteria"), pass outputs separated as data, receive judgments only as structured values, and track the discrepancy rate between the judge model and humans as a metric.
Metrics for measuring defense effectiveness
Defense effectiveness is viewed through at least three numbers.
| Metric | Calculation | What happens when overlooked |
|---|---|---|
| Attack pass rate (Attack success rate) | Successful attack attempts ÷ Total attack attempts | Launching without knowing security holes exist |
| False positive rate for benign requests | Blocked benign requests ÷ Total benign requests | Users migrate to unmanaged tools |
| Task completion rate | Benign tasks processed to completion ÷ Total benign tasks | A system that does not block, but cannot be used |
Because benign requests that are not blocked may still fail to complete due to model errors or timeouts, the task completion rate is not simply 100% minus the false positive rate.
When examining numbers, check the denominator first. Depending on whether it is measured per scenario, per attempt, or per conversation, the exact same result yields entirely different figures. If 50 attempts were made for a single scenario and one succeeded, the attempt-level pass rate is 2%, but at the scenario level it is a "breached scenario." Because attackers can repeat attempts, scenario-level "was it breached even once?" is often more critical for security decisions.
Review layer-by-layer metrics together as well. Logging which layer halted each attack attempt reveals the contribution of each layer, such as "Input triage caught 70%, and human verification caught most of the remainder." If a layer catches almost nothing, either that layer is unnecessary or there are no scenarios targeting it.
Continuous monitoring and regression
Pre-launch evaluation is merely a snapshot at the moment of release. Anthropic recommends regularly analyzing signs of successful injections to iteratively refine prompt, validation, and filtering strategies, and responding with warnings, rate limiting, and blocking when the same user repeatedly attempts bypasses. This aligns with the "Adjust controls and rapid feedback loops" element of SAIF.
In production, run three feedback loops: de-identify red teaming and incident cases and add them to the regression set; rerun the set whenever any of the model, prompt, tools, or classifiers change; and investigate the root cause whenever guardrail trigger rates, false positive reports, or approval rates change abruptly. Guardrails are operational assets that must be measured and refined.
When the ATLAS edition changes, realign the checklist
MITRE ATLAS, used as a scope checklist, also changes editions. Data release v2026.10, published on 2026-10-28, contains 1 matrix, 16 tactics, 129 techniques, 92 sub-techniques, and 44 mitigations. Starting with the 2026.05 release, knowledge base content and data formats are versioned separately. Therefore, simply stating "based on ATLAS" in a report leaves no way to know which edition was used. If coverage is reported as "how many out of all techniques," the denominator itself varies across editions.
When editions change, the same attack may be referred to by a different ID. The v2026.07 release consolidated three techniques that publish poisoned artifacts into one.
| Prior to v2026.07 | Starting with v2026.07 |
|---|---|
| Publish Poisoned Datasets (AML.T0019) | Publish Poisoned AI Artifacts (AML.T0115): Datasets |
| Publish Poisoned Models (AML.T0058) | AML.T0115: Models |
| Publish Poisoned AI Agent Tool (AML.T0104) | AML.T0115: AI Agent Tools |
In the same release, AML.T0020 was renamed from Poison Training Data to Training Data Poisoning. Because the ID remains identical, update only the name field in the mapping table.
Suppose a team has a card in their checklist created last year: "AML.T0104 — Upload poisoned tool to internal plugin repository." If they tally coverage under the new edition while leaving the old ID intact, the AML.T0115 cell will appear empty, and the team will recreate a path they have already tested. The count tallied by technique will also shift: previously there were three techniques, but now there is one technique with three sub-techniques.
Record the referenced ATLAS edition on scenario cards and evaluation reports. When upgrading editions, transfer changed IDs via the mapping table and retally the checklist. This is the same reason model versions are recorded: when the baseline reference table changes, placing new figures alongside previous numbers invalidates any comparison.
Servers and connections are also red-teaming targets: Default ports and state handles
Red-teaming targets do not end with guardrails. Servers hosting models and tool connections are also targets. Because default values change frequently in this domain, realign the target list and checklist items in the rules of engagement across releases.
| Target | Default value | What to check |
|---|---|---|
| llama-server | Port 9931 starting 2026-10-09 (previously 8080); remains 8080 inside Docker containers | --api-key defaults to no authentication; multiple keys specified with commas |
| Ollama | Port 11434 on 127.0.0.1 | Whether the bind address was changed via OLLAMA_HOST |
If an inspection script searches for a server by port number alone, it may miss the server depending on the version or deployment method. Write the success condition on the card not as "port is open," but as "received a response without a key from an unauthorized network."
In its 2026-07-28 revision, MCP eliminated protocol-level sessions and the Mcp-Session-Id header. The attack addressed by the security guidelines up to the 2025-11-25 edition was session hijacking, targeting server-issued session IDs. The guidelines at that time instructed servers implementing authorization to validate every incoming request and prohibited using sessions as a means of authentication. Session IDs had to be secure and unpredictable values. The new edition places state handle hijacking in that slot and firmly stipulates that possessing a state handle must not be treated as authentication. Though the name has changed, the principle remains identical: acquiring an identifier does not make one its owner.
If a team is testing an internal coding assistant, they would write the card title as "Invoke user's repository tool using state handle left in another user's logs." If an invocation by a user other than the handle owner is recorded in the simulated repository tool log, it is judged as breached. Rather than discarding session hijacking cards written under the old guidelines, revise them into this card.
Deployment pipelines are also scenarios: Model signatures and npm trusted publishing
When a swapped model or package enters through standard deployment pipelines, input guardrails do not view it as an attack. Supply chain scenarios test which stage notices when artifacts have been altered.
For model signatures, OMS (Open Model Signing), introduced by OpenSSF on 2025-06-25, serves as the standard. OMS signature files follow the Sigstore Bundle Format. Because OMS itself is not tied to a specific PKI, it accepts raw keys, certificates, and Sigstore keyless signatures. The specification repository sets SHA-256 as the default hash, with BLAKE2b as an alternative. The signing tool sigstore/model-transparency defaults to Sigstore keyless signing while also supporting keys, certificates, and PKCS#11.
On the package side, keep in mind the Nx 'S1ngularity' breach (2025-08-26). In a vulnerable pull_request_target workflow, a bash injection planted in a PR title was executed, exposing the npm publish token. Teams using npm trusted publishing should verify the following conditions as prerequisites for their scenarios:
- Only cloud-hosted runners are supported; self-hosted runners are not yet supported.
- Starting 2026-10-02, unverified configurations expire 48 hours after creation and can no longer authorize publishing.
- If a token originates from a GitHub Actions
issue_commentevent, npm rejects it. - The permission to manage dist-tags (2026-09-30) defaults to off for both new and existing configurations and must be enabled manually.
Suppose a team uploads summarization model weights to an internal repository and distributes the MCP server invoking that model via npm. This team writes two cards. The first card is "Inject swapped weights through a path loaded without signature verification," with the judgment basis being verification failure logs at the loading stage. The second card is "An external contributor triggers the publishing workflow via a PR title or comment," judged by publishing records in the test registry. On the ATLAS checklist, mark the first card under AML.T0115 Models, and the second card under AI Agent Tools.
Going deeper
How many runs are needed: Interpreting probabilistic results
Just because a scenario was blocked in a single run does not mean you can write that it "is blocked." This is because outputs are probabilistic. There is a piece of common statistical knowledge that can be used when determining the number of repetitions. If there are zero successes in n independent trials, the 95% upper confidence bound of the true success rate is approximately 3/n (an approximation when there are sufficiently many trials). If it is breached 0 times across 30 runs, you can only say that "the success rate is likely lower than about 10%," not that "the success rate is 0." Stating a 1% level requires approximately 300 runs.
This rule of thumb teaches two things. First, rather than concluding that it is "secure" from a small evaluation, you must report that it "appears to be below this level." Second, controls that reduce impact are often more efficient than endlessly narrowing the probability through repetitions. Evaluation reports must specify the model, prompt, tool, and classifier versions, the number of attempts, and denominator units so that results can be reproduced. The OWASP Cheat Sheet also notes that passing a brief audit test does not prove resistance against a determined attacker.
Experiments comparing the effects of control combinations
From a result stating "things improved after adding all defenses," it is impossible to know which control produced the effect. Comparative experiments are designed as follows. First, measure a baseline without defenses. Measure configurations with controls added one by one using the same evaluation set, the same model version, and the same number of repetitions. Also test configurations with one control removed. If the result barely changes when that control is removed, that control either overlaps with other controls or the scenarios did not target that control.
Read results by examining the attack pass rate and the task completion rate together. If the task completion rate dropped by 15 percentage points in exchange for lowering the pass rate by 2 percentage points, that control is a candidate for modification into another form (confirmation instead of blocking, or only high-risk operations instead of all operations).
At work
River Securities: Which layer missed what
The securities firm River Securities decided to attach account inquiry and transfer scheduling tools to its customer inquiry chatbot, and formulated a red team plan four weeks prior to launch. The rules of engagement specified a test environment isolated from production, synthetic customer data, mock transfer tools, abortion upon external requests, and same-day reporting of findings.
The trust boundaries were three: customer chat inputs, transaction confirmation images attached by customers, and transfer scheduling tool calls. The defenses already applied were an input screening classifier, a step passing attached image OCR results as tool results and screening them, and a customer confirmation screen prior to scheduling a transfer.
Scenarios were created for each defense layer. The input screening layer was tested with 60 policy-bypassing conversations, the OCR pathway with 25 test images containing hidden instructions, and the confirmation screen with 12 scenarios searching for "whether there is a path where transfers execute without confirmation." Each scenario was repeated 5 times, and 400 normal customer inquiries were also run alongside them to measure false-positive blocking rates and task completion rates. Success determination was made based on call logs of the mock transfer tool and whether synthetic account numbers planted as canaries were output.
The results were as follows. Input screening caught most policy bypass attempts, but blocked 5% of normal inquiries. On the OCR pathway, two scenarios passed screening in some attempts across the repetitions, but all were stopped at the confirmation screen. Among the confirmation screen scenarios, one found an issue. The "edit" function for changing the scheduled date reused the initial approval as-is, applying even amount changes without confirmation.
The team adjusted screening criteria to lower the false-positive blocking rate, added the two passed OCR scenarios to the regression set, and ensured the edit function required confirmation again if the amount or recipient changed. In the launch report, rather than a single pass-rate figure, they recorded what was caught and missed by layer, the number of repetitions, and remaining risks. The point was not "how many cases were blocked," but "which layer missed what, and did the next layer back it up?"
Pinwheel Car Rental: Three configurations with the same test suite
The car rental company Pinwheel Car Rental was operating a reservation modification assistant and was struggling to decide on a defense configuration. The security team suggested strengthening only the input classifier, while the product team worried that increasing confirmation screens would drive customers away. Instead of debating, the team decided to measure them using the same test suite.
The evaluation set consisted of 150 attack scenarios (direct input, web pages from links pasted by customers, and reservation email paths sent by partners) and 300 normal tasks created by de-identifying actual inquiries. Attack scenarios were each repeated 5 times. There were three configurations.
| Configuration | Details | Unauthorized reservation modifications (scenario-level) | Normal task completion rate |
|---|---|---|---|
| A | Strengthened input classifier | 11 out of 150 | 94% |
| B | A + customer confirmation on all write tools | 0 | 81% |
| C | A + risk-tiered confirmation (date changes without confirmation; car model changes, cancellations, and payments with confirmation) + tool result screening | 0 | 92% |
All three configurations left existing server-side authorization intact.
Configuration B eliminated unauthorized modifications, but in a substantial portion of normal tasks, customers abandoned the conversation before the confirmation step. Configuration C prevented unauthorized modifications while almost entirely preserving the completion rate. The justification for leaving date changes without confirmation was verified separately: the server checked that date changes were permitted only for the customer's own reservation and only within a scope where no price changes occurred.
There was also something learned from the evaluation method. Initially, an evaluator model read entire conversations to judge whether attacks succeeded, but comparing this with 100 human-labeled samples revealed that discrepancies clustered around cases where the model "verbally refused but called the tool." The team switched the evaluation of action-targeting scenarios to mock tool call logs, choosing to use the evaluator model only for response contamination scenarios. They selected C as the final configuration, and documented the number of repetitions, denominator units, and tested model versions in the report.
Common mistakes
- "Moving to output guardrails makes it safer." Because output guardrails run after the agent finishes, they cannot undo tool calls that have already executed.
- "If the screening model refuses, pass it through since there is no decision." Treating the absence of a decision as a pass creates a bypass. Anthropic advises treating refusals as harmful verdicts.
- "A high block rate is sufficient." What was measured, how many times, and with what denominator come first. Numbers measured on data used to write rules are meaningless.
- "False-positive blocking is merely a usability issue." When false positives are frequent, users migrate to unmonitored tools, and the controls are eventually turned off. False-positive blocking is also a security metric.
- "If the model writes a refusal sentence, the defense succeeded." Refusal sentences and tool calls can occur together. Evaluation is determined by logs and state changes.
- "Because a toxicity classifier is attached, injections are also blocked." Toxicity classification, attack detection, and authorization checks answer different questions.
- "It ran 30 times without being breached once, so it is secure." All that can be said from that result is that "the success rate is likely lower than roughly 10%."
- "Evaluating with public collections of attack prompts is sufficient." Public prompts inflate scores and do not traverse our actual pathways. Use knowledge bases to verify coverage.
Summary at a glance
| Topic | Sentence to remember |
|---|---|
| Guardrail placement | Input, tool results, tool calls, output. Output checks cannot undo executed actions |
| Execution mode | Parallel input checks are fast, but tools may run in the meantime |
| Classifiers | Toxicity, attack detection, and authorization are different questions |
| Failure behavior | Absence of a decision is not a pass. Fail-closed by risk level |
| Red team | Authorized scope, synthetic data, mock tools, stop conditions |
| Scenarios | Cards filling the pathway × defense layer grid |
| Evaluation set | Attack, normal, boundary; separation of development and validation sets; per-language; canaries |
| Evaluation | Via logs and state changes, not refusal sentences |
| Metrics | Attack pass rate, false-positive blocking rate, task completion rate, checking denominators |
| Repetitions | If 0/n, the upper bound is approximately 3/n |
Check the official docs
- OpenAI Agents SDK — Guardrails: Guardrail types, execution modes, scope of application.
- Anthropic — Mitigate jailbreaks and prompt injections: Screening, refusal handling, monitoring, self-agent red teaming.
- Anthropic — Define success criteria and build evaluations: Evaluation design principles and scoring methods.
- OpenAI — Safety best practices: Moderation API, adversarial testing, human review.
- Microsoft — Prompt Shields: Detection scope and limitations, annotate and block modes.
- NIST AI 600-1: Definition and types of AI red teaming, cautions when utilizing results.
- MITRE ATLAS: Attack tactics and techniques for checking scenario coverage.
- MITRE — ATLAS Data v2026.07 release: Three sub-techniques grouped under AML.T0115, renaming of AML.T0020.
- Model Context Protocol — Security Best Practices (2026-07-28): State handle hijacking, rule against treating handles as authentication.
- GitHub — Unvalidated npm trusted publishing configurations now expire: 48-hour expiration of unvalidated configurations, rejection of tokens for
issue_commentevents. - OpenSSF — model-signing-spec: Default hash algorithms and alternatives in the OMS specification.
Self-check
4-1. Write two types of tools to which OpenAI Agents SDK tool guardrails do not apply, and name one control that can be placed instead on an agent that uses such tools.
4-2. Write one line each for the question that harmful content classification, injection attack detection, and authorization checking answer.
4-3. Write five items to agree upon as rules of engagement before beginning a red team.
4-4. Write the purpose of embedding a synthetic secret value (canary) in an evaluation set, and two conditions to observe when choosing that value.
4-5. Out of 240 attack attempts, 9 succeeded, and out of 500 normal requests, 15 were blocked. Calculate the attack pass rate and the false block rate for normal requests, and state one thing that cannot be determined from these two numbers alone.
4-6. A scenario was repeated independently 60 times without being breached once. State the approximate upper bound of the success rate that can be claimed from this result, and what cannot be claimed.
4-7. Design task: Design an experiment to compare which is more effective between "adding input screening" and "adding write tool confirmation". Present the configurations to compare, three conditions to hold constant, and two metrics to observe.
Hands-on tasks
Exercise
Building a small evaluation set of 30 cases (60 minutes)
- Choose three paths from the list of injection paths created in Chapter 2.
- For each path, create 5 attack cases (fake documents containing hidden instructions, prompting unrequested tool calls, etc.), 4 normal cases, and 1 edge case. Use only synthetic data that causes no actual harm, and plant canary strings in the attack cases.
- For each case, record the "expected outcome (block, pass, flag)", "basis for judgment (logs, canary, scoring criteria)", and "defense layer that should catch it".
- Assign a version number to the set, and split it into 20 cases for development and 10 cases for validation.
Done when: All 30 cases have their expected outcomes and bases for judgment recorded, and there is no case where the basis for judgment relies solely on whether a refusal statement was present.
Exercise
Scenario cards and metric calculation table (50 minutes)
- Draw a path × defense layer grid, and write five scenario cards targeting columns (defense layers) with many empty cells. On each card, include attacker capabilities, path, intended outcome, success condition, targeted layer, attempt limit, and abort condition.
- If possible, run each card repeatedly 10 or more times in a test environment. If execution is difficult, write down the expected results and rationale under the current configuration.
- Separately calculate the attack pass rate and the false block rate for normal requests at both the attempt level and the scenario level, record the layer where each attack stopped, and build a table of contributions by layer.
- For cards with 0 successes, include the 3/n upper bound alongside the result.
Done when: The denominator unit is explicitly stated for each metric, and if there is a "layer that caught nothing" in the contribution by layer table, the reason for this is written in a single line.