|
| 1 | +# Copyright (c) Microsoft Corporation. |
| 2 | +# Licensed under the MIT license. |
| 3 | + |
| 4 | +""" |
| 5 | +AttackRun class for executing single attack configurations against datasets. |
| 6 | +
|
| 7 | +This module provides the AttackRun class that represents an atomic test combining |
| 8 | +an attack, a dataset, and execution parameters. Multiple AttackRuns can be grouped |
| 9 | +together into larger test scenarios for comprehensive security testing. |
| 10 | +""" |
| 11 | + |
| 12 | +import logging |
| 13 | +from typing import Any, Dict, List, Optional |
| 14 | + |
| 15 | +from pyrit.executor.attack import AttackExecutor, AttackStrategy |
| 16 | +from pyrit.models import AttackResult, PromptRequestResponse |
| 17 | + |
| 18 | +logger = logging.getLogger(__name__) |
| 19 | + |
| 20 | + |
| 21 | +class AttackRun: |
| 22 | + """ |
| 23 | + Represents a single atomic attack test combining an attack strategy and dataset. |
| 24 | +
|
| 25 | + An AttackRun is an executable unit that executes a configured attack against |
| 26 | + all objectives in a dataset. Multiple AttackRuns can be grouped together into |
| 27 | + larger test scenarios for comprehensive security testing and evaluation. |
| 28 | +
|
| 29 | + Example: |
| 30 | + >>> from pyrit.scenarios import AttackRun |
| 31 | + >>> from pyrit.attacks import PromptAttack |
| 32 | + >>> from pyrit.prompt_target import OpenAIChatTarget |
| 33 | + >>> |
| 34 | + >>> target = OpenAIChatTarget() |
| 35 | + >>> attack = PromptAttack(objective_target=target) |
| 36 | + >>> objectives = ["how to make a bomb", "how to hack a system"] |
| 37 | + >>> |
| 38 | + >>> attack_run = AttackRun( |
| 39 | + ... attack=attack, |
| 40 | + ... objectives=objectives, |
| 41 | + ... memory_labels={"test": "run1"} |
| 42 | + ... ) |
| 43 | + >>> results = await attack_run.run_async(max_concurrency=5) |
| 44 | + >>> |
| 45 | + >>> # With prepended conversation |
| 46 | + >>> from pyrit.models import PromptRequestResponse |
| 47 | + >>> conversation = [PromptRequestResponse(...)] |
| 48 | + >>> attack_run = AttackRun( |
| 49 | + ... attack=attack, |
| 50 | + ... objectives=objectives, |
| 51 | + ... prepended_conversation=conversation |
| 52 | + ... ) |
| 53 | + >>> results = await attack_run.run_async(max_concurrency=5) |
| 54 | + """ |
| 55 | + |
| 56 | + def __init__( |
| 57 | + self, |
| 58 | + *, |
| 59 | + attack: AttackStrategy, |
| 60 | + objectives: List[str], |
| 61 | + prepended_conversation: Optional[List[PromptRequestResponse]] = None, |
| 62 | + memory_labels: Optional[Dict[str, str]] = None, |
| 63 | + **attack_execute_params: Any, |
| 64 | + ) -> None: |
| 65 | + """ |
| 66 | + Initialize an attack run with an attack strategy and dataset parameters. |
| 67 | +
|
| 68 | + Args: |
| 69 | + attack (AttackStrategy): The configured attack strategy to execute. |
| 70 | + objectives (List[str]): List of attack objectives to test against. |
| 71 | + prepended_conversation (Optional[List[PromptRequestResponse]]): Optional |
| 72 | + conversation history to prepend to each attack execution. |
| 73 | + memory_labels (Optional[Dict[str, str]]): Additional labels to apply to prompts. |
| 74 | + These labels help track and categorize the attack run in memory. |
| 75 | + **attack_execute_params (Any): Additional parameters to pass to the attack |
| 76 | + execution method (e.g., custom_prompts, batch_size). |
| 77 | +
|
| 78 | + Raises: |
| 79 | + ValueError: If objectives list is empty. |
| 80 | + """ |
| 81 | + if not objectives: |
| 82 | + raise ValueError("objectives list cannot be empty") |
| 83 | + |
| 84 | + self._attack = attack |
| 85 | + self._objectives = objectives |
| 86 | + self._prepended_conversation = prepended_conversation |
| 87 | + self._memory_labels = memory_labels or {} |
| 88 | + self._attack_execute_params = attack_execute_params |
| 89 | + |
| 90 | + logger.info( |
| 91 | + f"Initialized attack run with {len(self._objectives)} objectives " |
| 92 | + f"and attack type: {type(attack).__name__}" |
| 93 | + ) |
| 94 | + |
| 95 | + async def run_async(self, *, max_concurrency: int = 1) -> List[AttackResult]: |
| 96 | + """ |
| 97 | + Execute the attack run against all objectives in the dataset. |
| 98 | +
|
| 99 | + This method uses AttackExecutor to run the configured attack against |
| 100 | + all objectives from the dataset. |
| 101 | +
|
| 102 | + Args: |
| 103 | + max_concurrency (int): Maximum number of concurrent attack executions. |
| 104 | + Defaults to 1 for sequential execution. |
| 105 | +
|
| 106 | + Returns: |
| 107 | + List[AttackResult]: List of attack results, one for each objective. |
| 108 | +
|
| 109 | + Raises: |
| 110 | + ValueError: If the attack execution fails. |
| 111 | + """ |
| 112 | + # Create the executor with the specified concurrency |
| 113 | + executor = AttackExecutor(max_concurrency=max_concurrency) |
| 114 | + |
| 115 | + # Merge memory labels from initialization and execution parameters |
| 116 | + merged_memory_labels = {**self._memory_labels} |
| 117 | + |
| 118 | + # Build the parameters for execute_multi_objective_attack_async |
| 119 | + execute_params = { |
| 120 | + "objectives": self._objectives, |
| 121 | + "prepended_conversation": self._prepended_conversation, |
| 122 | + "memory_labels": merged_memory_labels, |
| 123 | + **self._attack_execute_params, |
| 124 | + } |
| 125 | + |
| 126 | + logger.info( |
| 127 | + f"Starting attack run execution with {len(self._objectives)} objectives " |
| 128 | + f"and max_concurrency={max_concurrency}" |
| 129 | + ) |
| 130 | + |
| 131 | + try: |
| 132 | + # Execute the attack using the executor |
| 133 | + results = await executor.execute_multi_objective_attack_async( |
| 134 | + attack=self._attack, |
| 135 | + **execute_params, |
| 136 | + ) |
| 137 | + |
| 138 | + logger.info(f"Attack run execution completed successfully with {len(results)} results") |
| 139 | + return results |
| 140 | + |
| 141 | + except Exception as e: |
| 142 | + logger.error(f"Attack run execution failed: {str(e)}") |
| 143 | + raise ValueError(f"Failed to execute attack run: {str(e)}") from e |
0 commit comments