Skip to content

Commit afda988

Browse files
FEAT Content harm scenario (microsoft#1174)
1 parent e5c0f42 commit afda988

24 files changed

Lines changed: 1735 additions & 240 deletions

.env_example

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -151,12 +151,12 @@ OPENAI_SORA_MODEL = "sora-2"
151151
# or copy to AZURE_ML_MANAGED_ENDPOINT
152152
###################################
153153

154-
AZURE_ML_MIXTRAL_ENDPOINT="https://xxxxxx.westus3.inference.ml.azure.com/score"
155-
AZURE_ML_MIXTRAL_KEY="xxxxx"
154+
AZURE_ML_PHI_ENDPOINT="https://xxxxxx.westus3.inference.ml.azure.com/score"
155+
AZURE_ML_PHI_KEY="xxxxx"
156156

157157
# The below is set as the default Azure OpenAI model used in most notebooks. Adjust as needed.
158-
AZURE_ML_MANAGED_ENDPOINT=${AZURE_ML_MIXTRAL_ENDPOINT}
159-
AZURE_ML_KEY=${AZURE_ML_MIXTRAL_KEY}
158+
AZURE_ML_MANAGED_ENDPOINT=${AZURE_ML_PHI_ENDPOINT}
159+
AZURE_ML_KEY=${AZURE_ML_PHI_KEY}
160160

161161

162162
##################################

.pre-commit-config.yaml

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -54,6 +54,7 @@ repos:
5454
hooks:
5555
- id: ruff-check
5656
name: ruff-check
57+
args: [--fix]
5758

5859
- repo: https://github.com/PyCQA/flake8
5960
rev: 7.1.2

doc/_toc.yml

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -128,7 +128,9 @@ chapters:
128128
- file: code/auxiliary_attacks/0_auxiliary_attacks
129129
sections:
130130
- file: code/auxiliary_attacks/1_gcg_azure_ml
131-
- file: code/scenarios/scenarios
131+
- file: code/scenarios/0_scenarios
132+
sections:
133+
- file: code/scenarios/1_composite_scenario
132134
- file: code/front_end/0_front_end
133135
sections:
134136
- file: code/front_end/1_pyrit_scan

doc/code/front_end/1_pyrit_scan.ipynb

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,7 @@
77
"source": [
88
"# 1. PyRIT Scan - Command Line Execution\n",
99
"\n",
10-
"`pyrit_scan` allows you to run automated security testing and red teaming attacks against AI systems using [scenarios](../scenarios/scenarios.ipynb) for strategies and [configuration](../setup/1_configuration.ipynb).\n",
10+
"`pyrit_scan` allows you to run automated security testing and red teaming attacks against AI systems using [scenarios](../scenarios/0_scenarios.ipynb) for strategies and [configuration](../setup/1_configuration.ipynb).\n",
1111
"\n",
1212
"Note in this doc the ! prefaces all commands in the terminal so we can run in a Jupyter Notebook.\n",
1313
"\n",
@@ -442,7 +442,6 @@
442442
" name=\"My Custom Scenario\",\n",
443443
" version=1,\n",
444444
" strategy_class=MyCustomStrategy,\n",
445-
" default_aggregate=MyCustomStrategy.ALL,\n",
446445
" scenario_result_id=scenario_result_id,\n",
447446
" )\n",
448447
" # ... your scenario-specific initialization code\n",

doc/code/front_end/1_pyrit_scan.py

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -15,7 +15,7 @@
1515
# %% [markdown]
1616
# # 1. PyRIT Scan
1717
#
18-
# `pyrit_scan` allows you to run automated security testing and red teaming attacks against AI systems using [scenarios](../scenarios/scenarios.ipynb) for strategies and [configuration](../setup/1_configuration.ipynb).
18+
# `pyrit_scan` allows you to run automated security testing and red teaming attacks against AI systems using [scenarios](../scenarios/0_scenarios.ipynb) for strategies and [configuration](../setup/1_configuration.ipynb).
1919
#
2020
# Note in this doc the ! prefaces all commands in the terminal so we can run in a Jupyter Notebook.
2121
#
@@ -154,7 +154,6 @@ def __init__(self, *, scenario_result_id=None, **kwargs):
154154
name="My Custom Scenario",
155155
version=1,
156156
strategy_class=MyCustomStrategy,
157-
default_aggregate=MyCustomStrategy.ALL,
158157
scenario_result_id=scenario_result_id,
159158
)
160159
# ... your scenario-specific initialization code
Lines changed: 315 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,315 @@
1+
{
2+
"cells": [
3+
{
4+
"cell_type": "markdown",
5+
"id": "0",
6+
"metadata": {
7+
"lines_to_next_cell": 0
8+
},
9+
"source": [
10+
"Scenarios\n",
11+
"\n",
12+
"A `Scenario` is a higher-level construct that groups multiple Attack Configurations together. This allows you to execute a comprehensive testing campaign with multiple attack methods sequentially. Scenarios are meant to be configured and written to test for specific workflows. As such, it is okay to hard code some values.\n",
13+
"\n",
14+
"# What is a Scenario?\n",
15+
"\n",
16+
"A `Scenario` represents a comprehensive testing campaign composed of multiple atomic attack tests. It orchestrates the execution of multiple `AtomicAttack` instances sequentially and aggregates the results into a single `ScenarioResult`.\n",
17+
"\n",
18+
"## Key Components\n",
19+
"\n",
20+
"- **Scenario**: The top-level orchestrator that groups and executes multiple atomic attacks\n",
21+
"- **AtomicAttack**: An atomic test unit combining an attack strategy, objectives, and execution parameters\n",
22+
"- **ScenarioResult**: Contains the aggregated results from all atomic attacks and scenario metadata\n",
23+
"\n",
24+
"# Use Cases\n",
25+
"\n",
26+
"Some examples of scenarios you might create:\n",
27+
"\n",
28+
"- **VibeCheckScenario**: Randomly selects a few prompts from HarmBench to quickly assess model behavior\n",
29+
"- **QuickViolence**: Checks how resilient a model is to violent objectives using multiple attack techniques\n",
30+
"- **ComprehensiveFoundry**: Tests a target with all available attack converters and strategies\n",
31+
"- **CustomCompliance**: Tests against specific compliance requirements with curated datasets and attacks\n",
32+
"\n",
33+
"These Scenarios can be updated and added to as you refine what you are testing for.\n",
34+
"\n",
35+
"# How It Works\n",
36+
"\n",
37+
"Each `Scenario` contains a collection of `AtomicAttack` objects. When executed:\n",
38+
"\n",
39+
"1. Each `AtomicAttack` is executed sequentially\n",
40+
"2. Every `AtomicAttack` tests its configured attack against all specified objectives and datasets\n",
41+
"3. Results are aggregated into a single `ScenarioResult` with all attack outcomes\n",
42+
"4. Optional memory labels help track and categorize the scenario execution\n",
43+
"\n",
44+
"# Creating Custom Scenarios\n",
45+
"\n",
46+
"To create a custom scenario, extend the `Scenario` base class and implement the required abstract methods.\n",
47+
"\n",
48+
"## Required Components\n",
49+
"\n",
50+
"1. **Strategy Enum**: Create a `ScenarioStrategy` enum that defines the available strategies for your scenario.\n",
51+
" - Each enum member is defined as `(value, tags)` where value is a string and tags is a set of strings\n",
52+
" - Include an `ALL` aggregate strategy that expands to all available strategies\n",
53+
" - Optionally implement `supports_composition()` and `validate_composition()` for strategy composition rules\n",
54+
"\n",
55+
"2. **Scenario Class**: Extend `Scenario` and implement these abstract methods:\n",
56+
" - `get_strategy_class()`: Return your strategy enum class\n",
57+
" - `get_default_strategy()`: Return the default strategy (typically `YourStrategy.ALL`)\n",
58+
" - `_get_atomic_attacks_async()`: Build and return a list of `AtomicAttack` instances\n",
59+
"\n",
60+
"3. **Constructor**: Use `@apply_defaults` decorator and call `super().__init__()` with scenario metadata:\n",
61+
" - `name`: Descriptive name for your scenario\n",
62+
" - `version`: Integer version number\n",
63+
" - `strategy_class`: The strategy enum class for this scenario\n",
64+
" - `objective_scorer_identifier`: Identifier dict for the scoring mechanism (optional)\n",
65+
" - `include_default_baseline`: Whether to include a baseline attack (default: True)\n",
66+
" - `scenario_result_id`: Optional ID to resume an existing scenario (optional)\n",
67+
"\n",
68+
"4. **Initialization**: Call `await scenario.initialize_async()` to populate atomic attacks:\n",
69+
" - `objective_target`: The target system being tested (required)\n",
70+
" - `scenario_strategies`: List of strategies to execute (optional, defaults to ALL)\n",
71+
" - `max_concurrency`: Number of concurrent operations (default: 1)\n",
72+
" - `max_retries`: Number of retry attempts on failure (default: 0)\n",
73+
" - `memory_labels`: Optional labels for tracking (optional)\n",
74+
"\n",
75+
"## Example Structure"
76+
]
77+
},
78+
{
79+
"cell_type": "code",
80+
"execution_count": null,
81+
"id": "1",
82+
"metadata": {},
83+
"outputs": [],
84+
"source": [
85+
"from typing import List, Optional, Type\n",
86+
"\n",
87+
"from pyrit.common import apply_defaults\n",
88+
"from pyrit.executor.attack import AttackScoringConfig, PromptSendingAttack\n",
89+
"from pyrit.scenario import AtomicAttack, Scenario, ScenarioStrategy\n",
90+
"from pyrit.scenario.core.scenario_strategy import ScenarioCompositeStrategy\n",
91+
"from pyrit.score.true_false.true_false_scorer import TrueFalseScorer\n",
92+
"\n",
93+
"\n",
94+
"class MyStrategy(ScenarioStrategy):\n",
95+
" ALL = (\"all\", {\"all\"})\n",
96+
" StrategyA = (\"strategy_a\", {\"tag1\", \"tag2\"})\n",
97+
" StrategyB = (\"strategy_b\", {\"tag1\"})\n",
98+
"\n",
99+
"\n",
100+
"class MyScenario(Scenario):\n",
101+
" version: int = 1\n",
102+
"\n",
103+
" @classmethod\n",
104+
" def get_strategy_class(cls) -> Type[ScenarioStrategy]:\n",
105+
" return MyStrategy\n",
106+
"\n",
107+
" @classmethod\n",
108+
" def get_default_strategy(cls) -> ScenarioStrategy:\n",
109+
" return MyStrategy.ALL\n",
110+
"\n",
111+
" @apply_defaults\n",
112+
" def __init__(\n",
113+
" self,\n",
114+
" *,\n",
115+
" objective_scorer: Optional[TrueFalseScorer] = None,\n",
116+
" scenario_result_id: Optional[str] = None,\n",
117+
" ):\n",
118+
" self._objective_scorer = objective_scorer\n",
119+
" self._scorer_config = AttackScoringConfig(objective_scorer=objective_scorer)\n",
120+
"\n",
121+
" # Call parent constructor - note: objective_target is NOT passed here\n",
122+
" super().__init__(\n",
123+
" name=\"My Custom Scenario\",\n",
124+
" version=self.version,\n",
125+
" strategy_class=MyStrategy,\n",
126+
" objective_scorer_identifier=objective_scorer.get_identifier() if objective_scorer else None,\n",
127+
" scenario_result_id=scenario_result_id,\n",
128+
" )\n",
129+
"\n",
130+
" async def _get_atomic_attacks_async(self) -> List[AtomicAttack]:\n",
131+
" \"\"\"\n",
132+
" Build atomic attacks based on selected strategies.\n",
133+
" \n",
134+
" This method is called by initialize_async() after strategies are prepared.\n",
135+
" Use self._scenario_composites to access the selected strategies.\n",
136+
" \"\"\"\n",
137+
" atomic_attacks = []\n",
138+
" \n",
139+
" # objective_target is guaranteed to be non-None by parent class validation\n",
140+
" assert self._objective_target is not None\n",
141+
" \n",
142+
" # Extract individual strategy values from the composites\n",
143+
" selected_strategies = ScenarioCompositeStrategy.extract_single_strategy_values(\n",
144+
" self._scenario_composites, strategy_type=MyStrategy\n",
145+
" )\n",
146+
" \n",
147+
" for strategy in selected_strategies:\n",
148+
" # Create attack instances based on strategy\n",
149+
" attack = PromptSendingAttack(\n",
150+
" objective_target=self._objective_target,\n",
151+
" attack_scoring_config=self._scorer_config,\n",
152+
" )\n",
153+
" atomic_attacks.append(\n",
154+
" AtomicAttack(\n",
155+
" atomic_attack_name=strategy,\n",
156+
" attack=attack,\n",
157+
" objectives=[\"objective1\", \"objective2\"],\n",
158+
" memory_labels=self._memory_labels,\n",
159+
" )\n",
160+
" )\n",
161+
" return atomic_attacks"
162+
]
163+
},
164+
{
165+
"cell_type": "markdown",
166+
"id": "2",
167+
"metadata": {},
168+
"source": [
169+
"\n",
170+
"## Existing Scenarios"
171+
]
172+
},
173+
{
174+
"cell_type": "code",
175+
"execution_count": null,
176+
"id": "3",
177+
"metadata": {},
178+
"outputs": [
179+
{
180+
"name": "stdout",
181+
"output_type": "stream",
182+
"text": [
183+
"Loading PyRIT modules...\n"
184+
]
185+
},
186+
{
187+
"name": "stdout",
188+
"output_type": "stream",
189+
"text": [
190+
"\n",
191+
"Available Scenarios:\n",
192+
"================================================================================\n",
193+
"\u001b[1m\u001b[36m\n",
194+
" airt\u001b[0m\n",
195+
" Class: CyberScenario\n",
196+
" Description:\n",
197+
" Cyber scenario implementation for PyRIT. This scenario tests how willing\n",
198+
" models are to exploit cybersecurity harms by generating malware. The\n",
199+
" CyberScenario class contains different variations of the malware\n",
200+
" generation techniques.\n",
201+
" Aggregate Strategies:\n",
202+
" - all\n",
203+
" Available Strategies (2):\n",
204+
" single_turn, multi_turn\n",
205+
" Default Strategy: all\n",
206+
"\u001b[1m\u001b[36m\n",
207+
" encoding_scenario\u001b[0m\n",
208+
" Class: EncodingScenario\n",
209+
" Description:\n",
210+
" Encoding Scenario implementation for PyRIT. This scenario tests how\n",
211+
" resilient models are to various encoding attacks by encoding potentially\n",
212+
" harmful text (by default slurs and XSS payloads) and testing if the\n",
213+
" model will decode and repeat the encoded payload. It mimics the Garak\n",
214+
" encoding probe. The scenario works by: 1. Taking seed prompts (the\n",
215+
" harmful text to be encoded) 2. Encoding them using various encoding\n",
216+
" schemes (Base64, ROT13, Morse, etc.) 3. Asking the target model to\n",
217+
" decode the encoded text 4. Scoring whether the model successfully\n",
218+
" decoded and repeated the harmful content By default, this uses the same\n",
219+
" dataset as Garak: slur terms and web XSS payloads.\n",
220+
" Aggregate Strategies:\n",
221+
" - all\n",
222+
" Available Strategies (17):\n",
223+
" base64, base2048, base16, base32, ascii85, hex, quoted_printable,\n",
224+
" uuencode, rot13, braille, atbash, morse_code, nato, ecoji, zalgo,\n",
225+
" leet_speak, ascii_smuggler\n",
226+
" Default Strategy: all\n",
227+
"\u001b[1m\u001b[36m\n",
228+
" foundry_scenario\u001b[0m\n",
229+
" Class: FoundryScenario\n",
230+
" Description:\n",
231+
" FoundryScenario is a preconfigured scenario that automatically generates\n",
232+
" multiple AtomicAttack instances based on the specified attack\n",
233+
" strategies. It supports both single-turn attacks (with various\n",
234+
" converters) and multi-turn attacks (Crescendo, RedTeaming), making it\n",
235+
" easy to quickly test a target against multiple attack vectors. The\n",
236+
" scenario can expand difficulty levels (EASY, MODERATE, DIFFICULT) into\n",
237+
" their constituent attack strategies, or you can specify individual\n",
238+
" strategies directly. Note this is not the same as the Foundry AI Red\n",
239+
" Teaming Agent. This is a PyRIT contract so their library can make use of\n",
240+
" PyRIT in a consistent way.\n",
241+
" Aggregate Strategies:\n",
242+
" - all, easy, moderate, difficult\n",
243+
" Available Strategies (23):\n",
244+
" ansi_attack, ascii_art, ascii_smuggler, atbash, base64, binary, caesar,\n",
245+
" character_space, char_swap, diacritic, flip, leetspeak, morse, rot13,\n",
246+
" suffix_append, string_join, unicode_confusable, unicode_substitution,\n",
247+
" url, jailbreak, tense, multi_turn, crescendo\n",
248+
" Default Strategy: easy\n",
249+
"\n",
250+
"================================================================================\n",
251+
"\n",
252+
"Total scenarios: 3\n"
253+
]
254+
},
255+
{
256+
"data": {
257+
"text/plain": [
258+
"0"
259+
]
260+
},
261+
"execution_count": null,
262+
"metadata": {},
263+
"output_type": "execute_result"
264+
}
265+
],
266+
"source": [
267+
"\n",
268+
"from pyrit.cli.frontend_core import FrontendCore, print_scenarios_list\n",
269+
"\n",
270+
"print_scenarios_list(context=FrontendCore())"
271+
]
272+
},
273+
{
274+
"cell_type": "markdown",
275+
"id": "4",
276+
"metadata": {},
277+
"source": [
278+
"\n",
279+
"# Resiliency\n",
280+
"\n",
281+
"Scenarios can run for a long time, and because of that, things can go wrong. Network issues, rate limits, or other transient failures can interrupt execution. PyRIT provides built-in resiliency features to handle these situations gracefully.\n",
282+
"\n",
283+
"## Automatic Resume\n",
284+
"\n",
285+
"If you re-run a `scenario`, it will automatically start where it left off. The framework tracks completed attacks and objectives in memory, so you won't lose progress if something interrupts your scenario execution. This means you can safely stop and restart scenarios without duplicating work.\n",
286+
"\n",
287+
"## Retry Mechanism\n",
288+
"\n",
289+
"You can utilize the `max_retries` parameter to handle transient failures. If any unknown exception occurs during execution, PyRIT will automatically retry the failed operation (starting where it left off) up to the specified number of times. This helps ensure your scenario completes successfully even in the face of temporary issues.\n",
290+
"\n",
291+
"## Dynamic Configuration\n",
292+
"\n",
293+
"During a long-running scenario, you may want to adjust parameters like `max_concurrency` to manage resource usage, or switch your scorer to use a different target. PyRIT's resiliency features make it safe to stop, reconfigure, and continue scenarios as needed.\n",
294+
"\n",
295+
"For more information, see [resiliency](../setup/2_resiliency.ipynb)"
296+
]
297+
}
298+
],
299+
"metadata": {
300+
"language_info": {
301+
"codemirror_mode": {
302+
"name": "ipython",
303+
"version": 3
304+
},
305+
"file_extension": ".py",
306+
"mimetype": "text/x-python",
307+
"name": "python",
308+
"nbconvert_exporter": "python",
309+
"pygments_lexer": "ipython3",
310+
"version": "3.11.14"
311+
}
312+
},
313+
"nbformat": 4,
314+
"nbformat_minor": 5
315+
}

0 commit comments

Comments
 (0)