From 0d10970b9fa4ea77c1f812ae72d299212906c7c1 Mon Sep 17 00:00:00 2001 From: Roman Lutz Date: Sat, 28 Feb 2026 14:49:37 +0000 Subject: [PATCH 1/7] Add run_initializers_async, Entra auth, and config-file support - Add run_initializers_async to pyrit.setup for programmatic initialization - Switch AIRTInitializer to Entra (Azure AD) auth, removing API key requirements - Add --config-file flag to pyrit_backend CLI - Use PyRIT configuration loader in FrontendCore and pyrit_backend - Update AIRTTargetInitializer with new target types Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- pyrit/cli/frontend_core.py | 80 +++++++++---------- pyrit/cli/pyrit_backend.py | 80 ++++++++----------- pyrit/setup/__init__.py | 10 ++- pyrit/setup/initialization.py | 25 +++++- pyrit/setup/initializers/airt.py | 48 ++++++----- pyrit/setup/initializers/airt_targets.py | 28 +++++-- tests/unit/cli/test_frontend_core.py | 58 +++++++------- tests/unit/cli/test_pyrit_backend.py | 59 ++++++++++++++ tests/unit/setup/test_airt_initializer.py | 13 +-- .../setup/test_airt_targets_initializer.py | 17 ++++ 10 files changed, 258 insertions(+), 160 deletions(-) create mode 100644 tests/unit/cli/test_pyrit_backend.py diff --git a/pyrit/cli/frontend_core.py b/pyrit/cli/frontend_core.py index 5c49525ec5..211b74ce05 100644 --- a/pyrit/cli/frontend_core.py +++ b/pyrit/cli/frontend_core.py @@ -15,13 +15,18 @@ from __future__ import annotations +import argparse +import inspect import json import logging import sys from pathlib import Path from typing import TYPE_CHECKING, Any, Optional -from pyrit.setup import ConfigurationLoader +from pyrit.registry import InitializerRegistry, ScenarioRegistry +from pyrit.scenario import DatasetConfiguration +from pyrit.scenario.printer.console_printer import ConsoleScenarioResultPrinter +from pyrit.setup import ConfigurationLoader, initialize_pyrit_async, run_initializers_async from pyrit.setup.configuration_loader import _MEMORY_DB_TYPE_MAP try: @@ -47,9 +52,7 @@ def cprint(text: str, color: str = None, attrs: list = None) -> None: # type: i from pyrit.models.scenario_result import ScenarioResult from pyrit.registry import ( InitializerMetadata, - InitializerRegistry, ScenarioMetadata, - ScenarioRegistry, ) logger = logging.getLogger(__name__) @@ -141,14 +144,17 @@ def __init__( logging.basicConfig(level=self._log_level) async def initialize_async(self) -> None: - """Initialize PyRIT and load registries (heavy operation).""" + """ + Initialize PyRIT and load registries (heavy operation). + + Sets up memory and loads scenario/initializer registries. + Initializers are NOT run here — they are run separately + (per-scenario in pyrit_scan, or up-front in pyrit_backend). + """ if self._initialized: return - from pyrit.registry import InitializerRegistry, ScenarioRegistry - from pyrit.setup import initialize_pyrit_async - - # Initialize PyRIT without initializers (they run per-scenario) + # Initialize PyRIT without initializers (they run separately) await initialize_pyrit_async( memory_db_type=self._database, initialization_scripts=None, @@ -167,6 +173,27 @@ async def initialize_async(self) -> None: self._initialized = True + async def run_initializers_async(self) -> None: + """ + Resolve and run all configured initializers and initialization scripts. + + Must be called after :meth:`initialize_async` so that registries are + available to resolve initializer names. This is the same pattern used + by :func:`run_scenario_async` before executing a scenario. + + If no initializers are configured this is a no-op. + """ + initializer_instances = None + if self._initializer_names: + print(f"Running {len(self._initializer_names)} initializer(s)...") + sys.stdout.flush() + initializer_instances = [self.initializer_registry.get_class(name)() for name in self._initializer_names] + + await run_initializers_async( + initializers=initializer_instances, + initialization_scripts=self._initialization_scripts, + ) + @property def scenario_registry(self) -> ScenarioRegistry: """ @@ -227,8 +254,6 @@ async def list_initializers_async( Sequence of initializer metadata dictionaries describing each initializer class. """ if discovery_path: - from pyrit.registry import InitializerRegistry - registry = InitializerRegistry(discovery_path=discovery_path) return registry.list_metadata() @@ -276,34 +301,13 @@ async def run_scenario_async( Note: Initializers from PyRITContext will be run before the scenario executes. """ - from pyrit.scenario.printer.console_printer import ConsoleScenarioResultPrinter - from pyrit.setup import initialize_pyrit_async - # Ensure context is initialized first (loads registries) # This must happen BEFORE we run initializers to avoid double-initialization if not context._initialized: await context.initialize_async() - # Run initializers before scenario - initializer_instances = None - if context._initializer_names: - print(f"Running {len(context._initializer_names)} initializer(s)...") - sys.stdout.flush() - - initializer_instances = [] - - for name in context._initializer_names: - initializer_class = context.initializer_registry.get_class(name) - initializer_instances.append(initializer_class()) - - # Re-initialize PyRIT with the scenario-specific initializers - # This resets memory and applies initializer defaults - await initialize_pyrit_async( - memory_db_type=context._database, - initialization_scripts=context._initialization_scripts, - initializers=initializer_instances, - env_files=context._env_files, - ) + # Resolve and run initializers + initialization scripts + await context.run_initializers_async() # Get scenario class scenario_class = context.scenario_registry.get_class(scenario_name) @@ -343,8 +347,6 @@ async def run_scenario_async( # - max_dataset_size only: default datasets with overridden limit if dataset_names: # User specified dataset names - create new config (fetches all unless max_dataset_size set) - from pyrit.scenario import DatasetConfiguration - init_kwargs["dataset_config"] = DatasetConfiguration( dataset_names=dataset_names, max_dataset_size=max_dataset_size, @@ -599,8 +601,6 @@ def _argparse_validator(validator_func: Callable[..., Any]) -> Callable[[Any], A Raises: ValueError: If validator_func has no parameters. """ - import inspect - # Get the first parameter name from the function signature sig = inspect.signature(validator_func) params = list(sig.parameters.keys()) @@ -609,13 +609,11 @@ def _argparse_validator(validator_func: Callable[..., Any]) -> Callable[[Any], A first_param = params[0] def wrapper(value: Any) -> Any: - import argparse as ap - try: # Call with keyword argument to support keyword-only parameters return validator_func(**{first_param: value}) except ValueError as e: - raise ap.ArgumentTypeError(str(e)) from e + raise argparse.ArgumentTypeError(str(e)) from e # Preserve function metadata for better debugging wrapper.__name__ = getattr(validator_func, "__name__", "argparse_validator") @@ -636,8 +634,6 @@ def resolve_initialization_scripts(script_paths: list[str]) -> list[Path]: Raises: FileNotFoundError: If a script path does not exist. """ - from pyrit.registry import InitializerRegistry - return InitializerRegistry.resolve_script_paths(script_paths=script_paths) diff --git a/pyrit/cli/pyrit_backend.py b/pyrit/cli/pyrit_backend.py index a3e3fe647f..20a01dce3d 100644 --- a/pyrit/cli/pyrit_backend.py +++ b/pyrit/cli/pyrit_backend.py @@ -10,6 +10,7 @@ import asyncio import sys from argparse import ArgumentParser, Namespace, RawDescriptionHelpFormatter +from pathlib import Path from typing import Optional # Ensure emoji and other Unicode characters don't crash on Windows consoles @@ -17,6 +18,8 @@ sys.stdout.reconfigure(errors="replace") # type: ignore[union-attr] sys.stderr.reconfigure(errors="replace") # type: ignore[union-attr] +import uvicorn + from pyrit.cli import frontend_core @@ -41,6 +44,9 @@ def parse_args(*, args: Optional[list[str]] = None) -> Namespace: # Start with custom initialization scripts pyrit_backend --initialization-scripts ./my_targets.py + # Start with explicit config file + pyrit_backend --config-file ./my_backend_conf.yaml + # Start with custom port and host pyrit_backend --host 0.0.0.0 --port 8080 @@ -80,13 +86,19 @@ def parse_args(*, args: Optional[list[str]] = None) -> Namespace: parser.add_argument( "--database", type=frontend_core.validate_database_argparse, - default=frontend_core.SQLITE, + default=None, help=( f"Database type to use for memory storage ({frontend_core.IN_MEMORY}, " - f"{frontend_core.SQLITE}, {frontend_core.AZURE_SQL}) (default: {frontend_core.SQLITE})" + f"{frontend_core.SQLITE}, {frontend_core.AZURE_SQL}) (default: from config file, or {frontend_core.SQLITE})" ), ) + parser.add_argument( + "--config-file", + type=str, + help=frontend_core.ARG_HELP["config_file"], + ) + parser.add_argument( "--initializers", type=str, @@ -124,55 +136,27 @@ async def initialize_and_run(*, parsed_args: Namespace) -> int: Returns: int: Exit code (0 for success, 1 for error). """ - from pyrit.setup import initialize_pyrit_async - - # Resolve initialization scripts if provided - initialization_scripts = None - if parsed_args.initialization_scripts: - try: - initialization_scripts = frontend_core.resolve_initialization_scripts( - script_paths=parsed_args.initialization_scripts - ) - except FileNotFoundError as e: - print(f"Error: {e}") - return 1 - - # Resolve env files if provided - env_files = None - if parsed_args.env_files: - try: - env_files = frontend_core.resolve_env_files(env_file_paths=parsed_args.env_files) - except ValueError as e: - print(f"Error: {e}") - return 1 - - # Resolve initializer instances if names provided - initializer_instances = None - if parsed_args.initializers: - from pyrit.registry import InitializerRegistry - - registry = InitializerRegistry() - initializer_instances = [] - for name in parsed_args.initializers: - try: - initializer_class = registry.get_class(name) - initializer_instances.append(initializer_class()) - except Exception as e: - print(f"Error: Could not load initializer '{name}': {e}") - return 1 - - # Initialize PyRIT with the provided configuration + try: + core = frontend_core.FrontendCore( + config_file=Path(parsed_args.config_file) if parsed_args.config_file else None, + database=parsed_args.database, + initialization_scripts=( + [Path(p) for p in parsed_args.initialization_scripts] if parsed_args.initialization_scripts else None + ), + initializer_names=parsed_args.initializers, + env_files=([Path(p) for p in parsed_args.env_files] if parsed_args.env_files else None), + log_level=parsed_args.log_level, + ) + except (ValueError, FileNotFoundError) as e: + print(f"Error: {e}") + return 1 + + # Initialize memory, registries, and run initializers. print("🔧 Initializing PyRIT...") - await initialize_pyrit_async( - memory_db_type=parsed_args.database, - initialization_scripts=initialization_scripts, - initializers=initializer_instances, - env_files=env_files, - ) + await core.initialize_async() + await core.run_initializers_async() # Start uvicorn server - import uvicorn - print(f"🚀 Starting PyRIT backend on http://{parsed_args.host}:{parsed_args.port}") print(f" API Docs: http://{parsed_args.host}:{parsed_args.port}/docs") diff --git a/pyrit/setup/__init__.py b/pyrit/setup/__init__.py index 2929a59ea3..2b0823e0f3 100644 --- a/pyrit/setup/__init__.py +++ b/pyrit/setup/__init__.py @@ -4,7 +4,14 @@ """Module containing initialization PyRIT.""" from pyrit.setup.configuration_loader import ConfigurationLoader, initialize_from_config_async -from pyrit.setup.initialization import AZURE_SQL, IN_MEMORY, SQLITE, MemoryDatabaseType, initialize_pyrit_async +from pyrit.setup.initialization import ( + AZURE_SQL, + IN_MEMORY, + SQLITE, + MemoryDatabaseType, + initialize_pyrit_async, + run_initializers_async, +) __all__ = [ "AZURE_SQL", @@ -12,6 +19,7 @@ "IN_MEMORY", "initialize_pyrit_async", "initialize_from_config_async", + "run_initializers_async", "MemoryDatabaseType", "ConfigurationLoader", ] diff --git a/pyrit/setup/initialization.py b/pyrit/setup/initialization.py index 0aff8deafc..64127e9f8f 100644 --- a/pyrit/setup/initialization.py +++ b/pyrit/setup/initialization.py @@ -284,14 +284,33 @@ async def initialize_pyrit_async( ) CentralMemory.set_memory_instance(memory) - # Combine directly provided initializers with those loaded from scripts + await run_initializers_async(initializers=initializers, initialization_scripts=initialization_scripts) + + +async def run_initializers_async( + *, + initializers: Optional[Sequence["PyRITInitializer"]] = None, + initialization_scripts: Optional[Sequence[Union[str, pathlib.Path]]] = None, +) -> None: + """ + Run initializers and initialization scripts without re-initializing memory or environment. + + This is useful when memory and environment are already set up (e.g. via + :func:`initialize_pyrit_async`) and only the initializer step needs to run. + + Args: + initializers: Optional sequence of PyRITInitializer instances to execute directly. + initialization_scripts: Optional sequence of Python script paths containing + PyRITInitializer classes. + + Raises: + ValueError: If initializers are invalid or scripts cannot be loaded. + """ all_initializers = list(initializers) if initializers else [] - # Load additional initializers from scripts if initialization_scripts: script_initializers = _load_initializers_from_scripts(script_paths=initialization_scripts) all_initializers.extend(script_initializers) - # Execute all initializers (sorted by execution_order) if all_initializers: await _execute_initializers_async(initializers=all_initializers) diff --git a/pyrit/setup/initializers/airt.py b/pyrit/setup/initializers/airt.py index a0d81613df..cd990a87de 100644 --- a/pyrit/setup/initializers/airt.py +++ b/pyrit/setup/initializers/airt.py @@ -9,7 +9,9 @@ """ import os +from typing import Callable +from pyrit.auth import get_azure_openai_auth, get_azure_token_provider from pyrit.common.apply_defaults import set_default_value, set_global_variable from pyrit.executor.attack import ( AttackAdversarialConfig, @@ -44,11 +46,12 @@ class AIRTInitializer(PyRITInitializer): Required Environment Variables: - AZURE_OPENAI_GPT4O_UNSAFE_CHAT_ENDPOINT: Azure OpenAI endpoint for converters and targets - - AZURE_OPENAI_GPT4O_UNSAFE_CHAT_KEY: Azure OpenAI API key for converters and targets - AZURE_OPENAI_GPT4O_UNSAFE_CHAT_MODEL: Azure OpenAI model name for converters and targets - AZURE_OPENAI_GPT4O_UNSAFE_CHAT_ENDPOINT2: Azure OpenAI endpoint for scoring - - AZURE_OPENAI_GPT4O_UNSAFE_CHAT_KEY2: Azure OpenAI API key for scoring - AZURE_OPENAI_GPT4O_UNSAFE_CHAT_MODEL2: Azure OpenAI model name for scoring + - AZURE_CONTENT_SAFETY_API_ENDPOINT: Azure Content Safety endpoint + + Authentication is handled via Entra ID (Azure AD) using DefaultAzureCredential. This configuration is designed for full AI Red Team operations with: - Separate endpoints for attack execution vs scoring (security isolation) @@ -81,13 +84,10 @@ def required_env_vars(self) -> list[str]: """Get list of required environment variables.""" return [ "AZURE_OPENAI_GPT4O_UNSAFE_CHAT_ENDPOINT", - "AZURE_OPENAI_GPT4O_UNSAFE_CHAT_KEY", "AZURE_OPENAI_GPT4O_UNSAFE_CHAT_MODEL", "AZURE_OPENAI_GPT4O_UNSAFE_CHAT_ENDPOINT2", - "AZURE_OPENAI_GPT4O_UNSAFE_CHAT_KEY2", "AZURE_OPENAI_GPT4O_UNSAFE_CHAT_MODEL2", "AZURE_CONTENT_SAFETY_API_ENDPOINT", - "AZURE_CONTENT_SAFETY_API_KEY", ] async def initialize_async(self) -> None: @@ -102,37 +102,43 @@ async def initialize_async(self) -> None: """ # Get environment variables (validated by validate() method) converter_endpoint = os.getenv("AZURE_OPENAI_GPT4O_UNSAFE_CHAT_ENDPOINT") - converter_api_key = os.getenv("AZURE_OPENAI_GPT4O_UNSAFE_CHAT_KEY") converter_model_name = os.getenv("AZURE_OPENAI_GPT4O_UNSAFE_CHAT_MODEL") scorer_endpoint = os.getenv("AZURE_OPENAI_GPT4O_UNSAFE_CHAT_ENDPOINT2") - scorer_api_key = os.getenv("AZURE_OPENAI_GPT4O_UNSAFE_CHAT_KEY2") scorer_model_name = os.getenv("AZURE_OPENAI_GPT4O_UNSAFE_CHAT_MODEL2") # Type assertions - safe because validate() already checked these assert converter_endpoint is not None - assert converter_api_key is not None assert scorer_endpoint is not None - assert scorer_api_key is not None # model name can be empty in certain cases (e.g., custom model deployments that don't need model name) + # Use Entra authentication via Azure token providers + converter_auth = get_azure_openai_auth(converter_endpoint) + scorer_auth = get_azure_openai_auth(scorer_endpoint) + content_safety_auth = get_azure_token_provider("https://cognitiveservices.azure.com/.default") + # 1. Setup converter target self._setup_converter_target( - endpoint=converter_endpoint, api_key=converter_api_key, model_name=converter_model_name + endpoint=converter_endpoint, credential=converter_auth, model_name=converter_model_name ) # 2. Setup scorers - self._setup_scorers(endpoint=scorer_endpoint, api_key=scorer_api_key, model_name=scorer_model_name) + self._setup_scorers( + endpoint=scorer_endpoint, + credential=scorer_auth, + model_name=scorer_model_name, + content_safety_credential=content_safety_auth, + ) # 3. Setup adversarial targets self._setup_adversarial_targets( - endpoint=converter_endpoint, api_key=converter_api_key, model_name=converter_model_name + endpoint=converter_endpoint, credential=converter_auth, model_name=converter_model_name ) - def _setup_converter_target(self, *, endpoint: str, api_key: str, model_name: str) -> None: + def _setup_converter_target(self, *, endpoint: str, credential: Callable, model_name: str) -> None: """Set up the default converter target configuration.""" default_converter_target = OpenAIChatTarget( endpoint=endpoint, - api_key=api_key, + api_key=credential, model_name=model_name, temperature=1.1, ) @@ -144,11 +150,13 @@ def _setup_converter_target(self, *, endpoint: str, api_key: str, model_name: st value=default_converter_target, ) - def _setup_scorers(self, *, endpoint: str, api_key: str, model_name: str) -> None: + def _setup_scorers( + self, *, endpoint: str, credential: Callable, model_name: str, content_safety_credential: Callable + ) -> None: """Set up the composite harm and objective scorers.""" scorer_target = OpenAIChatTarget( endpoint=endpoint, - api_key=api_key, + api_key=credential, model_name=model_name, temperature=0.3, ) @@ -161,7 +169,9 @@ def _setup_scorers(self, *, endpoint: str, api_key: str, model_name: str) -> Non default_harm_scorer = TrueFalseCompositeScorer( aggregator=TrueFalseScoreAggregator.AND, scorers=[ - FloatScaleThresholdScorer(scorer=AzureContentFilterScorer(), threshold=0.5), + FloatScaleThresholdScorer( + scorer=AzureContentFilterScorer(api_key=content_safety_credential), threshold=0.5 + ), TrueFalseInverterScorer( scorer=SelfAskRefusalScorer(chat_target=scorer_target), ), @@ -205,12 +215,12 @@ def _setup_scorers(self, *, endpoint: str, api_key: str, model_name: str) -> Non value=default_objective_scorer_config, ) - def _setup_adversarial_targets(self, *, endpoint: str, api_key: str, model_name: str) -> None: + def _setup_adversarial_targets(self, *, endpoint: str, credential: Callable, model_name: str) -> None: """Set up the adversarial target configurations for attacks.""" adversarial_config = AttackAdversarialConfig( target=OpenAIChatTarget( endpoint=endpoint, - api_key=api_key, + api_key=credential, model_name=model_name, temperature=1.2, ) diff --git a/pyrit/setup/initializers/airt_targets.py b/pyrit/setup/initializers/airt_targets.py index be42a8c173..0f6f2f7c6f 100644 --- a/pyrit/setup/initializers/airt_targets.py +++ b/pyrit/setup/initializers/airt_targets.py @@ -14,8 +14,8 @@ import logging import os -from dataclasses import dataclass -from typing import Any, Optional +from dataclasses import dataclass, field +from typing import Any, Dict, List, Optional, Type from pyrit.prompt_target import ( AzureMLChatTarget, @@ -45,6 +45,7 @@ class TargetConfig: key_var: str = "" # Empty string means no auth required model_var: Optional[str] = None underlying_model_var: Optional[str] = None + extra_kwargs: Dict[str, Any] = field(default_factory=dict) # Define all supported target configurations. @@ -168,6 +169,15 @@ class TargetConfig: model_var="AZURE_OPENAI_GPT5_MODEL", underlying_model_var="AZURE_OPENAI_GPT5_UNDERLYING_MODEL", ), + TargetConfig( + registry_name="azure_openai_gpt5_responses_high_reasoning", + target_class=OpenAIResponseTarget, + endpoint_var="AZURE_OPENAI_GPT5_RESPONSES_ENDPOINT", + key_var="AZURE_OPENAI_GPT5_KEY", + model_var="AZURE_OPENAI_GPT5_MODEL", + underlying_model_var="AZURE_OPENAI_GPT5_UNDERLYING_MODEL", + extra_kwargs={"extra_body_parameters": {"reasoning": {"effort": "high"}}}, + ), TargetConfig( registry_name="platform_openai_responses", target_class=OpenAIResponseTarget, @@ -243,12 +253,11 @@ class TargetConfig: # Video Targets (OpenAIVideoTarget) # ============================================ TargetConfig( - registry_name="azure_openai_video", + registry_name="openai_video", target_class=OpenAIVideoTarget, - endpoint_var="AZURE_OPENAI_VIDEO_ENDPOINT", - key_var="AZURE_OPENAI_VIDEO_KEY", - model_var="AZURE_OPENAI_VIDEO_MODEL", - underlying_model_var="AZURE_OPENAI_VIDEO_UNDERLYING_MODEL", + endpoint_var="OPENAI_VIDEO_ENDPOINT", + key_var="OPENAI_VIDEO_KEY", + model_var="OPENAI_VIDEO_MODEL", ), # ============================================ # Completion Targets (OpenAICompletionTarget) @@ -310,6 +319,7 @@ class AIRTTargetInitializer(PyRITInitializer): **OpenAI Responses Targets (OpenAIResponseTarget):** - AZURE_OPENAI_GPT5_RESPONSES_* - Azure OpenAI GPT-5 Responses + - AZURE_OPENAI_GPT5_RESPONSES_* (high reasoning) - Azure OpenAI GPT-5 Responses with high reasoning effort - PLATFORM_OPENAI_RESPONSES_* - Platform OpenAI Responses - AZURE_OPENAI_RESPONSES_* - Azure OpenAI Responses @@ -416,6 +426,10 @@ def _register_target(self, config: TargetConfig) -> None: if underlying_model is not None: kwargs["underlying_model"] = underlying_model + # Add any extra constructor kwargs (e.g. extra_body_parameters for reasoning) + if config.extra_kwargs: + kwargs.update(config.extra_kwargs) + target = config.target_class(**kwargs) registry = TargetRegistry.get_registry_singleton() registry.register_instance(target, name=config.registry_name) diff --git a/tests/unit/cli/test_frontend_core.py b/tests/unit/cli/test_frontend_core.py index 3bf264a505..f26d87a3e3 100644 --- a/tests/unit/cli/test_frontend_core.py +++ b/tests/unit/cli/test_frontend_core.py @@ -24,7 +24,7 @@ def test_init_with_defaults(self): assert context._database == frontend_core.SQLITE assert context._initialization_scripts is None - assert context._initializer_names is None + assert context._initializer_names == ["airt", "airt_targets"] assert context._log_level == logging.WARNING assert context._initialized is False @@ -53,9 +53,9 @@ def test_init_with_invalid_database(self): with pytest.raises(ValueError, match="Invalid database type"): frontend_core.FrontendCore(database="InvalidDB") - @patch("pyrit.registry.ScenarioRegistry") - @patch("pyrit.registry.InitializerRegistry") - @patch("pyrit.setup.initialize_pyrit_async", new_callable=AsyncMock) + @patch("pyrit.cli.frontend_core.ScenarioRegistry") + @patch("pyrit.cli.frontend_core.InitializerRegistry") + @patch("pyrit.cli.frontend_core.initialize_pyrit_async", new_callable=AsyncMock) def test_initialize_loads_registries( self, mock_init_pyrit: AsyncMock, @@ -73,9 +73,9 @@ def test_initialize_loads_registries( mock_scenario_registry.get_registry_singleton.assert_called_once() mock_init_registry.assert_called_once() - @patch("pyrit.registry.ScenarioRegistry") - @patch("pyrit.registry.InitializerRegistry") - @patch("pyrit.setup.initialize_pyrit_async", new_callable=AsyncMock) + @patch("pyrit.cli.frontend_core.ScenarioRegistry") + @patch("pyrit.cli.frontend_core.InitializerRegistry") + @patch("pyrit.cli.frontend_core.initialize_pyrit_async", new_callable=AsyncMock) async def test_scenario_registry_property_initializes( self, mock_init_pyrit: AsyncMock, @@ -92,9 +92,9 @@ async def test_scenario_registry_property_initializes( assert context._initialized is True assert registry is not None - @patch("pyrit.registry.ScenarioRegistry") - @patch("pyrit.registry.InitializerRegistry") - @patch("pyrit.setup.initialize_pyrit_async", new_callable=AsyncMock) + @patch("pyrit.cli.frontend_core.ScenarioRegistry") + @patch("pyrit.cli.frontend_core.InitializerRegistry") + @patch("pyrit.cli.frontend_core.initialize_pyrit_async", new_callable=AsyncMock) async def test_initializer_registry_property_initializes( self, mock_init_pyrit: AsyncMock, @@ -249,7 +249,7 @@ def test_parse_memory_labels_non_string_key(self): class TestResolveInitializationScripts: """Tests for resolve_initialization_scripts function.""" - @patch("pyrit.registry.InitializerRegistry.resolve_script_paths") + @patch("pyrit.cli.frontend_core.InitializerRegistry.resolve_script_paths") def test_resolve_initialization_scripts(self, mock_resolve: MagicMock): """Test resolve_initialization_scripts calls InitializerRegistry.""" mock_resolve.return_value = [Path("/test/script.py")] @@ -302,7 +302,7 @@ async def test_list_initializers_without_discovery_path(self): assert result == [{"name": "test_init"}] mock_registry.list_metadata.assert_called_once() - @patch("pyrit.registry.InitializerRegistry") + @patch("pyrit.cli.frontend_core.InitializerRegistry") async def test_list_initializers_with_discovery_path(self, mock_init_registry_class: MagicMock): """Test list_initializers_async with discovery path.""" mock_registry = MagicMock() @@ -620,12 +620,12 @@ def test_parse_run_arguments_missing_value(self): class TestRunScenarioAsync: """Tests for run_scenario_async function.""" - @patch("pyrit.setup.initialize_pyrit_async", new_callable=AsyncMock) - @patch("pyrit.scenario.printer.console_printer.ConsoleScenarioResultPrinter") + @patch("pyrit.cli.frontend_core.run_initializers_async", new_callable=AsyncMock) + @patch("pyrit.cli.frontend_core.ConsoleScenarioResultPrinter") async def test_run_scenario_async_basic( self, mock_printer_class: MagicMock, - mock_init_pyrit: AsyncMock, + mock_run_init: AsyncMock, ): """Test running a basic scenario.""" # Mock context @@ -660,8 +660,8 @@ async def test_run_scenario_async_basic( mock_scenario_instance.run_async.assert_called_once() mock_printer.print_summary_async.assert_called_once_with(mock_result) - @patch("pyrit.setup.initialize_pyrit_async", new_callable=AsyncMock) - async def test_run_scenario_async_not_found(self, mock_init_pyrit: AsyncMock): + @patch("pyrit.cli.frontend_core.run_initializers_async", new_callable=AsyncMock) + async def test_run_scenario_async_not_found(self, mock_run_init: AsyncMock): """Test running non-existent scenario raises ValueError.""" context = frontend_core.FrontendCore() mock_scenario_registry = MagicMock() @@ -678,12 +678,12 @@ async def test_run_scenario_async_not_found(self, mock_init_pyrit: AsyncMock): context=context, ) - @patch("pyrit.setup.initialize_pyrit_async", new_callable=AsyncMock) - @patch("pyrit.scenario.printer.console_printer.ConsoleScenarioResultPrinter") + @patch("pyrit.cli.frontend_core.run_initializers_async", new_callable=AsyncMock) + @patch("pyrit.cli.frontend_core.ConsoleScenarioResultPrinter") async def test_run_scenario_async_with_strategies( self, mock_printer_class: MagicMock, - mock_init_pyrit: AsyncMock, + mock_run_init: AsyncMock, ): """Test running scenario with strategies.""" context = frontend_core.FrontendCore() @@ -724,12 +724,12 @@ class MockStrategy(Enum): call_kwargs = mock_scenario_instance.initialize_async.call_args[1] assert "scenario_strategies" in call_kwargs - @patch("pyrit.setup.initialize_pyrit_async", new_callable=AsyncMock) - @patch("pyrit.scenario.printer.console_printer.ConsoleScenarioResultPrinter") + @patch("pyrit.cli.frontend_core.run_initializers_async", new_callable=AsyncMock) + @patch("pyrit.cli.frontend_core.ConsoleScenarioResultPrinter") async def test_run_scenario_async_with_initializers( self, mock_printer_class: MagicMock, - mock_init_pyrit: AsyncMock, + mock_run_init: AsyncMock, ): """Test running scenario with initializers.""" context = frontend_core.FrontendCore(initializer_names=["test_init"]) @@ -763,12 +763,12 @@ async def test_run_scenario_async_with_initializers( # Verify initializer was retrieved mock_initializer_registry.get_class.assert_called_once_with("test_init") - @patch("pyrit.setup.initialize_pyrit_async", new_callable=AsyncMock) - @patch("pyrit.scenario.printer.console_printer.ConsoleScenarioResultPrinter") + @patch("pyrit.cli.frontend_core.run_initializers_async", new_callable=AsyncMock) + @patch("pyrit.cli.frontend_core.ConsoleScenarioResultPrinter") async def test_run_scenario_async_with_max_concurrency( self, mock_printer_class: MagicMock, - mock_init_pyrit: AsyncMock, + mock_run_init: AsyncMock, ): """Test running scenario with max_concurrency.""" context = frontend_core.FrontendCore() @@ -802,12 +802,12 @@ async def test_run_scenario_async_with_max_concurrency( call_kwargs = mock_scenario_instance.initialize_async.call_args[1] assert call_kwargs["max_concurrency"] == 5 - @patch("pyrit.setup.initialize_pyrit_async", new_callable=AsyncMock) - @patch("pyrit.scenario.printer.console_printer.ConsoleScenarioResultPrinter") + @patch("pyrit.cli.frontend_core.run_initializers_async", new_callable=AsyncMock) + @patch("pyrit.cli.frontend_core.ConsoleScenarioResultPrinter") async def test_run_scenario_async_without_print_summary( self, mock_printer_class: MagicMock, - mock_init_pyrit: AsyncMock, + mock_run_init: AsyncMock, ): """Test running scenario without printing summary.""" context = frontend_core.FrontendCore() diff --git a/tests/unit/cli/test_pyrit_backend.py b/tests/unit/cli/test_pyrit_backend.py new file mode 100644 index 0000000000..e1e54f0c06 --- /dev/null +++ b/tests/unit/cli/test_pyrit_backend.py @@ -0,0 +1,59 @@ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT license. + +from pathlib import Path +from unittest.mock import AsyncMock, MagicMock, patch + +import pytest + +from pyrit.cli import pyrit_backend + + +class TestParseArgs: + """Tests for pyrit_backend.parse_args.""" + + def test_parse_args_defaults(self) -> None: + """Should parse backend defaults correctly.""" + args = pyrit_backend.parse_args(args=[]) + + assert args.host == "0.0.0.0" + assert args.port == 8000 + assert args.config_file is None + + def test_parse_args_accepts_config_file(self) -> None: + """Should parse --config-file argument.""" + args = pyrit_backend.parse_args(args=["--config-file", "./custom_conf.yaml"]) + + assert args.config_file == "./custom_conf.yaml" + + +class TestInitializeAndRun: + """Tests for pyrit_backend.initialize_and_run.""" + + @pytest.mark.asyncio + async def test_initialize_and_run_passes_config_file_to_frontend_core(self) -> None: + """Should forward parsed config file path to FrontendCore.""" + parsed_args = pyrit_backend.parse_args(args=["--config-file", "./custom_conf.yaml"]) + + with ( + patch("pyrit.cli.pyrit_backend.frontend_core.FrontendCore") as mock_core_class, + patch("pyrit.cli.pyrit_backend.uvicorn.Config") as mock_uvicorn_config, + patch("pyrit.cli.pyrit_backend.uvicorn.Server") as mock_uvicorn_server, + ): + mock_core = MagicMock() + mock_core.initialize_async = AsyncMock() + mock_core.run_initializers_async = AsyncMock() + mock_core_class.return_value = mock_core + + mock_server = MagicMock() + mock_server.serve = AsyncMock() + mock_uvicorn_server.return_value = mock_server + + result = await pyrit_backend.initialize_and_run(parsed_args=parsed_args) + + assert result == 0 + mock_core_class.assert_called_once() + assert mock_core_class.call_args.kwargs["config_file"] == Path("./custom_conf.yaml") + mock_uvicorn_config.assert_called_once() + mock_uvicorn_server.assert_called_once() + mock_server.serve.assert_awaited_once() diff --git a/tests/unit/setup/test_airt_initializer.py b/tests/unit/setup/test_airt_initializer.py index 434833681c..ebd121fa78 100644 --- a/tests/unit/setup/test_airt_initializer.py +++ b/tests/unit/setup/test_airt_initializer.py @@ -36,13 +36,10 @@ def setup_method(self) -> None: reset_default_values() # Set up required env vars for AIRT os.environ["AZURE_OPENAI_GPT4O_UNSAFE_CHAT_ENDPOINT"] = "https://test-converter.openai.azure.com" - os.environ["AZURE_OPENAI_GPT4O_UNSAFE_CHAT_KEY"] = "test_converter_key" os.environ["AZURE_OPENAI_GPT4O_UNSAFE_CHAT_MODEL"] = "gpt-4" os.environ["AZURE_OPENAI_GPT4O_UNSAFE_CHAT_ENDPOINT2"] = "https://test-scorer.openai.azure.com" - os.environ["AZURE_OPENAI_GPT4O_UNSAFE_CHAT_KEY2"] = "test_scorer_key" os.environ["AZURE_OPENAI_GPT4O_UNSAFE_CHAT_MODEL2"] = "gpt-4" os.environ["AZURE_CONTENT_SAFETY_API_ENDPOINT"] = "https://test-safety.cognitiveservices.azure.com" - os.environ["AZURE_CONTENT_SAFETY_API_KEY"] = "test_safety_key" # Clean up globals for attr in [ "default_converter_target", @@ -59,13 +56,10 @@ def teardown_method(self) -> None: # Clean up env vars for var in [ "AZURE_OPENAI_GPT4O_UNSAFE_CHAT_ENDPOINT", - "AZURE_OPENAI_GPT4O_UNSAFE_CHAT_KEY", "AZURE_OPENAI_GPT4O_UNSAFE_CHAT_MODEL", "AZURE_OPENAI_GPT4O_UNSAFE_CHAT_ENDPOINT2", - "AZURE_OPENAI_GPT4O_UNSAFE_CHAT_KEY2", "AZURE_OPENAI_GPT4O_UNSAFE_CHAT_MODEL2", "AZURE_CONTENT_SAFETY_API_ENDPOINT", - "AZURE_CONTENT_SAFETY_API_KEY", ]: if var in os.environ: del os.environ[var] @@ -137,7 +131,7 @@ def test_validate_missing_multiple_env_vars_raises_error(self): """Test that validate raises error listing all missing env vars.""" # Remove multiple required env vars del os.environ["AZURE_OPENAI_GPT4O_UNSAFE_CHAT_ENDPOINT"] - del os.environ["AZURE_OPENAI_GPT4O_UNSAFE_CHAT_KEY"] + del os.environ["AZURE_OPENAI_GPT4O_UNSAFE_CHAT_MODEL"] init = AIRTInitializer() with pytest.raises(ValueError) as exc_info: @@ -145,7 +139,7 @@ def test_validate_missing_multiple_env_vars_raises_error(self): error_message = str(exc_info.value) assert "AZURE_OPENAI_GPT4O_UNSAFE_CHAT_ENDPOINT" in error_message - assert "AZURE_OPENAI_GPT4O_UNSAFE_CHAT_KEY" in error_message + assert "AZURE_OPENAI_GPT4O_UNSAFE_CHAT_MODEL" in error_message class TestAIRTInitializerGetInfo: @@ -160,11 +154,8 @@ async def test_get_info_returns_expected_structure(self): assert info["class"] == "AIRTInitializer" assert "required_env_vars" in info assert "AZURE_OPENAI_GPT4O_UNSAFE_CHAT_ENDPOINT" in info["required_env_vars"] - assert "AZURE_OPENAI_GPT4O_UNSAFE_CHAT_KEY" in info["required_env_vars"] assert "AZURE_OPENAI_GPT4O_UNSAFE_CHAT_ENDPOINT2" in info["required_env_vars"] - assert "AZURE_OPENAI_GPT4O_UNSAFE_CHAT_KEY2" in info["required_env_vars"] assert "AZURE_CONTENT_SAFETY_API_ENDPOINT" in info["required_env_vars"] - assert "AZURE_CONTENT_SAFETY_API_KEY" in info["required_env_vars"] async def test_get_info_includes_description(self): """Test that get_info_async includes the description field.""" diff --git a/tests/unit/setup/test_airt_targets_initializer.py b/tests/unit/setup/test_airt_targets_initializer.py index 356a6388d5..39571cfed8 100644 --- a/tests/unit/setup/test_airt_targets_initializer.py +++ b/tests/unit/setup/test_airt_targets_initializer.py @@ -165,6 +165,23 @@ async def test_registers_ollama_without_api_key(self): assert target is not None assert target._model_name == "llama2" + @pytest.mark.asyncio + async def test_registers_gpt5_high_reasoning_with_extra_body_parameters(self): + """Test that GPT-5 high-reasoning target has extra_body_parameters set.""" + os.environ["AZURE_OPENAI_GPT5_RESPONSES_ENDPOINT"] = "https://gpt5.openai.azure.com" + os.environ["AZURE_OPENAI_GPT5_KEY"] = "test_key" + os.environ["AZURE_OPENAI_GPT5_MODEL"] = "gpt-5" + os.environ["AZURE_OPENAI_GPT5_UNDERLYING_MODEL"] = "gpt-5" + + init = AIRTTargetInitializer() + await init.initialize_async() + + registry = TargetRegistry.get_registry_singleton() + assert "azure_openai_gpt5_responses_high_reasoning" in registry + target = registry.get_instance_by_name("azure_openai_gpt5_responses_high_reasoning") + assert target is not None + assert target._extra_body_parameters == {"reasoning": {"effort": "high"}} + @pytest.mark.usefixtures("patch_central_database") class TestAIRTTargetInitializerTargetConfigs: From a9993aba502afe88b98259be0c6acc56d0a3e4cd Mon Sep 17 00:00:00 2001 From: Roman Lutz Date: Sat, 28 Feb 2026 14:52:53 +0000 Subject: [PATCH 2/7] Expand memory interface and models for attack results - Add conversation_stats model and attack_result extensions - Add get_attack_results with filtering by harm categories, labels, attack type, and converter types to memory interface - Implement SQLite-specific JSON filtering for attack results - Add memory_models field for targeted_harm_categories - Add prompt_metadata support to openai image/video/response targets - Fix missing return statements in SQLite harm_category and label filters Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- pyrit/memory/azure_sql_memory.py | 119 +++++++-- pyrit/memory/memory_interface.py | 170 ++++++++++--- pyrit/memory/memory_models.py | 1 + pyrit/memory/sqlite_memory.py | 142 ++++++++--- pyrit/models/__init__.py | 2 + pyrit/models/attack_result.py | 4 + pyrit/models/conversation_stats.py | 23 ++ .../openai/openai_image_target.py | 10 + .../openai/openai_realtime_target.py | 3 +- .../openai/openai_response_target.py | 6 + pyrit/prompt_target/openai/openai_target.py | 6 +- .../openai/openai_video_target.py | 10 + .../test_interface_attack_results.py | 240 +++++++++++++----- tests/unit/memory/test_sqlite_memory.py | 120 +++++++++ tests/unit/target/test_image_target.py | 18 ++ tests/unit/target/test_video_target.py | 17 ++ 16 files changed, 749 insertions(+), 142 deletions(-) create mode 100644 pyrit/models/conversation_stats.py diff --git a/pyrit/memory/azure_sql_memory.py b/pyrit/memory/azure_sql_memory.py index 6702f22407..d441197492 100644 --- a/pyrit/memory/azure_sql_memory.py +++ b/pyrit/memory/azure_sql_memory.py @@ -1,6 +1,7 @@ # Copyright (c) Microsoft Corporation. # Licensed under the MIT license. +import json import logging import struct from collections.abc import MutableSequence, Sequence @@ -27,6 +28,7 @@ ) from pyrit.models import ( AzureBlobStorageIO, + ConversationStats, MessagePiece, ) @@ -386,37 +388,37 @@ def _get_attack_result_label_condition(self, *, labels: dict[str, str]) -> Any: ) ) - def _get_attack_result_attack_class_condition(self, *, attack_class: str) -> Any: + def _get_attack_result_attack_type_condition(self, *, attack_type: str) -> Any: """ Azure SQL implementation for filtering AttackResults by attack type. Uses JSON_VALUE() to match class_name in the attack_identifier JSON column. Args: - attack_class (str): Exact attack class name to match. + attack_type (str): Exact attack type name to match. Returns: Any: SQLAlchemy text condition with bound parameter. """ return text( """ISJSON("AttackResultEntries".attack_identifier) = 1 - AND JSON_VALUE("AttackResultEntries".attack_identifier, '$.class_name') = :attack_class""" - ).bindparams(attack_class=attack_class) + AND JSON_VALUE("AttackResultEntries".attack_identifier, '$.class_name') = :attack_type""" + ).bindparams(attack_type=attack_type) - def _get_attack_result_converter_condition(self, *, converter_classes: Sequence[str]) -> Any: + def _get_attack_result_converter_types_condition(self, *, converter_types: Sequence[str]) -> Any: """ - Azure SQL implementation for filtering AttackResults by converter classes. + Azure SQL implementation for filtering AttackResults by converter types. - When converter_classes is empty, matches attacks with no converters. - When non-empty, uses OPENJSON() to check all specified classes are present + When converter_types is empty, matches attacks with no converters. + When non-empty, uses OPENJSON() to check all specified types are present (AND logic, case-insensitive). Args: - converter_classes (Sequence[str]): List of converter class names. Empty list means no converters. + converter_types (Sequence[str]): List of converter type names. Empty list means no converters. Returns: Any: SQLAlchemy combined condition with bound parameters. """ - if len(converter_classes) == 0: + if len(converter_types) == 0: # Explicitly "no converters": match attacks where the converter list # is absent, null, or empty in the stored JSON. return text( @@ -428,7 +430,7 @@ def _get_attack_result_converter_condition(self, *, converter_classes: Sequence[ conditions = [] bindparams_dict: dict[str, str] = {} - for i, cls in enumerate(converter_classes): + for i, cls in enumerate(converter_types): param_name = f"conv_cls_{i}" conditions.append( f'EXISTS(SELECT 1 FROM OPENJSON(JSON_QUERY("AttackResultEntries".attack_identifier, ' @@ -442,7 +444,7 @@ def _get_attack_result_converter_condition(self, *, converter_classes: Sequence[ **bindparams_dict ) - def get_unique_attack_class_names(self) -> list[str]: + def get_unique_attack_type_names(self) -> list[str]: """ Azure SQL implementation: extract unique class_name values from attack_identifier JSON. @@ -460,7 +462,7 @@ def get_unique_attack_class_names(self) -> list[str]: ).fetchall() return sorted(row[0] for row in rows) - def get_unique_converter_class_names(self) -> list[str]: + def get_unique_converter_type_names(self) -> list[str]: """ Azure SQL implementation: extract unique converter class_name values from the request_converter_identifiers array in attack_identifier JSON. @@ -481,6 +483,87 @@ def get_unique_converter_class_names(self) -> list[str]: ).fetchall() return sorted(row[0] for row in rows) + def get_conversation_stats(self, *, conversation_ids: Sequence[str]) -> dict[str, ConversationStats]: + """ + Azure SQL implementation: lightweight aggregate stats per conversation. + + Executes a single SQL query that returns message count (distinct + sequences), a truncated last-message preview, the first non-empty + labels dict, and the earliest timestamp for each conversation_id. + + Args: + conversation_ids (Sequence[str]): The conversation IDs to query. + + Returns: + Mapping from conversation_id to ConversationStats. + """ + if not conversation_ids: + return {} + + placeholders = ", ".join(f":cid{i}" for i in range(len(conversation_ids))) + params = {f"cid{i}": cid for i, cid in enumerate(conversation_ids)} + + max_len = ConversationStats.PREVIEW_MAX_LEN + sql = text( + f""" + SELECT + pme.conversation_id, + COUNT(DISTINCT pme.sequence) AS msg_count, + ( + SELECT TOP 1 LEFT(p2.converted_value, {max_len + 3}) + FROM "PromptMemoryEntries" p2 + WHERE p2.conversation_id = pme.conversation_id + ORDER BY p2.sequence DESC, p2.id DESC + ) AS last_preview, + ( + SELECT TOP 1 p3.labels + FROM "PromptMemoryEntries" p3 + WHERE p3.conversation_id = pme.conversation_id + AND p3.labels IS NOT NULL + AND p3.labels != '{{}}' + AND p3.labels != 'null' + ) AS first_labels, + MIN(pme.timestamp) AS created_at + FROM "PromptMemoryEntries" pme + WHERE pme.conversation_id IN ({placeholders}) + GROUP BY pme.conversation_id + """ + ) + + with closing(self.get_session()) as session: + rows = session.execute(sql, params).fetchall() + + result: dict[str, ConversationStats] = {} + for row in rows: + conv_id, msg_count, last_preview, raw_labels, raw_created_at = row + + preview = None + if last_preview: + preview = last_preview[:max_len] + "..." if len(last_preview) > max_len else last_preview + + labels: dict[str, str] = {} + if raw_labels and raw_labels not in ("null", "{}"): + try: + labels = json.loads(raw_labels) + except (ValueError, TypeError): + pass + + created_at = None + if raw_created_at is not None: + if isinstance(raw_created_at, str): + created_at = datetime.fromisoformat(raw_created_at) + else: + created_at = raw_created_at + + result[conv_id] = ConversationStats( + message_count=msg_count, + last_message_preview=preview, + labels=labels, + created_at=created_at, + ) + + return result + def _get_scenario_result_label_condition(self, *, labels: dict[str, str]) -> Any: """ Get the SQL Azure implementation for filtering ScenarioResults by labels. @@ -673,8 +756,14 @@ def _update_entries(self, *, entries: MutableSequence[Base], update_fields: dict with closing(self.get_session()) as session: try: for entry in entries: - # Ensure the entry is attached to the session. If it's detached, merge it. - entry_in_session = session.merge(entry) if not session.is_modified(entry) else entry + # Load a fresh copy by primary key so we only touch the + # requested fields. Using merge() would copy ALL + # attributes from the (potentially stale) detached object + # and silently overwrite concurrent updates to columns + # that are NOT in update_fields. + entry_in_session = session.get(type(entry), entry.id) # type: ignore[attr-defined] + if entry_in_session is None: + entry_in_session = session.merge(entry) for field, value in update_fields.items(): if field in vars(entry_in_session): setattr(entry_in_session, field, value) diff --git a/pyrit/memory/memory_interface.py b/pyrit/memory/memory_interface.py index 67e6dcfb6d..c9c3753daa 100644 --- a/pyrit/memory/memory_interface.py +++ b/pyrit/memory/memory_interface.py @@ -34,6 +34,7 @@ ) from pyrit.models import ( AttackResult, + ConversationStats, DataTypeSerializer, Message, MessagePiece, @@ -290,33 +291,33 @@ def _get_attack_result_label_condition(self, *, labels: dict[str, str]) -> Any: """ @abc.abstractmethod - def _get_attack_result_attack_class_condition(self, *, attack_class: str) -> Any: + def _get_attack_result_attack_type_condition(self, *, attack_type: str) -> Any: """ Return a database-specific condition for filtering AttackResults by attack type (class_name in the attack_identifier JSON column). Args: - attack_class: Exact attack class name to match. + attack_type: Exact attack type name to match. Returns: Database-specific SQLAlchemy condition. """ @abc.abstractmethod - def _get_attack_result_converter_condition(self, *, converter_classes: Sequence[str]) -> Any: + def _get_attack_result_converter_types_condition(self, *, converter_types: Sequence[str]) -> Any: """ - Return a database-specific condition for filtering AttackResults by converter classes + Return a database-specific condition for filtering AttackResults by converter types in the request_converter_identifiers array within attack_identifier JSON column. - This method is only called when converter filtering is requested (converter_classes + This method is only called when converter filtering is requested (converter_types is not None). The caller handles the None-vs-list distinction: - - ``len(converter_classes) == 0``: return a condition matching attacks with NO converters. - - ``len(converter_classes) > 0``: return a condition requiring ALL specified converter - class names to be present (AND logic, case-insensitive). + - ``len(converter_types) == 0``: return a condition matching attacks with NO converters. + - ``len(converter_types) > 0``: return a condition requiring ALL specified converter + type names to be present (AND logic, case-insensitive). Args: - converter_classes: Converter class names to require. An empty sequence means + converter_types: Converter type names to require. An empty sequence means "match only attacks that have no converters". Returns: @@ -324,27 +325,45 @@ class names to be present (AND logic, case-insensitive). """ @abc.abstractmethod - def get_unique_attack_class_names(self) -> list[str]: + def get_unique_attack_type_names(self) -> list[str]: """ - Return sorted unique attack class names from all stored attack results. + Return sorted unique attack type names from all stored attack results. Extracts class_name from the attack_identifier JSON column via a database-level DISTINCT query. Returns: - Sorted list of unique attack class name strings. + Sorted list of unique attack type name strings. """ @abc.abstractmethod - def get_unique_converter_class_names(self) -> list[str]: + def get_unique_converter_type_names(self) -> list[str]: """ - Return sorted unique converter class names used across all attack results. + Return sorted unique converter type names used across all attack results. Extracts class_name values from the request_converter_identifiers array within the attack_identifier JSON column via a database-level query. Returns: - Sorted list of unique converter class name strings. + Sorted list of unique converter type name strings. + """ + + @abc.abstractmethod + def get_conversation_stats(self, *, conversation_ids: Sequence[str]) -> dict[str, "ConversationStats"]: + """ + Return lightweight aggregate statistics for one or more conversations. + + Computes per-conversation message count (distinct sequence numbers), + a truncated last-message preview, the first non-empty labels dict, + and the earliest message timestamp using efficient SQL aggregation + instead of loading full pieces. + + Args: + conversation_ids: The conversation IDs to query. + + Returns: + Mapping from conversation_id to ConversationStats. + Conversations with no pieces are omitted from the result. """ @abc.abstractmethod @@ -631,15 +650,18 @@ def get_message_pieces( logger.exception(f"Failed to retrieve prompts with error {e}") raise - def _duplicate_conversation(self, *, messages: Sequence[Message]) -> tuple[str, Sequence[MessagePiece]]: + def duplicate_messages(self, *, messages: Sequence[Message]) -> tuple[str, Sequence[MessagePiece]]: """ - Duplicate messages with new conversation ID. + Duplicate messages with a new conversation ID. + + Each duplicated piece gets a fresh ``id`` and ``timestamp`` while + preserving ``original_prompt_id`` for tracking lineage. Args: - messages (Sequence[Message]): The messages to duplicate. + messages: The messages to duplicate. Returns: - tuple[str, Sequence[MessagePiece]]: The new conversation ID and the duplicated message pieces. + Tuple of (new_conversation_id, duplicated_message_pieces). """ new_conversation_id = str(uuid.uuid4()) @@ -669,7 +691,7 @@ def duplicate_conversation(self, *, conversation_id: str) -> str: The uuid for the new conversation. """ messages = self.get_conversation(conversation_id=conversation_id) - new_conversation_id, all_pieces = self._duplicate_conversation(messages=messages) + new_conversation_id, all_pieces = self.duplicate_messages(messages=messages) self.add_message_pieces_to_memory(message_pieces=all_pieces) return new_conversation_id @@ -702,7 +724,7 @@ def duplicate_conversation_excluding_last_turn(self, *, conversation_id: str) -> message for message in messages if message.sequence <= last_message.sequence - length_of_sequence_to_remove ] - new_conversation_id, all_pieces = self._duplicate_conversation(messages=messages_to_duplicate) + new_conversation_id, all_pieces = self.duplicate_messages(messages=messages_to_duplicate) self.add_message_pieces_to_memory(message_pieces=all_pieces) return new_conversation_id @@ -1256,8 +1278,83 @@ def add_attack_results_to_memory(self, *, attack_results: Sequence[AttackResult] """ Insert a list of attack results into the memory storage. The database model automatically calculates objective_sha256 for consistency. + + Raises: + SQLAlchemyError: If the database transaction fails. + """ + entries = [AttackResultEntry(entry=attack_result) for attack_result in attack_results] + # Capture the DB-assigned IDs before insert (they'll be set after flush/commit). + # _insert_entries closes the session, so we must read `entry.id` *inside* + # the session. Since _insert_entries uses a context manager, we instead + # read the ids from the entries *before* the session closes by doing the + # insert inline. + from contextlib import closing + + with closing(self.get_session()) as session: + from sqlalchemy.exc import SQLAlchemyError + + try: + session.add_all(entries) + session.commit() + # Populate the attack_result_id back onto the domain objects so callers + # can reference the DB-assigned ID immediately after insert. + for ar, entry in zip(attack_results, entries): + ar.attack_result_id = str(entry.id) + except SQLAlchemyError: + session.rollback() + raise + + def update_attack_result(self, *, conversation_id: str, update_fields: dict[str, Any]) -> bool: """ - self._insert_entries(entries=[AttackResultEntry(entry=attack_result) for attack_result in attack_results]) + Update specific fields of an existing AttackResultEntry identified by conversation_id. + + This method queries for the raw database entry by conversation_id and updates + the specified fields in place, avoiding the creation of duplicate rows. + + Args: + conversation_id (str): The conversation ID of the attack result to update. + update_fields (dict[str, Any]): A dictionary of column names to new values. + Valid fields include 'adversarial_chat_conversation_ids', + 'pruned_conversation_ids', 'outcome', 'attack_metadata', etc. + + Returns: + bool: True if the update was successful, False if the entry was not found. + + Raises: + ValueError: If update_fields is empty. + """ + entries: MutableSequence[AttackResultEntry] = self._query_entries( + AttackResultEntry, + conditions=AttackResultEntry.conversation_id == conversation_id, + ) + if not entries: + return False + + # When duplicate rows exist for the same conversation_id (legacy bug), + # pick the newest entry — it has the most up-to-date data. + target_entry = max(entries, key=lambda e: e.timestamp) + self._update_entries(entries=[target_entry], update_fields=update_fields) + return True + + def update_attack_result_by_id(self, *, attack_result_id: str, update_fields: dict[str, Any]) -> bool: + """ + Update specific fields of an existing AttackResultEntry identified by its primary key. + + Args: + attack_result_id: The UUID primary key of the AttackResultEntry. + update_fields: Column names to new values. + + Returns: + True if the update was successful, False if the entry was not found. + """ + entries: MutableSequence[AttackResultEntry] = self._query_entries( + AttackResultEntry, + conditions=AttackResultEntry.id == attack_result_id, + ) + if not entries: + return False + self._update_entries(entries=[entries[0]], update_fields=update_fields) + return True def get_attack_results( self, @@ -1267,8 +1364,8 @@ def get_attack_results( objective: Optional[str] = None, objective_sha256: Optional[Sequence[str]] = None, outcome: Optional[str] = None, - attack_class: Optional[str] = None, - converter_classes: Optional[Sequence[str]] = None, + attack_type: Optional[str] = None, + converter_types: Optional[Sequence[str]] = None, targeted_harm_categories: Optional[Sequence[str]] = None, labels: Optional[dict[str, str]] = None, ) -> Sequence[AttackResult]: @@ -1283,9 +1380,9 @@ def get_attack_results( Defaults to None. outcome (Optional[str], optional): The outcome to filter by (success, failure, undetermined). Defaults to None. - attack_class (Optional[str], optional): Filter by exact attack class_name in attack_identifier. + attack_type (Optional[str], optional): Filter by exact attack class_name in attack_identifier. Defaults to None. - converter_classes (Optional[Sequence[str]], optional): Filter by converter class names. + converter_types (Optional[Sequence[str]], optional): Filter by converter type names. Returns only attacks that used ALL specified converters (AND logic, case-insensitive). Defaults to None. targeted_harm_categories (Optional[Sequence[str]], optional): @@ -1319,14 +1416,14 @@ def get_attack_results( if outcome: conditions.append(AttackResultEntry.outcome == outcome) - if attack_class: + if attack_type: # Use database-specific JSON query method - conditions.append(self._get_attack_result_attack_class_condition(attack_class=attack_class)) + conditions.append(self._get_attack_result_attack_type_condition(attack_type=attack_type)) - if converter_classes is not None: - # converter_classes=[] means "only attacks with no converters" - # converter_classes=["A","B"] means "must have all listed converters" - conditions.append(self._get_attack_result_converter_condition(converter_classes=converter_classes)) + if converter_types is not None: + # converter_types=[] means "only attacks with no converters" + # converter_types=["A","B"] means "must have all listed converters" + conditions.append(self._get_attack_result_converter_types_condition(converter_types=converter_types)) if targeted_harm_categories: # Use database-specific JSON query method @@ -1342,7 +1439,14 @@ def get_attack_results( entries: Sequence[AttackResultEntry] = self._query_entries( AttackResultEntry, conditions=and_(*conditions) if conditions else None ) - return [entry.get_attack_result() for entry in entries] + # Deduplicate by conversation_id — when duplicate rows exist + # (legacy bug), keep only the newest entry per conversation_id. + seen: dict[str, AttackResultEntry] = {} + for entry in entries: + prev = seen.get(entry.conversation_id) + if prev is None or entry.timestamp > prev.timestamp: + seen[entry.conversation_id] = entry + return [entry.get_attack_result() for entry in seen.values()] except Exception as e: logger.exception(f"Failed to retrieve attack results with error {e}") raise diff --git a/pyrit/memory/memory_models.py b/pyrit/memory/memory_models.py index 04be633df5..50ed0fb876 100644 --- a/pyrit/memory/memory_models.py +++ b/pyrit/memory/memory_models.py @@ -852,6 +852,7 @@ def get_attack_result(self) -> AttackResult: return AttackResult( conversation_id=self.conversation_id, + attack_result_id=str(self.id), objective=self.objective, attack_identifier=ComponentIdentifier.from_dict(self.attack_identifier) if self.attack_identifier else None, last_response=self.last_response.get_message_piece() if self.last_response else None, diff --git a/pyrit/memory/sqlite_memory.py b/pyrit/memory/sqlite_memory.py index cfce238fdb..375c348e9d 100644 --- a/pyrit/memory/sqlite_memory.py +++ b/pyrit/memory/sqlite_memory.py @@ -1,6 +1,7 @@ # Copyright (c) Microsoft Corporation. # Licensed under the MIT license. +import json import logging import uuid from collections.abc import MutableSequence, Sequence @@ -9,7 +10,7 @@ from pathlib import Path from typing import Any, Optional, TypeVar, Union -from sqlalchemy import and_, create_engine, func, or_, text +from sqlalchemy import and_, create_engine, exists, func, or_, text from sqlalchemy.engine.base import Engine from sqlalchemy.exc import SQLAlchemyError from sqlalchemy.orm import joinedload, sessionmaker @@ -24,8 +25,9 @@ Base, EmbeddingDataEntry, PromptMemoryEntry, + ScenarioResultEntry, ) -from pyrit.models import DiskStorageIO, MessagePiece +from pyrit.models import ConversationStats, DiskStorageIO, MessagePiece logger = logging.getLogger(__name__) @@ -298,8 +300,14 @@ def _update_entries(self, *, entries: MutableSequence[Base], update_fields: dict with closing(self.get_session()) as session: try: for entry in entries: - # Ensure the entry is attached to the session. If it's detached, merge it. - entry_in_session = session.merge(entry) if not session.is_modified(entry) else entry + # Load a fresh copy by primary key so we only touch the + # requested fields. Using merge() would copy ALL + # attributes from the (potentially stale) detached object + # and silently overwrite concurrent updates to columns + # that are NOT in update_fields. + entry_in_session = session.get(type(entry), entry.id) # type: ignore[attr-defined] + if entry_in_session is None: + entry_in_session = session.merge(entry) for field, value in update_fields.items(): if field in vars(entry_in_session): setattr(entry_in_session, field, value) @@ -412,8 +420,6 @@ def export_conversations( # Export to JSON manually since the exporter expects objects but we have dicts with open(file_path, "w") as f: - import json - json.dump(merged_data, f, indent=4) return file_path @@ -462,7 +468,7 @@ def _get_attack_result_harm_category_condition(self, *, targeted_harm_categories from pyrit.memory.memory_models import AttackResultEntry, PromptMemoryEntry - return exists().where( + targeted_harm_categories_subquery = exists().where( and_( PromptMemoryEntry.conversation_id == AttackResultEntry.conversation_id, # Exclude empty strings, None, and empty lists @@ -477,6 +483,7 @@ def _get_attack_result_harm_category_condition(self, *, targeted_harm_categories ), ) ) + return targeted_harm_categories_subquery def _get_attack_result_label_condition(self, *, labels: dict[str, str]) -> Any: """ @@ -490,7 +497,7 @@ def _get_attack_result_label_condition(self, *, labels: dict[str, str]) -> Any: from pyrit.memory.memory_models import AttackResultEntry, PromptMemoryEntry - return exists().where( + labels_subquery = exists().where( and_( PromptMemoryEntry.conversation_id == AttackResultEntry.conversation_id, PromptMemoryEntry.labels.isnot(None), @@ -499,8 +506,9 @@ def _get_attack_result_label_condition(self, *, labels: dict[str, str]) -> Any: ), ) ) + return labels_subquery - def _get_attack_result_attack_class_condition(self, *, attack_class: str) -> Any: + def _get_attack_result_attack_type_condition(self, *, attack_type: str) -> Any: """ SQLite implementation for filtering AttackResults by attack type. Uses json_extract() to match class_name in the attack_identifier JSON column. @@ -508,21 +516,21 @@ def _get_attack_result_attack_class_condition(self, *, attack_class: str) -> Any Returns: Any: A SQLAlchemy condition for filtering by attack type. """ - return func.json_extract(AttackResultEntry.attack_identifier, "$.class_name") == attack_class + return func.json_extract(AttackResultEntry.attack_identifier, "$.class_name") == attack_type - def _get_attack_result_converter_condition(self, *, converter_classes: Sequence[str]) -> Any: + def _get_attack_result_converter_types_condition(self, *, converter_types: Sequence[str]) -> Any: """ - SQLite implementation for filtering AttackResults by converter classes. + SQLite implementation for filtering AttackResults by converter types. - When converter_classes is empty, matches attacks with no converters + When converter_types is empty, matches attacks with no converters (request_converter_identifiers is absent or null in the JSON). - When non-empty, uses json_each() to check all specified classes are present + When non-empty, uses json_each() to check all specified types are present (AND logic, case-insensitive). Returns: - Any: A SQLAlchemy condition for filtering by converter classes. + Any: A SQLAlchemy condition for filtering by converter types. """ - if len(converter_classes) == 0: + if len(converter_types) == 0: # Explicitly "no converters": match attacks where the converter list # is absent, null, or empty in the stored JSON. converter_json = func.json_extract(AttackResultEntry.attack_identifier, "$.request_converter_identifiers") @@ -534,7 +542,7 @@ def _get_attack_result_converter_condition(self, *, converter_classes: Sequence[ ) conditions = [] - for i, cls in enumerate(converter_classes): + for i, cls in enumerate(converter_types): param_name = f"conv_cls_{i}" conditions.append( text( @@ -545,7 +553,7 @@ def _get_attack_result_converter_condition(self, *, converter_classes: Sequence[ ) return and_(*conditions) - def get_unique_attack_class_names(self) -> list[str]: + def get_unique_attack_type_names(self) -> list[str]: """ SQLite implementation: extract unique class_name values from attack_identifier JSON. @@ -561,7 +569,7 @@ def get_unique_attack_class_names(self) -> list[str]: ) return sorted(row[0] for row in rows) - def get_unique_converter_class_names(self) -> list[str]: + def get_unique_converter_type_names(self) -> list[str]: """ SQLite implementation: extract unique converter class_name values from the request_converter_identifiers array in attack_identifier JSON. @@ -581,6 +589,89 @@ def get_unique_converter_class_names(self) -> list[str]: ).fetchall() return sorted(row[0] for row in rows) + def get_conversation_stats(self, *, conversation_ids: Sequence[str]) -> dict[str, ConversationStats]: + """ + SQLite implementation: lightweight aggregate stats per conversation. + + Executes a single SQL query that returns message count (distinct + sequences), a truncated last-message preview, the first non-empty + labels dict, and the earliest timestamp for each conversation_id. + + Args: + conversation_ids: The conversation IDs to query. + + Returns: + Mapping from conversation_id to ConversationStats. + """ + if not conversation_ids: + return {} + + placeholders = ", ".join(f":cid{i}" for i in range(len(conversation_ids))) + params = {f"cid{i}": cid for i, cid in enumerate(conversation_ids)} + + max_len = ConversationStats.PREVIEW_MAX_LEN + sql = text( + f""" + SELECT + pme.conversation_id, + COUNT(DISTINCT pme.sequence) AS msg_count, + ( + SELECT SUBSTR(p2.converted_value, 1, {max_len + 3}) + FROM "PromptMemoryEntries" p2 + WHERE p2.conversation_id = pme.conversation_id + ORDER BY p2.sequence DESC, p2.id DESC + LIMIT 1 + ) AS last_preview, + ( + SELECT p3.labels + FROM "PromptMemoryEntries" p3 + WHERE p3.conversation_id = pme.conversation_id + AND p3.labels IS NOT NULL + AND p3.labels != '{{}}' + AND p3.labels != 'null' + LIMIT 1 + ) AS first_labels, + MIN(pme.timestamp) AS created_at + FROM "PromptMemoryEntries" pme + WHERE pme.conversation_id IN ({placeholders}) + GROUP BY pme.conversation_id + """ + ) + + with closing(self.get_session()) as session: + rows = session.execute(sql, params).fetchall() + + result: dict[str, ConversationStats] = {} + for row in rows: + conv_id, msg_count, last_preview, raw_labels, raw_created_at = row + + preview = None + if last_preview: + preview = last_preview[:max_len] + "..." if len(last_preview) > max_len else last_preview + + labels: dict[str, str] = {} + if raw_labels and raw_labels not in ("null", "{}"): + try: + labels = json.loads(raw_labels) + except (ValueError, TypeError): + pass + + created_at = None + if raw_created_at is not None: + if isinstance(raw_created_at, str): + created_at = datetime.fromisoformat(raw_created_at) + else: + created_at = raw_created_at + + result[conv_id] = ConversationStats( + message_count=msg_count, + last_message_preview=preview, + labels=labels, + created_at=created_at, + ) + + return result + def _get_scenario_result_label_condition(self, *, labels: dict[str, str]) -> Any: """ SQLite implementation for filtering ScenarioResults by labels. @@ -589,11 +680,6 @@ def _get_scenario_result_label_condition(self, *, labels: dict[str, str]) -> Any Returns: Any: A SQLAlchemy exists subquery condition. """ - from sqlalchemy import and_, func - - from pyrit.memory.memory_models import ScenarioResultEntry - - # Return a combined condition that checks ALL labels must be present return and_( *[func.json_extract(ScenarioResultEntry.labels, f"$.{key}") == value for key, value in labels.items()] ) @@ -606,10 +692,6 @@ def _get_scenario_result_target_endpoint_condition(self, *, endpoint: str) -> An Returns: Any: A SQLAlchemy subquery for filtering by target endpoint. """ - from sqlalchemy import func - - from pyrit.memory.memory_models import ScenarioResultEntry - return func.lower(func.json_extract(ScenarioResultEntry.objective_target_identifier, "$.endpoint")).like( f"%{endpoint.lower()}%" ) @@ -622,10 +704,6 @@ def _get_scenario_result_target_model_condition(self, *, model_name: str) -> Any Returns: Any: A SQLAlchemy subquery for filtering by target model name. """ - from sqlalchemy import func - - from pyrit.memory.memory_models import ScenarioResultEntry - return func.lower(func.json_extract(ScenarioResultEntry.objective_target_identifier, "$.model_name")).like( f"%{model_name.lower()}%" ) diff --git a/pyrit/models/__init__.py b/pyrit/models/__init__.py index 6f6734cb86..26eeae2d15 100644 --- a/pyrit/models/__init__.py +++ b/pyrit/models/__init__.py @@ -11,6 +11,7 @@ ChatMessagesDataset, ) from pyrit.models.conversation_reference import ConversationReference, ConversationType +from pyrit.models.conversation_stats import ConversationStats from pyrit.models.data_type_serializer import ( AllowedCategories, AudioPathDataTypeSerializer, @@ -70,6 +71,7 @@ "ChatMessageRole", "ChatMessageListDictContent", "ConversationReference", + "ConversationStats", "ConversationType", "construct_response_from_request", "DataTypeSerializer", diff --git a/pyrit/models/attack_result.py b/pyrit/models/attack_result.py index cd9efff5ce..499e3f6de3 100644 --- a/pyrit/models/attack_result.py +++ b/pyrit/models/attack_result.py @@ -47,6 +47,10 @@ class AttackResult(StrategyResult): # Natural-language description of the attacker's objective objective: str + # Database-assigned unique ID for this AttackResult row. + # ``None`` for newly-constructed results that haven't been persisted yet. + attack_result_id: Optional[str] = None + # Identifier of the attack strategy that produced this result attack_identifier: Optional[ComponentIdentifier] = None diff --git a/pyrit/models/conversation_stats.py b/pyrit/models/conversation_stats.py new file mode 100644 index 0000000000..c67f3d8427 --- /dev/null +++ b/pyrit/models/conversation_stats.py @@ -0,0 +1,23 @@ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT license. + +from __future__ import annotations + +from dataclasses import dataclass, field +from datetime import datetime +from typing import ClassVar, Dict, Optional + + +@dataclass(frozen=True) +class ConversationStats: + """Lightweight aggregate statistics for a conversation. + + Used to build attack summaries without loading full message pieces. + """ + + PREVIEW_MAX_LEN: ClassVar[int] = 100 + + message_count: int = 0 + last_message_preview: Optional[str] = None + labels: Dict[str, str] = field(default_factory=dict) + created_at: Optional[datetime] = None diff --git a/pyrit/prompt_target/openai/openai_image_target.py b/pyrit/prompt_target/openai/openai_image_target.py index 1c65ed6030..ebdbdfe1a0 100644 --- a/pyrit/prompt_target/openai/openai_image_target.py +++ b/pyrit/prompt_target/openai/openai_image_target.py @@ -314,6 +314,16 @@ def _validate_request(self, *, message: Message) -> None: other_types = [p.converted_value_data_type for p in other_pieces] raise ValueError(f"The message contains unsupported piece types. Unsupported types: {other_types}.") + request = text_pieces[0] + messages = self._memory.get_conversation(conversation_id=request.conversation_id) + + n_messages = len(messages) + if n_messages > 0: + raise ValueError( + "This target only supports a single turn conversation. " + f"Received: {n_messages} messages which indicates a prior turn." + ) + def is_json_response_supported(self) -> bool: """ Check if the target supports JSON as a response format. diff --git a/pyrit/prompt_target/openai/openai_realtime_target.py b/pyrit/prompt_target/openai/openai_realtime_target.py index 774eeb7733..c57de2156d 100644 --- a/pyrit/prompt_target/openai/openai_realtime_target.py +++ b/pyrit/prompt_target/openai/openai_realtime_target.py @@ -21,6 +21,7 @@ construct_response_from_request, data_serializer_factory, ) +from pyrit.prompt_target.common.prompt_chat_target import PromptChatTarget from pyrit.prompt_target.common.utils import limit_requests_per_minute from pyrit.prompt_target.openai.openai_target import OpenAITarget @@ -55,7 +56,7 @@ def flatten_transcripts(self) -> str: return "".join(self.transcripts) -class RealtimeTarget(OpenAITarget): +class RealtimeTarget(OpenAITarget, PromptChatTarget): """ A prompt target for Azure OpenAI Realtime API. diff --git a/pyrit/prompt_target/openai/openai_response_target.py b/pyrit/prompt_target/openai/openai_response_target.py index 34ff23b700..5352573d7a 100644 --- a/pyrit/prompt_target/openai/openai_response_target.py +++ b/pyrit/prompt_target/openai/openai_response_target.py @@ -171,6 +171,11 @@ def _build_identifier(self) -> ComponentIdentifier: Returns: ComponentIdentifier: The identifier for this target instance. """ + specific_params: dict[str, Any] = { + "max_output_tokens": self._max_output_tokens, + } + if self._extra_body_parameters: + specific_params["extra_body_parameters"] = self._extra_body_parameters return self._create_identifier( params={ "temperature": self._temperature, @@ -179,6 +184,7 @@ def _build_identifier(self) -> ComponentIdentifier: "reasoning_effort": self._reasoning_effort, "reasoning_summary": self._reasoning_summary, }, + target_specific_params=specific_params, ) def _set_openai_env_configuration_vars(self) -> None: diff --git a/pyrit/prompt_target/openai/openai_target.py b/pyrit/prompt_target/openai/openai_target.py index bf9c46bf6e..e4fb8ecddd 100644 --- a/pyrit/prompt_target/openai/openai_target.py +++ b/pyrit/prompt_target/openai/openai_target.py @@ -29,7 +29,7 @@ handle_bad_request_exception, ) from pyrit.models import Message, MessagePiece -from pyrit.prompt_target.common.prompt_chat_target import PromptChatTarget +from pyrit.prompt_target.common.prompt_target import PromptTarget from pyrit.prompt_target.openai.openai_error_handling import ( _extract_error_payload, _extract_request_id_from_exception, @@ -78,7 +78,7 @@ async def async_token_provider() -> str: return async_token_provider -class OpenAITarget(PromptChatTarget): +class OpenAITarget(PromptTarget): """ Abstract base class for OpenAI-based prompt targets. @@ -159,7 +159,7 @@ def __init__( ) # Initialize parent with endpoint and model_name - PromptChatTarget.__init__( + PromptTarget.__init__( self, max_requests_per_minute=max_requests_per_minute, endpoint=endpoint_value, diff --git a/pyrit/prompt_target/openai/openai_video_target.py b/pyrit/prompt_target/openai/openai_video_target.py index 276bbfc2c7..b6b96956e0 100644 --- a/pyrit/prompt_target/openai/openai_video_target.py +++ b/pyrit/prompt_target/openai/openai_video_target.py @@ -476,6 +476,16 @@ def _validate_request(self, *, message: Message) -> None: if remix_video_id and image_pieces: raise ValueError("Cannot use image input in remix mode. Remix uses existing video as reference.") + request = message.message_pieces[0] + messages = self._memory.get_conversation(conversation_id=request.conversation_id) + + n_messages = len(messages) + if n_messages > 0: + raise ValueError( + "This target only supports a single turn conversation. " + f"Received: {n_messages} messages which indicates a prior turn." + ) + def is_json_response_supported(self) -> bool: """ Check if the target supports JSON response data. diff --git a/tests/unit/memory/memory_interface/test_interface_attack_results.py b/tests/unit/memory/memory_interface/test_interface_attack_results.py index 3106409fde..b977532059 100644 --- a/tests/unit/memory/memory_interface/test_interface_attack_results.py +++ b/tests/unit/memory/memory_interface/test_interface_attack_results.py @@ -126,7 +126,11 @@ def test_get_attack_results_by_ids(sqlite_instance: MemoryInterface): def test_get_attack_results_by_conversation_id(sqlite_instance: MemoryInterface): - """Test retrieving attack results by conversation ID.""" + """Test retrieving attack results by conversation ID. + + When duplicate rows exist for the same conversation_id (legacy bug), + get_attack_results deduplicates and returns only the newest entry. + """ # Create and add attack results attack_result1 = AttackResult( conversation_id="conv_1", @@ -137,7 +141,7 @@ def test_get_attack_results_by_conversation_id(sqlite_instance: MemoryInterface) ) attack_result2 = AttackResult( - conversation_id="conv_1", # Same conversation ID + conversation_id="conv_1", # Same conversation ID (simulates legacy duplicate) objective="Test objective 2", executed_turns=3, execution_time_ms=500, @@ -155,13 +159,11 @@ def test_get_attack_results_by_conversation_id(sqlite_instance: MemoryInterface) # Add all attack results to memory sqlite_instance.add_attack_results_to_memory(attack_results=[attack_result1, attack_result2, attack_result3]) - # Retrieve attack results by conversation ID + # Retrieve attack results by conversation ID — deduplication keeps only the newest retrieved_results = sqlite_instance.get_attack_results(conversation_id="conv_1") - # Verify correct results were retrieved - assert len(retrieved_results) == 2 - for result in retrieved_results: - assert result.conversation_id == "conv_1" + assert len(retrieved_results) == 1 + assert retrieved_results[0].conversation_id == "conv_1" def test_get_attack_results_by_objective(sqlite_instance: MemoryInterface): @@ -593,6 +595,128 @@ def test_attack_result_without_attack_generation_conversation_ids(sqlite_instanc assert not retrieved_result.get_conversations_by_type(ConversationType.ADVERSARIAL) +def test_update_attack_result_adversarial_chat_conversation_ids_round_trip(sqlite_instance: MemoryInterface): + """Test that updating adversarial_chat_conversation_ids is reflected when reading back. + + This catches a regression where the conversation count in the attack history + was always showing 1 instead of the actual number of conversations. + """ + # Create attack with no related conversations + attack_result = AttackResult( + conversation_id="conv_1", + objective="Test conversation count", + outcome=AttackOutcome.UNDETERMINED, + metadata={"created_at": "2026-01-01T00:00:00", "updated_at": "2026-01-01T00:00:00"}, + ) + sqlite_instance.add_attack_results_to_memory(attack_results=[attack_result]) + + # Verify initial state: no related conversations + results = sqlite_instance.get_attack_results(conversation_id="conv_1") + assert len(results) == 1 + assert len(results[0].related_conversations) == 0 + + # Add first related conversation + sqlite_instance.update_attack_result( + conversation_id="conv_1", + update_fields={"adversarial_chat_conversation_ids": ["branch-1"]}, + ) + + results = sqlite_instance.get_attack_results(conversation_id="conv_1") + assert len(results[0].related_conversations) == 1 + assert {r.conversation_id for r in results[0].related_conversations} == {"branch-1"} + + # Add second related conversation (preserving the first) + sqlite_instance.update_attack_result( + conversation_id="conv_1", + update_fields={"adversarial_chat_conversation_ids": ["branch-1", "branch-2"]}, + ) + + results = sqlite_instance.get_attack_results(conversation_id="conv_1") + assert len(results[0].related_conversations) == 2 + assert {r.conversation_id for r in results[0].related_conversations} == {"branch-1", "branch-2"} + + # Verify they are all ADVERSARIAL type + for ref in results[0].related_conversations: + assert ref.conversation_type == ConversationType.ADVERSARIAL + + +def test_update_attack_result_metadata_does_not_clobber_conversation_ids(sqlite_instance: MemoryInterface): + """Regression test: updating only attack_metadata must not erase adversarial_chat_conversation_ids. + + This was the root cause of the conversation-count bug. The old _update_entries + used session.merge() which copied ALL attributes from the (potentially stale) + detached entry, silently overwriting JSON columns that were not in update_fields. + """ + attack_result = AttackResult( + conversation_id="conv_1", + objective="Test metadata update preserves conversation ids", + outcome=AttackOutcome.UNDETERMINED, + metadata={"created_at": "2026-01-01T00:00:00"}, + ) + sqlite_instance.add_attack_results_to_memory(attack_results=[attack_result]) + + # Step 1: add related conversations + sqlite_instance.update_attack_result( + conversation_id="conv_1", + update_fields={"adversarial_chat_conversation_ids": ["branch-1", "branch-2"]}, + ) + + # Step 2: update ONLY metadata (this is what add_message_async does) + sqlite_instance.update_attack_result( + conversation_id="conv_1", + update_fields={"attack_metadata": {"created_at": "2026-01-01T00:00:00", "updated_at": "2026-01-02T00:00:00"}}, + ) + + # Verify conversation ids are still present + results = sqlite_instance.get_attack_results(conversation_id="conv_1") + assert len(results[0].related_conversations) == 2, ( + "Updating attack_metadata must not erase adversarial_chat_conversation_ids" + ) + assert {r.conversation_id for r in results[0].related_conversations} == {"branch-1", "branch-2"} + + +def test_update_attack_result_stale_entry_does_not_overwrite(sqlite_instance: MemoryInterface): + """Regression test: merging a stale entry must not overwrite concurrent updates. + + Simulates the race condition where entry is loaded, then another update modifies + the DB, and finally the stale entry is used for an unrelated update. + """ + from pyrit.memory.memory_models import AttackResultEntry + + attack_result = AttackResult( + conversation_id="conv_1", + objective="Test stale merge", + outcome=AttackOutcome.UNDETERMINED, + metadata={"created_at": "2026-01-01T00:00:00"}, + ) + sqlite_instance.add_attack_results_to_memory(attack_results=[attack_result]) + + # Load entry (will become stale) + stale_entries = sqlite_instance._query_entries( + AttackResultEntry, conditions=AttackResultEntry.conversation_id == "conv_1" + ) + assert stale_entries[0].adversarial_chat_conversation_ids is None + + # Concurrent update adds conversation ids + sqlite_instance.update_attack_result( + conversation_id="conv_1", + update_fields={"adversarial_chat_conversation_ids": ["branch-1"]}, + ) + + # Now update with the stale entry (only metadata) + sqlite_instance._update_entries( + entries=[stale_entries[0]], + update_fields={"attack_metadata": {"updated_at": "2026-01-02T00:00:00"}}, + ) + + # Verify the concurrent update was NOT lost + results = sqlite_instance.get_attack_results(conversation_id="conv_1") + assert len(results[0].related_conversations) == 1, ( + "Stale entry merge must not overwrite concurrent adversarial_chat_conversation_ids update" + ) + assert results[0].related_conversations.pop().conversation_id == "branch-1" + + def test_get_attack_results_by_harm_category_single(sqlite_instance: MemoryInterface): """Test filtering attack results by a single harm category.""" @@ -1025,60 +1149,60 @@ def _make_attack_result_with_identifier( ) -def test_get_attack_results_by_attack_class(sqlite_instance: MemoryInterface): - """Test filtering attack results by attack_class matches class_name in JSON.""" +def test_get_attack_results_by_attack_type(sqlite_instance: MemoryInterface): + """Test filtering attack results by attack_type matches class_name in JSON.""" ar1 = _make_attack_result_with_identifier("conv_1", "CrescendoAttack") ar2 = _make_attack_result_with_identifier("conv_2", "ManualAttack") ar3 = _make_attack_result_with_identifier("conv_3", "CrescendoAttack") sqlite_instance.add_attack_results_to_memory(attack_results=[ar1, ar2, ar3]) - results = sqlite_instance.get_attack_results(attack_class="CrescendoAttack") + results = sqlite_instance.get_attack_results(attack_type="CrescendoAttack") assert len(results) == 2 assert {r.conversation_id for r in results} == {"conv_1", "conv_3"} -def test_get_attack_results_by_attack_class_no_match(sqlite_instance: MemoryInterface): - """Test that attack_class filter returns empty when nothing matches.""" +def test_get_attack_results_by_attack_type_no_match(sqlite_instance: MemoryInterface): + """Test that attack_type filter returns empty when nothing matches.""" ar1 = _make_attack_result_with_identifier("conv_1", "CrescendoAttack") sqlite_instance.add_attack_results_to_memory(attack_results=[ar1]) - results = sqlite_instance.get_attack_results(attack_class="NonExistentAttack") + results = sqlite_instance.get_attack_results(attack_type="NonExistentAttack") assert len(results) == 0 -def test_get_attack_results_by_attack_class_case_sensitive(sqlite_instance: MemoryInterface): - """Test that attack_class filter is case-sensitive (exact match).""" +def test_get_attack_results_by_attack_type_case_sensitive(sqlite_instance: MemoryInterface): + """Test that attack_type filter is case-sensitive (exact match).""" ar1 = _make_attack_result_with_identifier("conv_1", "CrescendoAttack") sqlite_instance.add_attack_results_to_memory(attack_results=[ar1]) - results = sqlite_instance.get_attack_results(attack_class="crescendoattack") + results = sqlite_instance.get_attack_results(attack_type="crescendoattack") assert len(results) == 0 -def test_get_attack_results_by_attack_class_no_identifier(sqlite_instance: MemoryInterface): - """Test that attacks with no attack_identifier (empty JSON) are excluded by attack_class filter.""" +def test_get_attack_results_by_attack_type_no_identifier(sqlite_instance: MemoryInterface): + """Test that attacks with no attack_identifier (empty JSON) are excluded by attack_type filter.""" ar1 = create_attack_result("conv_1", 1) # No attack_identifier → stored as {} ar2 = _make_attack_result_with_identifier("conv_2", "CrescendoAttack") sqlite_instance.add_attack_results_to_memory(attack_results=[ar1, ar2]) - results = sqlite_instance.get_attack_results(attack_class="CrescendoAttack") + results = sqlite_instance.get_attack_results(attack_type="CrescendoAttack") assert len(results) == 1 assert results[0].conversation_id == "conv_2" -def test_get_attack_results_converter_classes_none_returns_all(sqlite_instance: MemoryInterface): - """Test that converter_classes=None (omitted) returns all attacks unfiltered.""" +def test_get_attack_results_converter_types_none_returns_all(sqlite_instance: MemoryInterface): + """Test that converter_types=None (omitted) returns all attacks unfiltered.""" ar1 = _make_attack_result_with_identifier("conv_1", "Attack", ["Base64Converter"]) ar2 = _make_attack_result_with_identifier("conv_2", "Attack") # No converters (None) ar3 = create_attack_result("conv_3", 3) # No identifier at all sqlite_instance.add_attack_results_to_memory(attack_results=[ar1, ar2, ar3]) - results = sqlite_instance.get_attack_results(converter_classes=None) + results = sqlite_instance.get_attack_results(converter_types=None) assert len(results) == 3 -def test_get_attack_results_converter_classes_empty_matches_no_converters(sqlite_instance: MemoryInterface): - """Test that converter_classes=[] returns only attacks with no converters.""" +def test_get_attack_results_converter_types_empty_matches_no_converters(sqlite_instance: MemoryInterface): + """Test that converter_types=[] returns only attacks with no converters.""" ar_with_conv = _make_attack_result_with_identifier("conv_1", "Attack", ["Base64Converter"]) ar_no_conv_none = _make_attack_result_with_identifier("conv_2", "Attack") # converter_ids=None ar_no_conv_empty = _make_attack_result_with_identifier("conv_3", "Attack", []) # converter_ids=[] @@ -1087,7 +1211,7 @@ def test_get_attack_results_converter_classes_empty_matches_no_converters(sqlite attack_results=[ar_with_conv, ar_no_conv_none, ar_no_conv_empty, ar_no_identifier] ) - results = sqlite_instance.get_attack_results(converter_classes=[]) + results = sqlite_instance.get_attack_results(converter_types=[]) conv_ids = {r.conversation_id for r in results} # Should include attacks with no converters (None key, empty array, or empty identifier) assert "conv_1" not in conv_ids, "Should not include attacks that have converters" @@ -1096,130 +1220,130 @@ def test_get_attack_results_converter_classes_empty_matches_no_converters(sqlite assert "conv_4" in conv_ids, "Should include attacks with empty attack_identifier" -def test_get_attack_results_converter_classes_single_match(sqlite_instance: MemoryInterface): - """Test that converter_classes with one class returns attacks using that converter.""" +def test_get_attack_results_converter_types_single_match(sqlite_instance: MemoryInterface): + """Test that converter_types with one type returns attacks using that converter.""" ar1 = _make_attack_result_with_identifier("conv_1", "Attack", ["Base64Converter"]) ar2 = _make_attack_result_with_identifier("conv_2", "Attack", ["ROT13Converter"]) ar3 = _make_attack_result_with_identifier("conv_3", "Attack", ["Base64Converter", "ROT13Converter"]) sqlite_instance.add_attack_results_to_memory(attack_results=[ar1, ar2, ar3]) - results = sqlite_instance.get_attack_results(converter_classes=["Base64Converter"]) + results = sqlite_instance.get_attack_results(converter_types=["Base64Converter"]) conv_ids = {r.conversation_id for r in results} assert conv_ids == {"conv_1", "conv_3"} -def test_get_attack_results_converter_classes_and_logic(sqlite_instance: MemoryInterface): - """Test that multiple converter_classes use AND logic — all must be present.""" +def test_get_attack_results_converter_types_and_logic(sqlite_instance: MemoryInterface): + """Test that multiple converter_types use AND logic — all must be present.""" ar1 = _make_attack_result_with_identifier("conv_1", "Attack", ["Base64Converter"]) ar2 = _make_attack_result_with_identifier("conv_2", "Attack", ["ROT13Converter"]) ar3 = _make_attack_result_with_identifier("conv_3", "Attack", ["Base64Converter", "ROT13Converter"]) ar4 = _make_attack_result_with_identifier("conv_4", "Attack", ["Base64Converter", "ROT13Converter", "UrlConverter"]) sqlite_instance.add_attack_results_to_memory(attack_results=[ar1, ar2, ar3, ar4]) - results = sqlite_instance.get_attack_results(converter_classes=["Base64Converter", "ROT13Converter"]) + results = sqlite_instance.get_attack_results(converter_types=["Base64Converter", "ROT13Converter"]) conv_ids = {r.conversation_id for r in results} # conv_3 and conv_4 have both; conv_1 and conv_2 have only one assert conv_ids == {"conv_3", "conv_4"} -def test_get_attack_results_converter_classes_case_insensitive(sqlite_instance: MemoryInterface): - """Test that converter class matching is case-insensitive.""" +def test_get_attack_results_converter_types_case_insensitive(sqlite_instance: MemoryInterface): + """Test that converter type matching is case-insensitive.""" ar1 = _make_attack_result_with_identifier("conv_1", "Attack", ["Base64Converter"]) sqlite_instance.add_attack_results_to_memory(attack_results=[ar1]) - results = sqlite_instance.get_attack_results(converter_classes=["base64converter"]) + results = sqlite_instance.get_attack_results(converter_types=["base64converter"]) assert len(results) == 1 assert results[0].conversation_id == "conv_1" -def test_get_attack_results_converter_classes_no_match(sqlite_instance: MemoryInterface): - """Test that converter_classes filter returns empty when no attack has the converter.""" +def test_get_attack_results_converter_types_no_match(sqlite_instance: MemoryInterface): + """Test that converter_types filter returns empty when no attack has the converter.""" ar1 = _make_attack_result_with_identifier("conv_1", "Attack", ["Base64Converter"]) sqlite_instance.add_attack_results_to_memory(attack_results=[ar1]) - results = sqlite_instance.get_attack_results(converter_classes=["NonExistentConverter"]) + results = sqlite_instance.get_attack_results(converter_types=["NonExistentConverter"]) assert len(results) == 0 -def test_get_attack_results_attack_class_and_converter_classes_combined(sqlite_instance: MemoryInterface): - """Test combining attack_class and converter_classes filters.""" +def test_get_attack_results_attack_type_and_converter_types_combined(sqlite_instance: MemoryInterface): + """Test combining attack_type and converter_types filters.""" ar1 = _make_attack_result_with_identifier("conv_1", "CrescendoAttack", ["Base64Converter"]) ar2 = _make_attack_result_with_identifier("conv_2", "ManualAttack", ["Base64Converter"]) ar3 = _make_attack_result_with_identifier("conv_3", "CrescendoAttack", ["ROT13Converter"]) ar4 = _make_attack_result_with_identifier("conv_4", "CrescendoAttack") # No converters sqlite_instance.add_attack_results_to_memory(attack_results=[ar1, ar2, ar3, ar4]) - results = sqlite_instance.get_attack_results(attack_class="CrescendoAttack", converter_classes=["Base64Converter"]) + results = sqlite_instance.get_attack_results(attack_type="CrescendoAttack", converter_types=["Base64Converter"]) assert len(results) == 1 assert results[0].conversation_id == "conv_1" -def test_get_attack_results_attack_class_with_no_converters(sqlite_instance: MemoryInterface): - """Test combining attack_class with converter_classes=[] (no converters).""" +def test_get_attack_results_attack_type_with_no_converters(sqlite_instance: MemoryInterface): + """Test combining attack_type with converter_types=[] (no converters).""" ar1 = _make_attack_result_with_identifier("conv_1", "CrescendoAttack", ["Base64Converter"]) ar2 = _make_attack_result_with_identifier("conv_2", "CrescendoAttack") # No converters ar3 = _make_attack_result_with_identifier("conv_3", "ManualAttack") # No converters sqlite_instance.add_attack_results_to_memory(attack_results=[ar1, ar2, ar3]) - results = sqlite_instance.get_attack_results(attack_class="CrescendoAttack", converter_classes=[]) + results = sqlite_instance.get_attack_results(attack_type="CrescendoAttack", converter_types=[]) assert len(results) == 1 assert results[0].conversation_id == "conv_2" # ============================================================================ -# Unique attack class and converter class name tests +# Unique attack type and converter type name tests # ============================================================================ -def test_get_unique_attack_class_names_empty(sqlite_instance: MemoryInterface): +def test_get_unique_attack_type_names_empty(sqlite_instance: MemoryInterface): """Test that no attacks returns empty list.""" - result = sqlite_instance.get_unique_attack_class_names() + result = sqlite_instance.get_unique_attack_type_names() assert result == [] -def test_get_unique_attack_class_names_sorted_unique(sqlite_instance: MemoryInterface): - """Test that unique class names are returned sorted, with duplicates removed.""" +def test_get_unique_attack_type_names_sorted_unique(sqlite_instance: MemoryInterface): + """Test that unique type names are returned sorted, with duplicates removed.""" ar1 = _make_attack_result_with_identifier("conv_1", "CrescendoAttack") ar2 = _make_attack_result_with_identifier("conv_2", "ManualAttack") ar3 = _make_attack_result_with_identifier("conv_3", "CrescendoAttack") sqlite_instance.add_attack_results_to_memory(attack_results=[ar1, ar2, ar3]) - result = sqlite_instance.get_unique_attack_class_names() + result = sqlite_instance.get_unique_attack_type_names() assert result == ["CrescendoAttack", "ManualAttack"] -def test_get_unique_attack_class_names_skips_empty_identifier(sqlite_instance: MemoryInterface): +def test_get_unique_attack_type_names_skips_empty_identifier(sqlite_instance: MemoryInterface): """Test that attacks with empty attack_identifier (no class_name) are excluded.""" ar_no_id = create_attack_result("conv_1", 1) # No attack_identifier → stored as {} ar_with_id = _make_attack_result_with_identifier("conv_2", "CrescendoAttack") sqlite_instance.add_attack_results_to_memory(attack_results=[ar_no_id, ar_with_id]) - result = sqlite_instance.get_unique_attack_class_names() + result = sqlite_instance.get_unique_attack_type_names() assert result == ["CrescendoAttack"] -def test_get_unique_converter_class_names_empty(sqlite_instance: MemoryInterface): +def test_get_unique_converter_type_names_empty(sqlite_instance: MemoryInterface): """Test that no attacks returns empty list.""" - result = sqlite_instance.get_unique_converter_class_names() + result = sqlite_instance.get_unique_converter_type_names() assert result == [] -def test_get_unique_converter_class_names_sorted_unique(sqlite_instance: MemoryInterface): - """Test that unique converter class names are returned sorted, with duplicates removed.""" +def test_get_unique_converter_type_names_sorted_unique(sqlite_instance: MemoryInterface): + """Test that unique converter type names are returned sorted, with duplicates removed.""" ar1 = _make_attack_result_with_identifier("conv_1", "Attack", ["Base64Converter", "ROT13Converter"]) ar2 = _make_attack_result_with_identifier("conv_2", "Attack", ["Base64Converter"]) sqlite_instance.add_attack_results_to_memory(attack_results=[ar1, ar2]) - result = sqlite_instance.get_unique_converter_class_names() + result = sqlite_instance.get_unique_converter_type_names() assert result == ["Base64Converter", "ROT13Converter"] -def test_get_unique_converter_class_names_skips_no_converters(sqlite_instance: MemoryInterface): +def test_get_unique_converter_type_names_skips_no_converters(sqlite_instance: MemoryInterface): """Test that attacks with no converters don't contribute names.""" ar_no_conv = _make_attack_result_with_identifier("conv_1", "Attack") # No converters ar_with_conv = _make_attack_result_with_identifier("conv_2", "Attack", ["Base64Converter"]) ar_empty_id = create_attack_result("conv_3", 3) # Empty attack_identifier sqlite_instance.add_attack_results_to_memory(attack_results=[ar_no_conv, ar_with_conv, ar_empty_id]) - result = sqlite_instance.get_unique_converter_class_names() + result = sqlite_instance.get_unique_converter_type_names() assert result == ["Base64Converter"] diff --git a/tests/unit/memory/test_sqlite_memory.py b/tests/unit/memory/test_sqlite_memory.py index f99b725258..de404d2336 100644 --- a/tests/unit/memory/test_sqlite_memory.py +++ b/tests/unit/memory/test_sqlite_memory.py @@ -547,3 +547,123 @@ def test_update_prompt_metadata_by_conversation_id(sqlite_instance, sample_conve # Verify that the entry with a different conversation_id was not updated other_entry = session.query(PromptMemoryEntry).filter_by(conversation_id="other_id").first() assert other_entry.prompt_metadata == original_metadata # Metadata should remain unchanged + + +def test_get_conversation_stats_returns_empty_for_no_ids(sqlite_instance): + """Test that get_conversation_stats returns empty dict for empty input.""" + result = sqlite_instance.get_conversation_stats(conversation_ids=[]) + assert result == {} + + +def test_get_conversation_stats_returns_empty_for_unknown_ids(sqlite_instance): + """Test that get_conversation_stats omits unknown conversation IDs.""" + result = sqlite_instance.get_conversation_stats(conversation_ids=["nonexistent"]) + assert result == {} + + +def test_get_conversation_stats_counts_distinct_sequences(sqlite_instance, sample_conversation_entries): + """Test that message_count reflects distinct sequence numbers, not raw rows.""" + # Extract conversation IDs and sequences before inserting (entries get detached after commit) + from pyrit.models import Message + from unit.mocks import get_sample_conversations + + conversations = get_sample_conversations() + pieces = Message.flatten_to_message_pieces(conversations) + expected: dict[str, set[int]] = {} + for p in pieces: + expected.setdefault(p.conversation_id, set()).add(p.sequence) + + sqlite_instance._insert_entries(entries=sample_conversation_entries) + + conv_ids = list(expected.keys()) + result = sqlite_instance.get_conversation_stats(conversation_ids=conv_ids) + + for conv_id in conv_ids: + if conv_id in result: + assert result[conv_id].message_count == len(expected[conv_id]), ( + f"Conv {conv_id}: expected {len(expected[conv_id])}, got {result[conv_id].message_count}" + ) + + +def test_get_conversation_stats_returns_labels(sqlite_instance): + """Test that labels from the first piece with non-empty labels are returned.""" + import uuid + + from pyrit.models import MessagePiece + + conv_id = str(uuid.uuid4()) + piece = MessagePiece( + role="user", + original_value="hello", + original_value_data_type="text", + converted_value="hello", + converted_value_data_type="text", + conversation_id=conv_id, + sequence=0, + labels={"env": "prod", "source": "gui"}, + ) + entry = PromptMemoryEntry(entry=piece) + sqlite_instance._insert_entry(entry) + + result = sqlite_instance.get_conversation_stats(conversation_ids=[conv_id]) + assert conv_id in result + assert result[conv_id].labels == {"env": "prod", "source": "gui"} + + +def test_get_conversation_stats_preview_truncates(sqlite_instance): + """Test that last_message_preview is truncated to 100 chars + ellipsis.""" + import uuid + + from pyrit.models import MessagePiece + + conv_id = str(uuid.uuid4()) + long_text = "x" * 200 + piece = MessagePiece( + role="assistant", + original_value=long_text, + original_value_data_type="text", + converted_value=long_text, + converted_value_data_type="text", + conversation_id=conv_id, + sequence=0, + ) + entry = PromptMemoryEntry(entry=piece) + sqlite_instance._insert_entry(entry) + + result = sqlite_instance.get_conversation_stats(conversation_ids=[conv_id]) + assert conv_id in result + preview = result[conv_id].last_message_preview + assert preview is not None + assert len(preview) == 103 # 100 chars + "..." + assert preview.endswith("...") + + +def test_get_conversation_stats_batches_multiple_conversations(sqlite_instance): + """Test that a single call returns stats for multiple conversations.""" + import uuid + + from pyrit.models import MessagePiece + + conv_ids = [str(uuid.uuid4()) for _ in range(3)] + entries = [] + for i, cid in enumerate(conv_ids): + for seq in range(i + 1): # conv 0: 1 msg, conv 1: 2 msgs, conv 2: 3 msgs + piece = MessagePiece( + role="user", + original_value=f"msg-{seq}", + original_value_data_type="text", + converted_value=f"msg-{seq}", + converted_value_data_type="text", + conversation_id=cid, + sequence=seq, + ) + entries.append(PromptMemoryEntry(entry=piece)) + + sqlite_instance._insert_entries(entries=entries) + + result = sqlite_instance.get_conversation_stats(conversation_ids=conv_ids) + + assert len(result) == 3 + assert result[conv_ids[0]].message_count == 1 + assert result[conv_ids[1]].message_count == 2 + assert result[conv_ids[2]].message_count == 3 diff --git a/tests/unit/target/test_image_target.py b/tests/unit/target/test_image_target.py index ffba3a7564..4c5056e247 100644 --- a/tests/unit/target/test_image_target.py +++ b/tests/unit/target/test_image_target.py @@ -504,3 +504,21 @@ async def test_validate_piece_type(image_target: OpenAIImageTarget): finally: if os.path.isfile(audio_piece.original_value): os.remove(audio_piece.original_value) + + +@pytest.mark.asyncio +async def test_validate_previous_conversations( + image_target: OpenAIImageTarget, sample_conversations: MutableSequence[MessagePiece] +): + message_piece = sample_conversations[0] + + mock_memory = MagicMock() + mock_memory.get_conversation.return_value = sample_conversations + mock_memory.add_message_to_memory = AsyncMock() + + image_target._memory = mock_memory + + request = Message(message_pieces=[message_piece]) + + with pytest.raises(ValueError, match="This target only supports a single turn conversation."): + await image_target.send_prompt_async(message=request) diff --git a/tests/unit/target/test_video_target.py b/tests/unit/target/test_video_target.py index eab0d81ac4..877bce7d61 100644 --- a/tests/unit/target/test_video_target.py +++ b/tests/unit/target/test_video_target.py @@ -910,3 +910,20 @@ def test_supported_durations(self, video_target: OpenAIVideoTarget): n_seconds=duration, ) assert target._n_seconds == duration + + +def test_video_validate_previous_conversations( + video_target: OpenAIVideoTarget, sample_conversations: MutableSequence[MessagePiece] +): + message_piece = sample_conversations[0] + + mock_memory = MagicMock() + mock_memory.get_conversation.return_value = sample_conversations + mock_memory.add_message_to_memory = AsyncMock() + + video_target._memory = mock_memory + + request = Message(message_pieces=[message_piece]) + + with pytest.raises(ValueError, match="This target only supports a single turn conversation."): + video_target._validate_request(message=request) From 3cfc6054b58a5638d46767b2a37d1f9637a40eae Mon Sep 17 00:00:00 2001 From: Roman Lutz Date: Sat, 28 Feb 2026 14:54:34 +0000 Subject: [PATCH 3/7] Add attack-centric backend API with conversations and streaming - Add attack CRUD routes with conversation management - Add message sending with target dispatch and response handling - Add attack mappers for domain-to-DTO conversion with signed blob URLs - Add attack service with video remix support and piece persistence - Expand target service and routes with registry-based target management - Add version endpoint with database info Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- pyrit/backend/main.py | 25 +- pyrit/backend/mappers/__init__.py | 4 +- pyrit/backend/mappers/attack_mappers.py | 364 ++++++- pyrit/backend/mappers/target_mappers.py | 9 +- pyrit/backend/models/__init__.py | 6 +- pyrit/backend/models/attacks.py | 162 ++- pyrit/backend/models/targets.py | 11 +- pyrit/backend/routes/attacks.py | 202 +++- pyrit/backend/routes/targets.py | 12 +- pyrit/backend/routes/version.py | 23 +- pyrit/backend/services/attack_service.py | 711 ++++++++++-- pyrit/backend/services/target_service.py | 30 +- tests/unit/backend/test_api_routes.py | 214 +++- tests/unit/backend/test_attack_service.py | 1205 +++++++++++++++++++-- tests/unit/backend/test_main.py | 25 +- tests/unit/backend/test_mappers.py | 524 +++++++-- tests/unit/backend/test_target_service.py | 20 +- 17 files changed, 3085 insertions(+), 462 deletions(-) diff --git a/pyrit/backend/main.py b/pyrit/backend/main.py index f346a3e7d6..328937fd74 100644 --- a/pyrit/backend/main.py +++ b/pyrit/backend/main.py @@ -5,6 +5,7 @@ FastAPI application entry point for PyRIT backend. """ +import logging import os from collections.abc import AsyncGenerator from contextlib import asynccontextmanager @@ -18,21 +19,27 @@ from pyrit.backend.middleware import register_error_handlers from pyrit.backend.routes import attacks, converters, health, labels, targets, version from pyrit.memory import CentralMemory -from pyrit.setup.initialization import initialize_pyrit_async # Check for development mode from environment variable DEV_MODE = os.getenv("PYRIT_DEV_MODE", "false").lower() == "true" +logger = logging.getLogger(__name__) + @asynccontextmanager async def lifespan(app: FastAPI) -> AsyncGenerator[None, None]: """Manage application startup and shutdown lifecycle.""" - # When launched via pyrit_backend CLI, initialization is already done. - # Only initialize here for standalone uvicorn usage (e.g. uvicorn pyrit.backend.main:app). - if not CentralMemory._memory_instance: - await initialize_pyrit_async(memory_db_type="SQLite") + # Initialization is handled by the pyrit_backend CLI before uvicorn starts. + # Running 'uvicorn pyrit.backend.main:app' directly is not supported; + # use 'pyrit_backend' instead. + try: + CentralMemory.get_memory_instance() + except ValueError: + logger.warning( + "CentralMemory is not initialized. " + "Start the server via 'pyrit_backend' CLI instead of running uvicorn directly." + ) yield - # Shutdown: nothing to clean up currently app = FastAPI( @@ -91,9 +98,3 @@ def setup_frontend() -> None: # Set up frontend at module load time (needed when running via uvicorn) setup_frontend() - - -if __name__ == "__main__": - import uvicorn - - uvicorn.run(app, host="0.0.0.0", port=8000, log_level="info") diff --git a/pyrit/backend/mappers/__init__.py b/pyrit/backend/mappers/__init__.py index 63577e6efc..55c8b2af83 100644 --- a/pyrit/backend/mappers/__init__.py +++ b/pyrit/backend/mappers/__init__.py @@ -10,7 +10,7 @@ from pyrit.backend.mappers.attack_mappers import ( attack_result_to_summary, - pyrit_messages_to_dto, + pyrit_messages_to_dto_async, pyrit_scores_to_dto, request_piece_to_pyrit_message_piece, request_to_pyrit_message, @@ -25,7 +25,7 @@ __all__ = [ "attack_result_to_summary", "converter_object_to_instance", - "pyrit_messages_to_dto", + "pyrit_messages_to_dto_async", "pyrit_scores_to_dto", "request_piece_to_pyrit_message_piece", "request_to_pyrit_message", diff --git a/pyrit/backend/mappers/attack_mappers.py b/pyrit/backend/mappers/attack_mappers.py index c9c8dc7af2..fcb9a1ccf7 100644 --- a/pyrit/backend/mappers/attack_mappers.py +++ b/pyrit/backend/mappers/attack_mappers.py @@ -6,14 +6,26 @@ """ Attack mappers – domain ↔ DTO translation for attack-related models. -All functions are pure (no database or service calls) so they are easy to test. -The one exception is `attack_result_to_summary` which receives pre-fetched pieces. +Most functions are pure (no database or service calls). The exceptions are +``pyrit_messages_to_dto_async`` which fetches Azure Blob Storage content +and converts it to data URIs, and ``attack_result_to_summary`` which +receives pre-fetched pieces. """ +import base64 +import logging import mimetypes +import os +import time import uuid -from datetime import datetime, timezone -from typing import TYPE_CHECKING, Optional, cast +from datetime import datetime, timedelta, timezone +from typing import TYPE_CHECKING, Dict, List, Optional, Sequence, Tuple, cast +from urllib.parse import urlparse + +import httpx +from azure.identity.aio import DefaultAzureCredential +from azure.storage.blob import ContainerSasPermissions, generate_container_sas +from azure.storage.blob.aio import BlobServiceClient from pyrit.backend.models.attacks import ( AddMessageRequest, @@ -22,11 +34,15 @@ MessagePiece, MessagePieceRequest, Score, + TargetInfo, ) from pyrit.models import AttackResult, ChatMessageRole, PromptDataType from pyrit.models import Message as PyritMessage from pyrit.models import MessagePiece as PyritMessagePiece from pyrit.models import Score as PyritScore +from pyrit.models.conversation_stats import ConversationStats + +logger = logging.getLogger(__name__) if TYPE_CHECKING: from collections.abc import Sequence @@ -35,27 +51,189 @@ # Domain → DTO (for API responses) # ============================================================================ +# Media data types whose values are local file paths that need base64 encoding +_MEDIA_PATH_TYPES = frozenset({"image_path", "audio_path", "video_path", "binary_path"}) + +# Media types that are too large for base64 data URIs and should use signed URLs instead. +_STREAMING_PATH_TYPES = frozenset({"video_path"}) + +# --------------------------------------------------------------------------- +# Azure Blob SAS token cache +# --------------------------------------------------------------------------- +# Container URL -> (sas_token_query_string, expiry_epoch) +_sas_token_cache: Dict[str, Tuple[str, float]] = {} +_SAS_TTL_SECONDS = 3500 # cache for ~58 min; tokens are valid for 1 hour + + +def _is_azure_blob_url(value: str) -> bool: + """Return True if *value* looks like an Azure Blob Storage URL.""" + return value.startswith("https://") and ".blob.core.windows.net/" in value + + +async def _get_sas_for_container_async(*, container_url: str) -> str: + """ + Return a read-only SAS query string for *container_url*, generating and + caching one when necessary. + + The SAS token is cached per container URL and reused for ~1 hour. + + Args: + container_url: The full URL of the Azure Blob Storage container + (e.g. ``https://account.blob.core.windows.net/container``). + + Returns: + A SAS query string (without the leading ``?``). + """ + now = time.time() + cached = _sas_token_cache.get(container_url) + if cached and cached[1] > now: + return cached[0] + + parsed = urlparse(container_url) + account_url = f"{parsed.scheme}://{parsed.netloc}" + container_name = parsed.path.strip("/") + storage_account_name = parsed.netloc.split(".")[0] + + start_time = datetime.now() - timedelta(minutes=5) + expiry_time = start_time + timedelta(hours=1) + + credential = DefaultAzureCredential() + try: + async with BlobServiceClient(account_url=account_url, credential=credential) as bsc: + delegation_key = await bsc.get_user_delegation_key( + key_start_time=start_time, + key_expiry_time=expiry_time, + ) + sas_token: str = generate_container_sas( # type: ignore[assignment] + account_name=storage_account_name, + container_name=container_name, + user_delegation_key=delegation_key, + permission=ContainerSasPermissions(read=True), # type: ignore[no-untyped-call, unused-ignore] + expiry=expiry_time, + start=start_time, + ) + finally: + await credential.close() + + _sas_token_cache[container_url] = (sas_token, now + _SAS_TTL_SECONDS) + return sas_token + + +async def _sign_blob_url_async(*, blob_url: str) -> str: + """ + Append a read-only SAS token to an Azure Blob Storage URL. + + Non-blob URLs (local paths, data URIs, etc.) are returned unchanged. + + Args: + blob_url: The raw Azure Blob Storage URL. + + Returns: + The URL with an appended SAS query string, or the original value for + non-blob URLs. + """ + if not _is_azure_blob_url(blob_url): + return blob_url + + parsed = urlparse(blob_url) + # Already signed + if parsed.query: + return blob_url + + # Extract container name from path: /container/path/to/blob + parts = parsed.path.strip("/").split("/", 1) + if not parts: + return blob_url + + container_name = parts[0] + container_url = f"{parsed.scheme}://{parsed.netloc}/{container_name}" + + try: + sas = await _get_sas_for_container_async(container_url=container_url) + return f"{blob_url}?{sas}" + except Exception: + logger.warning("Failed to generate SAS token for %s; returning unsigned URL", blob_url, exc_info=True) + return blob_url + + +async def _fetch_blob_as_data_uri_async(*, blob_url: str) -> str: + """ + Fetch an Azure Blob Storage file and return it as a ``data:`` URI. + + The blob URL is first signed with a SAS token, then fetched server-side. + The content is base64-encoded into a data URI so the frontend receives the + same format regardless of whether storage is local or remote. + + Falls back to the raw (unsigned) URL if signing or fetching fails. + + Args: + blob_url: The raw Azure Blob Storage URL. + + Returns: + A ``data:;base64,...`` string, or the original URL on failure. + """ + signed_url = await _sign_blob_url_async(blob_url=blob_url) + + try: + async with httpx.AsyncClient() as client: + resp = await client.get(signed_url, follow_redirects=True, timeout=60.0) + resp.raise_for_status() + except Exception: + logger.warning("Failed to fetch blob %s; returning raw URL", blob_url, exc_info=True) + return blob_url + + content_type = resp.headers.get("content-type", "application/octet-stream") + encoded = base64.b64encode(resp.content).decode("ascii") + return f"data:{content_type};base64,{encoded}" + + +def _encode_media_value(*, value: Optional[str], data_type: str) -> Optional[str]: + """ + Return the value as-is for text, or base64-encode the referenced file for media types. + + If the file cannot be read (missing, permissions, etc.) the original value is + returned so the frontend can still display *something*. + + Returns: + The original value for text types, a ``data:`` URI for readable media files, + or the raw value when the file is inaccessible. + """ + if not value or data_type not in _MEDIA_PATH_TYPES: + return value + # Already a data-URI — no need to re-encode + if value.startswith("data:"): + return value + # Looks like a local file path — read & encode + if os.path.isfile(value): + try: + mime, _ = mimetypes.guess_type(value) + mime = mime or "application/octet-stream" + with open(value, "rb") as f: + encoded = base64.b64encode(f.read()).decode("ascii") + return f"data:{mime};base64,{encoded}" + except Exception: + logger.warning("Failed to read media file %s; returning raw path", value, exc_info=True) + return value + def attack_result_to_summary( ar: AttackResult, *, - pieces: Sequence[PyritMessagePiece], + stats: ConversationStats, ) -> AttackSummary: """ - Build an AttackSummary DTO from an AttackResult and its message pieces. - - Extracts only the frontend-relevant fields from the internal identifiers, - avoiding leakage of internal PyRIT core structures. + Build an AttackSummary DTO from an AttackResult. Args: ar: The domain AttackResult. - pieces: Pre-fetched message pieces for this conversation. + stats: Pre-aggregated conversation stats (from ``get_conversation_stats``). Returns: AttackSummary DTO ready for the API response. """ - message_count = len({p.sequence for p in pieces}) - last_preview = _get_preview_from_pieces(pieces) + message_count = stats.message_count + last_preview = stats.last_message_preview + labels = dict(stats.labels) if stats.labels else {} created_str = ar.metadata.get("created_at") updated_str = ar.metadata.get("updated_at") @@ -68,17 +246,28 @@ def attack_result_to_summary( target_id = aid.get_child("objective_target") if aid else None converter_ids = aid.get_child_list("request_converters") if aid else [] + target_info = ( + TargetInfo( + target_type=target_id.class_name, + endpoint=target_id.params.get("endpoint") or None, + model_name=target_id.params.get("model_name") or None, + ) + if target_id + else None + ) + return AttackSummary( + attack_result_id=ar.attack_result_id or "", conversation_id=ar.conversation_id, attack_type=aid.class_name if aid else "Unknown", attack_specific_params=aid.params or None if aid else None, - target_unique_name=target_id.unique_name if target_id else None, - target_type=target_id.class_name if target_id else None, + target=target_info, converters=[c.class_name for c in converter_ids] if converter_ids else [], outcome=ar.outcome.value, last_message_preview=last_preview, message_count=message_count, - labels=_collect_labels_from_pieces(pieces), + related_conversation_ids=[ref.conversation_id for ref in ar.related_conversations], + labels=labels, created_at=created_at, updated_at=updated_at, ) @@ -91,16 +280,25 @@ def pyrit_scores_to_dto(scores: list[PyritScore]) -> list[Score]: Returns: List of Score DTOs for the API. """ - return [ - Score( - score_id=str(s.id), - scorer_type=s.scorer_class_identifier.class_name, - score_value=float(s.score_value), - score_rationale=s.score_rationale, - scored_at=s.timestamp, + mapped_scores: List[Score] = [] + for score in scores: + try: + score_value = float(score.score_value) + except (TypeError, ValueError): + logger.warning("Skipping score %s with non-numeric score_value=%r", score.id, score.score_value) + continue + + mapped_scores.append( + Score( + score_id=str(score.id), + scorer_type=score.scorer_class_identifier.class_name, + score_value=score_value, + score_rationale=score.score_rationale, + scored_at=score.timestamp, + ) ) - for s in scores - ] + + return mapped_scores def _infer_mime_type(*, value: Optional[str], data_type: PromptDataType) -> Optional[str]: @@ -124,33 +322,114 @@ def _infer_mime_type(*, value: Optional[str], data_type: PromptDataType) -> Opti return mime_type -def pyrit_messages_to_dto(pyrit_messages: list[PyritMessage]) -> list[Message]: +def _build_filename( + *, + data_type: str, + sha256: Optional[str], + value: Optional[str], +) -> Optional[str]: + """ + Build a human-readable download filename from the data type and hash. + + Produces names like ``image_a1b2c3d4.png`` or ``audio_e5f6g7h8.wav``. + The hash is truncated to 8 characters for readability. + + Falls back to the file extension from *value* (path or URL) when the + MIME type cannot be determined from the data type alone. + + Returns ``None`` for text-like types that don't need a download filename. + + Args: + data_type: The prompt data type (e.g. ``image_path``, ``audio_path``). + sha256: The SHA256 hash of the content, if available. + value: The original value (path or URL) used to infer file extension. + """ + # Map data types to friendly prefixes + _PREFIX_MAP = { + "image_path": "image", + "audio_path": "audio", + "video_path": "video", + "binary_path": "file", + } + prefix = _PREFIX_MAP.get(data_type) + if not prefix: + return None + + short_hash = sha256[:8] if sha256 else uuid.uuid4().hex[:8] + + # Derive extension from the value (file path or URL) + ext = "" + if value and not value.startswith("data:"): + source = value + if source.startswith("http"): + source = urlparse(source).path + ext = os.path.splitext(source)[1] # e.g. ".png" + + if not ext: + # Fallback: guess from mime type based on data type prefix + _DEFAULT_EXT = {"image": ".png", "audio": ".wav", "video": ".mp4", "file": ".bin"} + ext = _DEFAULT_EXT.get(prefix, ".bin") + + return f"{prefix}_{short_hash}{ext}" + + +async def pyrit_messages_to_dto_async(pyrit_messages: List[PyritMessage]) -> List[Message]: """ Translate PyRIT messages to backend Message DTOs. + Local media files are base64-encoded into data URIs. Azure Blob Storage + files are fetched server-side and converted to data URIs so the frontend + receives the same format regardless of storage backend. + Returns: List of Message DTOs for the API. """ messages = [] for msg in pyrit_messages: - pieces = [ - MessagePiece( - piece_id=str(p.id), - original_value_data_type=p.original_value_data_type or "text", - converted_value_data_type=p.converted_value_data_type or "text", - original_value=p.original_value, - original_value_mime_type=_infer_mime_type( - value=p.original_value, data_type=p.original_value_data_type or "text" - ), - converted_value=p.converted_value or "", - converted_value_mime_type=_infer_mime_type( - value=p.converted_value, data_type=p.converted_value_data_type or "text" - ), - scores=pyrit_scores_to_dto(p.scores) if p.scores else [], - response_error=p.response_error or "none", + pieces = [] + for p in msg.message_pieces: + orig_dtype = p.original_value_data_type or "text" + conv_dtype = p.converted_value_data_type or "text" + + orig_val = _encode_media_value(value=p.original_value, data_type=orig_dtype) + conv_val = _encode_media_value(value=p.converted_value or "", data_type=conv_dtype) or "" + + # For streaming types (video), pass a signed URL directly instead of + # downloading and base64-encoding the entire file. + if orig_val and _is_azure_blob_url(orig_val): + if orig_dtype in _STREAMING_PATH_TYPES: + orig_val = await _sign_blob_url_async(blob_url=orig_val) + else: + orig_val = await _fetch_blob_as_data_uri_async(blob_url=orig_val) + if conv_val and _is_azure_blob_url(conv_val): + if conv_dtype in _STREAMING_PATH_TYPES: + conv_val = await _sign_blob_url_async(blob_url=conv_val) + else: + conv_val = await _fetch_blob_as_data_uri_async(blob_url=conv_val) + + pieces.append( + MessagePiece( + piece_id=str(p.id), + original_value_data_type=orig_dtype, + converted_value_data_type=conv_dtype, + original_value=orig_val, + original_value_mime_type=_infer_mime_type(value=p.original_value, data_type=orig_dtype), + converted_value=conv_val, + converted_value_mime_type=_infer_mime_type(value=p.converted_value, data_type=conv_dtype), + scores=pyrit_scores_to_dto(p.scores) if p.scores else [], + response_error=p.response_error or "none", + original_filename=_build_filename( + data_type=orig_dtype, + sha256=p.original_value_sha256, + value=p.original_value, + ), + converted_filename=_build_filename( + data_type=conv_dtype, + sha256=p.converted_value_sha256, + value=p.converted_value, + ), + ) ) - for p in msg.message_pieces - ] first = msg.message_pieces[0] if msg.message_pieces else None messages.append( @@ -239,6 +518,7 @@ def request_to_pyrit_message( return PyritMessage(pieces) + # ============================================================================ # Private Helpers # ============================================================================ diff --git a/pyrit/backend/mappers/target_mappers.py b/pyrit/backend/mappers/target_mappers.py index 0aec13e6d1..5be6c3395c 100644 --- a/pyrit/backend/mappers/target_mappers.py +++ b/pyrit/backend/mappers/target_mappers.py @@ -6,10 +6,10 @@ """ from pyrit.backend.models.targets import TargetInstance -from pyrit.prompt_target import PromptTarget +from pyrit.prompt_target import PromptChatTarget, PromptTarget -def target_object_to_instance(target_unique_name: str, target_obj: PromptTarget) -> TargetInstance: +def target_object_to_instance(target_registry_name: str, target_obj: PromptTarget) -> TargetInstance: """ Build a TargetInstance DTO from a registry target object. @@ -17,7 +17,7 @@ def target_object_to_instance(target_unique_name: str, target_obj: PromptTarget) avoiding leakage of internal PyRIT core structures. Args: - target_unique_name: The unique target instance identifier (registry key / unique_name). + target_registry_name: The human-friendly target registry name. target_obj: The domain PromptTarget object from the registry. Returns: @@ -26,12 +26,13 @@ def target_object_to_instance(target_unique_name: str, target_obj: PromptTarget) identifier = target_obj.get_identifier() return TargetInstance( - target_unique_name=target_unique_name, + target_registry_name=target_registry_name, target_type=identifier.class_name, endpoint=identifier.params.get("endpoint") or None, model_name=identifier.params.get("model_name") or None, temperature=identifier.params.get("temperature"), top_p=identifier.params.get("top_p"), max_requests_per_minute=identifier.params.get("max_requests_per_minute"), + supports_multiturn_chat=isinstance(target_obj, PromptChatTarget), target_specific_params=identifier.params.get("target_specific_params"), ) diff --git a/pyrit/backend/models/__init__.py b/pyrit/backend/models/__init__.py index 8f1c79e0c7..326a45d6aa 100644 --- a/pyrit/backend/models/__init__.py +++ b/pyrit/backend/models/__init__.py @@ -11,16 +11,15 @@ AddMessageRequest, AddMessageResponse, AttackListResponse, - AttackMessagesResponse, AttackOptionsResponse, AttackSummary, + ConversationMessagesResponse, ConverterOptionsResponse, CreateAttackRequest, CreateAttackResponse, Message, MessagePiece, MessagePieceRequest, - PrependedMessageRequest, Score, UpdateAttackRequest, ) @@ -51,14 +50,13 @@ "AddMessageRequest", "AddMessageResponse", "AttackListResponse", - "AttackMessagesResponse", + "ConversationMessagesResponse", "AttackSummary", "CreateAttackRequest", "CreateAttackResponse", "Message", "MessagePiece", "MessagePieceRequest", - "PrependedMessageRequest", "Score", "UpdateAttackRequest", # Common diff --git a/pyrit/backend/models/attacks.py b/pyrit/backend/models/attacks.py index 9183d933cf..d14b878f1f 100644 --- a/pyrit/backend/models/attacks.py +++ b/pyrit/backend/models/attacks.py @@ -9,7 +9,7 @@ """ from datetime import datetime -from typing import Any, Literal, Optional +from typing import Any, Dict, List, Literal, Optional from pydantic import BaseModel, Field @@ -53,10 +53,16 @@ class MessagePiece(BaseModel): response_error_description: Optional[str] = Field( default=None, description="Description of the error if response_error is not 'none'" ) + original_filename: Optional[str] = Field( + default=None, description="Original filename extracted from file path or blob URL" + ) + converted_filename: Optional[str] = Field( + default=None, description="Converted filename extracted from file path or blob URL" + ) class Message(BaseModel): - """A message within an attack.""" + """A message within a conversation.""" turn_number: int = Field(..., description="Turn number in the conversation (1-indexed)") role: ChatMessageRole = Field(..., description="Message role") @@ -69,15 +75,23 @@ class Message(BaseModel): # ============================================================================ +class TargetInfo(BaseModel): + """Target information extracted from the stored TargetIdentifier.""" + + target_type: str = Field(..., description="Target class name (e.g., 'OpenAIChatTarget')") + endpoint: Optional[str] = Field(None, description="Target endpoint URL") + model_name: Optional[str] = Field(None, description="Model or deployment name") + + class AttackSummary(BaseModel): """Summary view of an attack (for list views, omits full message content).""" - conversation_id: str = Field(..., description="Unique attack identifier") + attack_result_id: str = Field(..., description="Database-assigned unique ID for this AttackResult") + conversation_id: str = Field(..., description="Primary conversation of this attack result") attack_type: str = Field(..., description="Attack class name (e.g., 'CrescendoAttack', 'ManualAttack')") - attack_specific_params: Optional[dict[str, Any]] = Field(None, description="Additional attack-specific parameters") - target_unique_name: Optional[str] = Field(None, description="Unique name of the objective target") - target_type: Optional[str] = Field(None, description="Target class name (e.g., 'OpenAIChatTarget')") - converters: list[str] = Field( + attack_specific_params: Optional[Dict[str, Any]] = Field(None, description="Additional attack-specific parameters") + target: Optional[TargetInfo] = Field(None, description="Target information from the stored identifier") + converters: List[str] = Field( default_factory=list, description="Request converter class names applied in this attack" ) outcome: Optional[Literal["undetermined", "success", "failure"]] = Field( @@ -87,21 +101,24 @@ class AttackSummary(BaseModel): None, description="Preview of the last message (truncated to ~100 chars)" ) message_count: int = Field(0, description="Total number of messages in the attack") - labels: dict[str, str] = Field(default_factory=dict, description="User-defined labels for filtering") + related_conversation_ids: List[str] = Field( + default_factory=list, description="IDs of related conversations within this attack" + ) + labels: Dict[str, str] = Field(default_factory=dict, description="User-defined labels for filtering") created_at: datetime = Field(..., description="Attack creation timestamp") updated_at: datetime = Field(..., description="Last update timestamp") # ============================================================================ -# Attack Messages Response +# Conversation Messages Response # ============================================================================ -class AttackMessagesResponse(BaseModel): - """Response containing all messages for an attack.""" +class ConversationMessagesResponse(BaseModel): + """Response containing all messages for a conversation.""" - conversation_id: str = Field(..., description="Attack identifier") - messages: list[Message] = Field(default_factory=list, description="All messages in order") + conversation_id: str = Field(..., description="Conversation identifier") + messages: List[Message] = Field(default_factory=list, description="All messages in order") # ============================================================================ @@ -117,26 +134,19 @@ class AttackListResponse(BaseModel): class AttackOptionsResponse(BaseModel): - """Response containing unique attack class names used across attacks.""" + """Response containing unique attack type names used across attacks.""" - attack_classes: list[str] = Field( - ..., description="Sorted list of unique attack class names found in attack results" - ) + attack_types: List[str] = Field(..., description="Sorted list of unique attack type names found in attack results") class ConverterOptionsResponse(BaseModel): - """Response containing unique converter class names used across attacks.""" + """Response containing unique converter type names used across attacks.""" - converter_classes: list[str] = Field( - ..., description="Sorted list of unique converter class names found in attack results" + converter_types: List[str] = Field( + ..., description="Sorted list of unique converter type names found in attack results" ) -# ============================================================================ -# Create Attack -# ============================================================================ - - # ============================================================================ # Message Input Models # ============================================================================ @@ -163,11 +173,29 @@ class PrependedMessageRequest(BaseModel): pieces: list[MessagePieceRequest] = Field(..., description="Message pieces (supports multimodal)", max_length=50) +# ============================================================================ +# Create Attack +# ============================================================================ + + class CreateAttackRequest(BaseModel): - """Request to create a new attack.""" + """Request to create a new attack. + + For branching from an existing conversation into a new attack, provide + ``source_conversation_id`` and ``cutoff_index``. The backend will + duplicate messages up to and including the cutoff turn, preserving + lineage via ``original_prompt_id``. The new attack gets the labels + supplied in ``labels`` (typically the current operator's labels). + """ name: Optional[str] = Field(None, description="Attack name/label") - target_unique_name: str = Field(..., description="Target instance ID to attack") + target_registry_name: str = Field(..., description="Target registry name to attack") + source_conversation_id: Optional[str] = Field( + None, description="Conversation to branch from (clone messages into the new attack)" + ) + cutoff_index: Optional[int] = Field( + None, description="Include messages up to and including this turn index (0-based)" + ) prepended_conversation: Optional[list[PrependedMessageRequest]] = Field( None, description="Messages to prepend (system prompts, branching context)", max_length=200 ) @@ -177,7 +205,8 @@ class CreateAttackRequest(BaseModel): class CreateAttackResponse(BaseModel): """Response after creating an attack.""" - conversation_id: str = Field(..., description="Unique attack identifier") + attack_result_id: str = Field(..., description="Database-assigned unique ID for the AttackResult") + conversation_id: str = Field(..., description="Unique conversation identifier") created_at: datetime = Field(..., description="Attack creation timestamp") @@ -192,6 +221,65 @@ class UpdateAttackRequest(BaseModel): outcome: Literal["undetermined", "success", "failure"] = Field(..., description="Updated attack outcome") +# ============================================================================ +# Related Conversations +# ============================================================================ + + +class ConversationSummary(BaseModel): + """Summary of a conversation (message count, preview, timestamp).""" + + conversation_id: str = Field(..., description="Unique conversation identifier") + message_count: int = Field(0, description="Number of messages in this conversation") + last_message_preview: Optional[str] = Field(None, description="Preview of the last message") + created_at: Optional[str] = Field(None, description="ISO timestamp of the first message") + + +class AttackConversationsResponse(BaseModel): + """Response listing all conversations belonging to an attack.""" + + attack_result_id: str = Field(..., description="The AttackResult ID") + main_conversation_id: str = Field(..., description="The attack's primary conversation_id") + conversations: List[ConversationSummary] = Field( + default_factory=list, description="All conversations including main" + ) + + +class CreateConversationRequest(BaseModel): + """ + Request to create a new conversation within an existing attack. + + For branching from an existing conversation, provide ``source_conversation_id`` + and ``cutoff_index``. The backend will duplicate messages up to and including + the cutoff turn, preserving tracking relationships (original_prompt_id). + """ + + source_conversation_id: Optional[str] = Field(None, description="Conversation to branch from") + cutoff_index: Optional[int] = Field( + None, description="Include messages up to and including this turn index (0-based)" + ) + + +class CreateConversationResponse(BaseModel): + """Response after creating a new related conversation.""" + + conversation_id: str = Field(..., description="New conversation identifier") + created_at: datetime = Field(..., description="Conversation creation timestamp") + + +class ChangeMainConversationRequest(BaseModel): + """Request to change the main conversation of an attack result.""" + + conversation_id: str = Field(..., description="The conversation to promote to main") + + +class ChangeMainConversationResponse(BaseModel): + """Response after changing the main conversation of an attack result.""" + + attack_result_id: str = Field(..., description="The AttackResult whose main conversation was swapped") + conversation_id: str = Field(..., description="The conversation that is now the main conversation") + + # ============================================================================ # Add Message # ============================================================================ @@ -212,9 +300,23 @@ class AddMessageRequest(BaseModel): default=True, description="If True, send to target and wait for response. If False, just store in memory.", ) - converter_ids: Optional[list[str]] = Field( + target_registry_name: Optional[str] = Field( + None, + description="Target registry name. Required when send=True so the backend knows which target to use.", + ) + converter_ids: Optional[List[str]] = Field( None, description="Converter instance IDs to apply (overrides attack-level)" ) + target_conversation_id: str = Field( + ..., + description="The conversation_id to store and send messages under. " + "Usually the attack's main conversation, but can be a related conversation.", + ) + labels: Optional[Dict[str, str]] = Field( + None, + description="Labels to stamp on every message piece. " + "Falls back to labels from existing pieces in the conversation.", + ) class AddMessageResponse(BaseModel): @@ -227,4 +329,4 @@ class AddMessageResponse(BaseModel): """ attack: AttackSummary = Field(..., description="Updated attack metadata") - messages: AttackMessagesResponse = Field(..., description="All messages including new one(s)") + messages: ConversationMessagesResponse = Field(..., description="All messages including new one(s)") diff --git a/pyrit/backend/models/targets.py b/pyrit/backend/models/targets.py index 36b5634680..d2d98fe931 100644 --- a/pyrit/backend/models/targets.py +++ b/pyrit/backend/models/targets.py @@ -11,7 +11,7 @@ This module defines the Instance models for runtime target management. """ -from typing import Any, Optional +from typing import Any, Dict, Optional from pydantic import BaseModel, Field @@ -26,16 +26,17 @@ class TargetInstance(BaseModel): Also used as the create-target response (same shape as GET). """ - target_unique_name: str = Field( - ..., description="Unique target instance identifier (ComponentIdentifier.unique_name)" - ) + target_registry_name: str = Field(..., description="Human-friendly target registry name") target_type: str = Field(..., description="Target class name (e.g., 'OpenAIChatTarget')") endpoint: Optional[str] = Field(None, description="Target endpoint URL") model_name: Optional[str] = Field(None, description="Model or deployment name") temperature: Optional[float] = Field(None, description="Temperature parameter for generation") top_p: Optional[float] = Field(None, description="Top-p parameter for generation") max_requests_per_minute: Optional[int] = Field(None, description="Maximum requests per minute") - target_specific_params: Optional[dict[str, Any]] = Field(None, description="Additional target-specific parameters") + supports_multiturn_chat: bool = Field( + True, description="Whether the target supports multi-turn conversation history" + ) + target_specific_params: Optional[Dict[str, Any]] = Field(None, description="Additional target-specific parameters") class TargetListResponse(BaseModel): diff --git a/pyrit/backend/routes/attacks.py b/pyrit/backend/routes/attacks.py index ed6fc4c029..60169576c1 100644 --- a/pyrit/backend/routes/attacks.py +++ b/pyrit/backend/routes/attacks.py @@ -8,6 +8,7 @@ This is the attack-centric API design. """ +import traceback from typing import Literal, Optional from fastapi import APIRouter, HTTPException, Query, status @@ -15,13 +16,18 @@ from pyrit.backend.models.attacks import ( AddMessageRequest, AddMessageResponse, + AttackConversationsResponse, AttackListResponse, - AttackMessagesResponse, AttackOptionsResponse, AttackSummary, + ChangeMainConversationRequest, + ChangeMainConversationResponse, + ConversationMessagesResponse, ConverterOptionsResponse, CreateAttackRequest, CreateAttackResponse, + CreateConversationRequest, + CreateConversationResponse, UpdateAttackRequest, ) from pyrit.backend.models.common import ProblemDetail @@ -52,17 +58,17 @@ def _parse_labels(label_params: Optional[list[str]]) -> Optional[dict[str, str]] response_model=AttackListResponse, ) async def list_attacks( - attack_class: Optional[str] = Query(None, description="Filter by exact attack class name"), - converter_classes: Optional[list[str]] = Query( + attack_type: Optional[str] = Query(None, description="Filter by exact attack type name"), + converter_types: Optional[list[str]] = Query( None, - description="Filter by converter class names (repeatable, AND logic). Pass empty to match no-converter attacks.", + description="Filter by converter type names (repeatable, AND logic). Pass empty to match no-converter attacks.", ), outcome: Optional[Literal["undetermined", "success", "failure"]] = Query(None, description="Filter by outcome"), label: Optional[list[str]] = Query(None, description="Filter by labels (format: key:value, repeatable)"), min_turns: Optional[int] = Query(None, ge=0, description="Filter by minimum executed turns"), max_turns: Optional[int] = Query(None, ge=0, description="Filter by maximum executed turns"), limit: int = Query(20, ge=1, le=100, description="Maximum items per page"), - cursor: Optional[str] = Query(None, description="Pagination cursor (conversation_id)"), + cursor: Optional[str] = Query(None, description="Pagination cursor (attack_result_id)"), ) -> AttackListResponse: """ List attacks with optional filtering and pagination. @@ -76,8 +82,8 @@ async def list_attacks( service = get_attack_service() labels = _parse_labels(label) return await service.list_attacks_async( - attack_class=attack_class, - converter_classes=converter_classes, + attack_type=attack_type, + converter_types=converter_types, outcome=outcome, labels=labels, min_turns=min_turns, @@ -93,17 +99,17 @@ async def list_attacks( ) async def get_attack_options() -> AttackOptionsResponse: """ - Get unique attack class names used across all attacks. + Get unique attack type names used across all attacks. - Returns all attack class names found in stored attack results. + Returns all attack type names found in stored attack results. Useful for populating attack type filter dropdowns in the GUI. Returns: - AttackOptionsResponse: Sorted list of unique attack class names. + AttackOptionsResponse: Sorted list of unique attack type names. """ service = get_attack_service() - class_names = await service.get_attack_options_async() - return AttackOptionsResponse(attack_classes=class_names) + type_names = await service.get_attack_options_async() + return AttackOptionsResponse(attack_types=type_names) @router.get( @@ -112,17 +118,17 @@ async def get_attack_options() -> AttackOptionsResponse: ) async def get_converter_options() -> ConverterOptionsResponse: """ - Get unique converter class names used across all attacks. + Get unique converter type names used across all attacks. - Returns all converter class names found in stored attack results. + Returns all converter type names found in stored attack results. Useful for populating converter filter dropdowns in the GUI. Returns: - ConverterOptionsResponse: Sorted list of unique converter class names. + ConverterOptionsResponse: Sorted list of unique converter type names. """ service = get_attack_service() - class_names = await service.get_converter_options_async() - return ConverterOptionsResponse(converter_classes=class_names) + type_names = await service.get_converter_options_async() + return ConverterOptionsResponse(converter_types=type_names) @router.post( @@ -140,7 +146,7 @@ async def create_attack(request: CreateAttackRequest) -> CreateAttackResponse: Create a new attack. Establishes a new attack session with the specified target. - Optionally include prepended_conversation for system prompts or branching context. + Optionally specify source_conversation_id and cutoff_index to branch from an existing conversation. Returns: CreateAttackResponse: The created attack details. @@ -157,13 +163,13 @@ async def create_attack(request: CreateAttackRequest) -> CreateAttackResponse: @router.get( - "/{conversation_id}", + "/{attack_result_id}", response_model=AttackSummary, responses={ 404: {"model": ProblemDetail, "description": "Attack not found"}, }, ) -async def get_attack(conversation_id: str) -> AttackSummary: +async def get_attack(attack_result_id: str) -> AttackSummary: """ Get attack details. @@ -174,25 +180,25 @@ async def get_attack(conversation_id: str) -> AttackSummary: """ service = get_attack_service() - attack = await service.get_attack_async(conversation_id=conversation_id) + attack = await service.get_attack_async(attack_result_id=attack_result_id) if not attack: raise HTTPException( status_code=status.HTTP_404_NOT_FOUND, - detail=f"Attack '{conversation_id}' not found", + detail=f"Attack '{attack_result_id}' not found", ) return attack @router.patch( - "/{conversation_id}", + "/{attack_result_id}", response_model=AttackSummary, responses={ 404: {"model": ProblemDetail, "description": "Attack not found"}, }, ) async def update_attack( - conversation_id: str, + attack_result_id: str, request: UpdateAttackRequest, ) -> AttackSummary: """ @@ -205,46 +211,160 @@ async def update_attack( """ service = get_attack_service() - attack = await service.update_attack_async(conversation_id=conversation_id, request=request) + attack = await service.update_attack_async(attack_result_id=attack_result_id, request=request) if not attack: raise HTTPException( status_code=status.HTTP_404_NOT_FOUND, - detail=f"Attack '{conversation_id}' not found", + detail=f"Attack '{attack_result_id}' not found", ) return attack @router.get( - "/{conversation_id}/messages", - response_model=AttackMessagesResponse, + "/{attack_result_id}/messages", + response_model=ConversationMessagesResponse, responses={ - 404: {"model": ProblemDetail, "description": "Attack not found"}, + 404: {"model": ProblemDetail, "description": "Attack or conversation not found"}, }, ) -async def get_attack_messages(conversation_id: str) -> AttackMessagesResponse: +async def get_conversation_messages( + attack_result_id: str, + conversation_id: str = Query(..., description="The conversation_id whose messages to return"), +) -> ConversationMessagesResponse: """ - Get all messages for an attack. + Get all messages for a conversation belonging to an attack. Returns prepended conversation and all messages in order. Returns: - AttackMessagesResponse: All messages for the attack. + ConversationMessagesResponse: All messages for the conversation. """ service = get_attack_service() - messages = await service.get_attack_messages_async(conversation_id=conversation_id) + messages = await service.get_conversation_messages_async( + attack_result_id=attack_result_id, + conversation_id=conversation_id, + ) if not messages: raise HTTPException( status_code=status.HTTP_404_NOT_FOUND, - detail=f"Attack '{conversation_id}' not found", + detail=f"Attack '{attack_result_id}' not found", ) return messages +@router.get( + "/{attack_result_id}/conversations", + response_model=AttackConversationsResponse, + responses={ + 404: {"model": ProblemDetail, "description": "Attack not found"}, + }, +) +async def get_conversations(attack_result_id: str) -> AttackConversationsResponse: + """ + Get all conversations belonging to an attack. + + Returns the main conversation and all related conversations with + message counts and preview text. + + Returns: + AttackConversationsResponse: All conversations for the attack. + """ + service = get_attack_service() + + result = await service.get_conversations_async(attack_result_id=attack_result_id) + if not result: + raise HTTPException( + status_code=status.HTTP_404_NOT_FOUND, + detail=f"Attack '{attack_result_id}' not found", + ) + + return result + + +@router.post( + "/{attack_result_id}/conversations", + response_model=CreateConversationResponse, + status_code=status.HTTP_201_CREATED, + responses={ + 404: {"model": ProblemDetail, "description": "Attack not found"}, + }, +) +async def create_related_conversation( + attack_result_id: str, + request: CreateConversationRequest, +) -> CreateConversationResponse: + """ + Create a new conversation within an existing attack. + + Generates a new conversation_id, adds it as a related conversation + to the AttackResult, and optionally stores prepended messages. + + Returns: + CreateConversationResponse: The new conversation details. + """ + service = get_attack_service() + + result = await service.create_related_conversation_async( + attack_result_id=attack_result_id, + request=request, + ) + if not result: + raise HTTPException( + status_code=status.HTTP_404_NOT_FOUND, + detail=f"Attack '{attack_result_id}' not found", + ) + + return result + + +@router.post( + "/{attack_result_id}/change-main-conversation", + response_model=ChangeMainConversationResponse, + responses={ + 404: {"model": ProblemDetail, "description": "Attack not found"}, + 400: {"model": ProblemDetail, "description": "Invalid conversation"}, + }, +) +async def change_main_conversation( + attack_result_id: str, + request: ChangeMainConversationRequest, +) -> ChangeMainConversationResponse: + """ + Change the main conversation for an attack. + + Swaps the attack's ``conversation_id`` to the specified conversation + and moves the previous main into the related conversations list. + + Returns: + ChangeMainConversationResponse: The AttackResult ID and new main conversation. + """ + service = get_attack_service() + + try: + result = await service.change_main_conversation_async( + attack_result_id=attack_result_id, + request=request, + ) + except ValueError as e: + raise HTTPException( + status_code=status.HTTP_400_BAD_REQUEST, + detail=str(e), + ) + + if not result: + raise HTTPException( + status_code=status.HTTP_404_NOT_FOUND, + detail=f"Attack '{attack_result_id}' not found", + ) + + return result + + @router.post( - "/{conversation_id}/messages", + "/{attack_result_id}/messages", response_model=AddMessageResponse, responses={ 404: {"model": ProblemDetail, "description": "Attack not found"}, @@ -252,7 +372,7 @@ async def get_attack_messages(conversation_id: str) -> AttackMessagesResponse: }, ) async def add_message( - conversation_id: str, + attack_result_id: str, request: AddMessageRequest, ) -> AddMessageResponse: """ @@ -273,7 +393,7 @@ async def add_message( service = get_attack_service() try: - return await service.add_message_async(conversation_id=conversation_id, request=request) + return await service.add_message_async(attack_result_id=attack_result_id, request=request) except ValueError as e: error_msg = str(e) if "not found" in error_msg.lower(): @@ -286,7 +406,13 @@ async def add_message( detail=error_msg, ) from e except Exception as e: + tb = traceback.format_exception(type(e), e, e.__traceback__) + # Include the root cause if chained + cause = e.__cause__ + if cause: + tb += traceback.format_exception(type(cause), cause, cause.__traceback__) + detail = "".join(tb) raise HTTPException( status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, - detail=f"Failed to add message: {str(e)}", + detail=detail, ) from e diff --git a/pyrit/backend/routes/targets.py b/pyrit/backend/routes/targets.py index f17f4f4f68..4a4689ed68 100644 --- a/pyrit/backend/routes/targets.py +++ b/pyrit/backend/routes/targets.py @@ -32,7 +32,7 @@ ) async def list_targets( limit: int = Query(50, ge=1, le=200, description="Maximum items per page"), - cursor: Optional[str] = Query(None, description="Pagination cursor (target_unique_name)"), + cursor: Optional[str] = Query(None, description="Pagination cursor (target_registry_name)"), ) -> TargetListResponse: """ List target instances with pagination. @@ -83,26 +83,26 @@ async def create_target(request: CreateTargetRequest) -> TargetInstance: @router.get( - "/{target_unique_name}", + "/{target_registry_name}", response_model=TargetInstance, responses={ 404: {"model": ProblemDetail, "description": "Target not found"}, }, ) -async def get_target(target_unique_name: str) -> TargetInstance: +async def get_target(target_registry_name: str) -> TargetInstance: """ - Get a target instance by unique name. + Get a target instance by registry name. Returns: TargetInstance: The target instance details. """ service = get_target_service() - target = await service.get_target_async(target_unique_name=target_unique_name) + target = await service.get_target_async(target_registry_name=target_registry_name) if not target: raise HTTPException( status_code=status.HTTP_404_NOT_FOUND, - detail=f"Target '{target_unique_name}' not found", + detail=f"Target '{target_registry_name}' not found", ) return target diff --git a/pyrit/backend/routes/version.py b/pyrit/backend/routes/version.py index e24654b9d1..a5e6249810 100644 --- a/pyrit/backend/routes/version.py +++ b/pyrit/backend/routes/version.py @@ -12,6 +12,7 @@ from pydantic import BaseModel import pyrit +from pyrit.memory import CentralMemory logger = logging.getLogger(__name__) @@ -26,6 +27,7 @@ class VersionResponse(BaseModel): commit: Optional[str] = None modified: Optional[bool] = None display: str + database_info: Optional[str] = None @router.get("", response_model=VersionResponse) @@ -58,4 +60,23 @@ async def get_version_async() -> VersionResponse: except Exception as e: logger.warning(f"Failed to load build info: {e}") - return VersionResponse(version=version, source=source, commit=commit, modified=modified, display=display) + # Detect current database backend + database_info: Optional[str] = None + try: + memory = CentralMemory.get_memory_instance() + db_type = type(memory).__name__ + db_name = None + if memory.engine.url.database: + db_name = memory.engine.url.database.split("?")[0] + database_info = f"{db_type} ({db_name})" if db_name else db_type + except (ValueError, Exception) as e: + logger.debug(f"Could not detect database info: {e}") + + return VersionResponse( + version=version, + source=source, + commit=commit, + modified=modified, + display=display, + database_info=database_info, + ) diff --git a/pyrit/backend/services/attack_service.py b/pyrit/backend/services/attack_service.py index 652cafee53..07c97dc9bc 100644 --- a/pyrit/backend/services/attack_service.py +++ b/pyrit/backend/services/attack_service.py @@ -15,25 +15,32 @@ - AI-generated attacks may have multiple related conversations """ +import mimetypes import uuid from datetime import datetime, timezone from functools import lru_cache -from typing import Any, Literal, Optional +from typing import Any, Dict, List, Literal, Optional, Sequence, cast from pyrit.backend.mappers.attack_mappers import ( attack_result_to_summary, - pyrit_messages_to_dto, + pyrit_messages_to_dto_async, request_piece_to_pyrit_message_piece, request_to_pyrit_message, ) from pyrit.backend.models.attacks import ( AddMessageRequest, AddMessageResponse, + AttackConversationsResponse, AttackListResponse, - AttackMessagesResponse, AttackSummary, + ChangeMainConversationRequest, + ChangeMainConversationResponse, + ConversationMessagesResponse, + ConversationSummary, CreateAttackRequest, CreateAttackResponse, + CreateConversationRequest, + CreateConversationResponse, UpdateAttackRequest, ) from pyrit.backend.models.common import PaginationInfo @@ -41,7 +48,16 @@ from pyrit.backend.services.target_service import get_target_service from pyrit.identifiers import ComponentIdentifier from pyrit.memory import CentralMemory -from pyrit.models import AttackOutcome, AttackResult +from pyrit.memory.memory_models import PromptMemoryEntry +from pyrit.models import ( + AttackOutcome, + AttackResult, + ConversationStats, + ConversationType, + Message as PyritMessage, + PromptDataType, + data_serializer_factory, +) from pyrit.prompt_normalizer import PromptConverterConfiguration, PromptNormalizer @@ -63,8 +79,8 @@ def __init__(self) -> None: async def list_attacks_async( self, *, - attack_class: Optional[str] = None, - converter_classes: Optional[list[str]] = None, + attack_type: Optional[str] = None, + converter_types: Optional[List[str]] = None, outcome: Optional[Literal["undetermined", "success", "failure"]] = None, labels: Optional[dict[str, str]] = None, min_turns: Optional[int] = None, @@ -78,8 +94,8 @@ async def list_attacks_async( Queries AttackResult entries from the database. Args: - attack_class: Filter by exact attack class_name (case-sensitive). - converter_classes: Filter by converter usage. + attack_type: Filter by exact attack type name (case-sensitive). + converter_types: Filter by converter usage. None = no filter, [] = only attacks with no converters, ["A", "B"] = only attacks using ALL specified converters (AND logic, case-insensitive). outcome: Filter by attack outcome. @@ -95,9 +111,9 @@ async def list_attacks_async( # Phase 1: Query + lightweight filtering (no pieces needed) attack_results = self._memory.get_attack_results( outcome=outcome, - labels=labels, - attack_class=attack_class, - converter_classes=converter_classes, + labels=labels if labels else None, + attack_type=attack_type, + converter_types=converter_types, ) filtered: list[AttackResult] = [] @@ -116,13 +132,44 @@ async def list_attacks_async( # Paginate on the lightweight list first page_results, has_more = self._paginate_attack_results(filtered, cursor, limit) - next_cursor = page_results[-1].conversation_id if has_more and page_results else None + next_cursor = page_results[-1].attack_result_id if has_more and page_results else None + + # Phase 2: Lightweight DB aggregation for the page only. + # Collect conversation IDs we care about (main + pruned, not adversarial). + all_conv_ids: List[str] = [] + for ar in page_results: + all_conv_ids.append(ar.conversation_id) + all_conv_ids.extend( + ref.conversation_id + for ref in ar.related_conversations + if ref.conversation_type == ConversationType.PRUNED + ) + + stats_map = self._memory.get_conversation_stats(conversation_ids=all_conv_ids) if all_conv_ids else {} # Phase 2: Fetch pieces only for the page we're returning - page: list[AttackSummary] = [] + page: List[AttackSummary] = [] for ar in page_results: - pieces = self._memory.get_message_pieces(conversation_id=ar.conversation_id) - page.append(attack_result_to_summary(ar, pieces=pieces)) + # Merge stats for the main conversation and its pruned relatives. + main_stats = stats_map.get(ar.conversation_id) + pruned_ids = [ + ref.conversation_id + for ref in ar.related_conversations + if ref.conversation_type == ConversationType.PRUNED + ] + pruned_stats = [stats_map[cid] for cid in pruned_ids if cid in stats_map] + + total_count = (main_stats.message_count if main_stats else 0) + sum(s.message_count for s in pruned_stats) + preview = main_stats.last_message_preview if main_stats else None + conv_labels = (main_stats.labels if main_stats else None) or {} + + merged = ConversationStats( + message_count=total_count, + last_message_preview=preview, + labels=conv_labels, + ) + + page.append(attack_result_to_summary(ar, stats=merged)) return AttackListResponse( items=page, @@ -131,62 +178,84 @@ async def list_attacks_async( async def get_attack_options_async(self) -> list[str]: """ - Get all unique attack class names from stored attack results. + Get all unique attack type names from stored attack results. Delegates to the memory layer which extracts distinct class_name values from the attack_identifier JSON column via SQL. Returns: - Sorted list of unique attack class names. + Sorted list of unique attack type names. """ - return self._memory.get_unique_attack_class_names() + return self._memory.get_unique_attack_type_names() async def get_converter_options_async(self) -> list[str]: """ - Get all unique converter class names used across attack results. + Get all unique converter type names used across attack results. Delegates to the memory layer which extracts distinct converter - class_name values from the attack_identifier JSON column via SQL. + type names from the attack_identifier JSON column via SQL. Returns: - Sorted list of unique converter class names. + Sorted list of unique converter type names. """ - return self._memory.get_unique_converter_class_names() + return self._memory.get_unique_converter_type_names() - async def get_attack_async(self, *, conversation_id: str) -> Optional[AttackSummary]: + async def get_attack_async(self, *, attack_result_id: str) -> Optional[AttackSummary]: """ Get attack details (high-level metadata, no messages). - Queries the AttackResult from the database. + Queries the AttackResult from the database by its primary key. Returns: AttackSummary if found, None otherwise. """ - results = self._memory.get_attack_results(conversation_id=conversation_id) + results = self._memory.get_attack_results(attack_result_ids=[attack_result_id]) if not results: return None ar = results[0] - pieces = self._memory.get_message_pieces(conversation_id=ar.conversation_id) - return attack_result_to_summary(ar, pieces=pieces) + stats_map = self._memory.get_conversation_stats(conversation_ids=[ar.conversation_id]) + stats = stats_map.get(ar.conversation_id, ConversationStats(message_count=0)) + return attack_result_to_summary(ar, stats=stats) - async def get_attack_messages_async(self, *, conversation_id: str) -> Optional[AttackMessagesResponse]: + async def get_conversation_messages_async( + self, + *, + attack_result_id: str, + conversation_id: str, + ) -> Optional[ConversationMessagesResponse]: """ - Get all messages for an attack. + Get all messages for a conversation belonging to an attack. + + Args: + attack_result_id: The AttackResult's primary key (used to verify existence). + conversation_id: The conversation whose messages to return. Returns: - AttackMessagesResponse if attack found, None otherwise. + ConversationMessagesResponse if attack found, None otherwise. + + Raises: + ValueError: If the conversation does not belong to the attack. """ # Check attack exists - results = self._memory.get_attack_results(conversation_id=conversation_id) + results = self._memory.get_attack_results(attack_result_ids=[attack_result_id]) if not results: return None + # Verify the conversation belongs to this attack + ar = results[0] + allowed_related_ids = { + ref.conversation_id for ref in ar.related_conversations if ref.conversation_type == ConversationType.PRUNED + } + all_conv_ids = {ar.conversation_id} | allowed_related_ids + if conversation_id not in all_conv_ids: + raise ValueError(f"Conversation '{conversation_id}' is not part of attack '{attack_result_id}'") + # Get messages for this conversation pyrit_messages = self._memory.get_conversation(conversation_id=conversation_id) - backend_messages = pyrit_messages_to_dto(list(pyrit_messages)) + backend_messages = await pyrit_messages_to_dto_async(list(pyrit_messages)) - return AttackMessagesResponse( + return ConversationMessagesResponse( conversation_id=conversation_id, messages=backend_messages, ) @@ -195,24 +264,44 @@ async def create_attack_async(self, *, request: CreateAttackRequest) -> CreateAt """ Create a new attack. - Creates an AttackResult with a new conversation_id. + Creates an AttackResult with a new conversation_id. When + ``source_conversation_id`` and ``cutoff_index`` are provided the + backend duplicates messages up to and including the cutoff turn, + applies the new labels, and maps assistant roles to + ``simulated_assistant`` so the branched context is inert. Returns: CreateAttackResponse with the new attack's ID and creation time. + + Raises: + ValueError: If the target is not found. """ target_service = get_target_service() - target_instance = await target_service.get_target_async(target_unique_name=request.target_unique_name) + target_instance = await target_service.get_target_async(target_registry_name=request.target_registry_name) if not target_instance: - raise ValueError(f"Target instance '{request.target_unique_name}' not found") + raise ValueError(f"Target instance '{request.target_registry_name}' not found") # Get the actual target object so we can capture its ComponentIdentifier - target_obj = target_service.get_target_object(target_unique_name=request.target_unique_name) + target_obj = target_service.get_target_object(target_registry_name=request.target_registry_name) target_identifier = target_obj.get_identifier() if target_obj else None - # Generate a new conversation_id for this attack - conversation_id = str(uuid.uuid4()) now = datetime.now(timezone.utc) + # Merge source label with any user-supplied labels + labels = dict(request.labels) if request.labels else {} + labels.setdefault("source", "gui") + + # --- Branch via duplication (preferred for tracking) --------------- + if request.source_conversation_id is not None and request.cutoff_index is not None: + conversation_id = self._duplicate_conversation_up_to( + source_conversation_id=request.source_conversation_id, + cutoff_index=request.cutoff_index, + labels_override=labels, + remap_assistant_to_simulated=True, + ) + else: + conversation_id = str(uuid.uuid4()) + # Create AttackResult attack_result = AttackResult( conversation_id=conversation_id, @@ -229,14 +318,10 @@ async def create_attack_async(self, *, request: CreateAttackRequest) -> CreateAt }, ) - # Merge source label with any user-supplied labels - labels = dict(request.labels) if request.labels else {} - labels.setdefault("source", "gui") - # Store in memory self._memory.add_attack_results_to_memory(attack_results=[attack_result]) - # Store prepended conversation if provided + # Store prepended conversation messages if provided if request.prepended_conversation: await self._store_prepended_messages( conversation_id=conversation_id, @@ -244,10 +329,14 @@ async def create_attack_async(self, *, request: CreateAttackRequest) -> CreateAt labels=labels, ) - return CreateAttackResponse(conversation_id=conversation_id, created_at=now) + return CreateAttackResponse( + attack_result_id=attack_result.attack_result_id or "", + conversation_id=conversation_id, + created_at=now, + ) async def update_attack_async( - self, *, conversation_id: str, request: UpdateAttackRequest + self, *, attack_result_id: str, request: UpdateAttackRequest ) -> Optional[AttackSummary]: """ Update an attack's outcome. @@ -257,7 +346,7 @@ async def update_attack_async( Returns: Updated AttackSummary if found, None otherwise. """ - results = self._memory.get_attack_results(conversation_id=conversation_id) + results = self._memory.get_attack_results(attack_result_ids=[attack_result_id]) if not results: return None @@ -269,72 +358,333 @@ async def update_attack_async( } new_outcome = outcome_map.get(request.outcome, AttackOutcome.UNDETERMINED) - # Update the attack result (need to update via memory interface) - # For now, we update metadata to track the change ar = results[0] - ar.outcome = new_outcome - ar.metadata["updated_at"] = datetime.now(timezone.utc).isoformat() + updated_metadata = dict(ar.metadata) if ar.metadata else {} + updated_metadata["updated_at"] = datetime.now(timezone.utc).isoformat() + + self._memory.update_attack_result_by_id( + attack_result_id=attack_result_id, + update_fields={ + "outcome": new_outcome.value, + "attack_metadata": updated_metadata, + }, + ) + + return await self.get_attack_async(attack_result_id=attack_result_id) + + async def get_conversations_async(self, *, attack_result_id: str) -> Optional[AttackConversationsResponse]: + """ + Get all conversations belonging to an attack. + + Includes the main conversation and all related conversations from the + AttackResult. Each entry is enriched with message count, a preview, + and the earliest message timestamp using a single batched query. + + Returns: + AttackConversationsResponse if attack found, None otherwise. + """ + results = self._memory.get_attack_results(attack_result_ids=[attack_result_id]) + if not results: + return None + + ar = results[0] + + # Collect all conversation IDs (main + PRUNED related) and fetch stats in one query. + pruned_related_ids = [ + ref.conversation_id for ref in ar.related_conversations if ref.conversation_type == ConversationType.PRUNED + ] + all_conv_ids = [ar.conversation_id] + pruned_related_ids + stats_map = self._memory.get_conversation_stats(conversation_ids=all_conv_ids) + + conversations: List[ConversationSummary] = [] + for conv_id in all_conv_ids: + stats = stats_map.get(conv_id) + created_at = stats.created_at.isoformat() if stats and stats.created_at else None + conversations.append( + ConversationSummary( + conversation_id=conv_id, + message_count=stats.message_count if stats else 0, + last_message_preview=stats.last_message_preview if stats else None, + created_at=created_at, + ) + ) + + # Sort all conversations by created_at (earliest first, None last) + conversations.sort(key=lambda c: (c.created_at is None, c.created_at or "")) + + return AttackConversationsResponse( + attack_result_id=attack_result_id, + main_conversation_id=ar.conversation_id, + conversations=conversations, + ) + + async def create_related_conversation_async( + self, *, attack_result_id: str, request: CreateConversationRequest + ) -> Optional[CreateConversationResponse]: + """ + Create a new conversation within an existing attack. + + When ``source_conversation_id`` and ``cutoff_index`` are provided the + backend duplicates messages up to and including the cutoff turn. The + duplication preserves ``original_prompt_id`` so that the new pieces + remain linked to the originals for tracking purposes. + + Returns: + CreateConversationResponse if attack found, None otherwise. + """ + results = self._memory.get_attack_results(attack_result_ids=[attack_result_id]) + if not results: + return None + + ar = results[0] + now = datetime.now(timezone.utc) + + # --- Branch via duplication (preferred for tracking) --------------- + if request.source_conversation_id is not None and request.cutoff_index is not None: + new_conversation_id = self._duplicate_conversation_up_to( + source_conversation_id=request.source_conversation_id, + cutoff_index=request.cutoff_index, + ) + else: + new_conversation_id = str(uuid.uuid4()) + + # Add to pruned_conversation_ids so user-created branches are visible in the GUI history panel. + existing_pruned = [ + ref.conversation_id + for ref in ar.related_conversations + if ref.conversation_type == ConversationType.PRUNED + ] + + updated_metadata = dict(ar.metadata or {}) + updated_metadata["updated_at"] = now.isoformat() + + self._memory.update_attack_result_by_id( + attack_result_id=attack_result_id, + update_fields={ + "pruned_conversation_ids": existing_pruned + [new_conversation_id], + "attack_metadata": updated_metadata, + }, + ) + + return CreateConversationResponse(conversation_id=new_conversation_id, created_at=now) + + async def change_main_conversation_async( + self, *, attack_result_id: str, request: ChangeMainConversationRequest + ) -> Optional[ChangeMainConversationResponse]: + """ + Change the main conversation by promoting a related conversation. + + Updates the AttackResult's ``conversation_id`` to the target + conversation and moves the previous main conversation into the + related conversations list. The ``attack_result_id`` (primary + key) remains unchanged. + + Returns: + ChangeMainConversationResponse if the source attack exists, None otherwise. + """ + results = self._memory.get_attack_results(attack_result_ids=[attack_result_id]) + if not results: + return None + + ar = results[0] + target_conv_id = request.conversation_id - # Re-add to memory (this should update) - self._memory.add_attack_results_to_memory(attack_results=[ar]) + # If the target is already the main conversation, nothing to do. + if target_conv_id == ar.conversation_id: + return ChangeMainConversationResponse( + attack_result_id=attack_result_id, + conversation_id=target_conv_id, + ) - return await self.get_attack_async(conversation_id=conversation_id) + # Verify the conversation belongs to this attack (main or related) + all_conv_ids = {ar.conversation_id} | {ref.conversation_id for ref in ar.related_conversations} + if target_conv_id not in all_conv_ids: + raise ValueError(f"Conversation '{target_conv_id}' is not part of this attack") + + # Build updated DB columns: remove target from its list, add old main + # to adversarial list (GUI conversations are always adversarial). + updated_pruned = [ + ref.conversation_id + for ref in ar.related_conversations + if ref.conversation_id != target_conv_id and ref.conversation_type == ConversationType.PRUNED + ] + updated_adversarial = [ + ref.conversation_id + for ref in ar.related_conversations + if ref.conversation_id != target_conv_id and ref.conversation_type == ConversationType.ADVERSARIAL + ] + # The old main becomes an adversarial related conversation + updated_adversarial.append(ar.conversation_id) + + self._memory.update_attack_result_by_id( + attack_result_id=attack_result_id, + update_fields={ + "conversation_id": target_conv_id, + "pruned_conversation_ids": updated_pruned if updated_pruned else None, + "adversarial_chat_conversation_ids": updated_adversarial if updated_adversarial else None, + }, + ) + + return ChangeMainConversationResponse( + attack_result_id=attack_result_id, + conversation_id=target_conv_id, + ) - async def add_message_async(self, *, conversation_id: str, request: AddMessageRequest) -> AddMessageResponse: + async def add_message_async(self, *, attack_result_id: str, request: AddMessageRequest) -> AddMessageResponse: """ Add a message to an attack, optionally sending to target. Messages are stored in the database via PromptNormalizer. + The ``request.target_conversation_id`` field specifies which conversation + the messages are stored under (main conversation or a related one). Returns: AddMessageResponse containing the updated attack detail. """ # Check if attack exists - results = self._memory.get_attack_results(conversation_id=conversation_id) + results = self._memory.get_attack_results(attack_result_ids=[attack_result_id]) if not results: - raise ValueError(f"Attack '{conversation_id}' not found") + raise ValueError(f"Attack '{attack_result_id}' not found") ar = results[0] + main_conversation_id = ar.conversation_id aid = ar.attack_identifier - objective_target = aid.get_child("objective_target") if aid else None - if not aid or not objective_target: - raise ValueError(f"Attack '{conversation_id}' has no target configured") - target_unique_name = objective_target.unique_name + + # --- Guard: prevent adding messages with a mismatched target ---------- + # If the attack was created with a specific target, the caller must + # use exactly that target. This prevents silently corrupting the + # conversation by sending to a different model. + if request.send and request.target_registry_name: + stored_target_id = aid.get_child("objective_target") if aid else None + if stored_target_id: + target_service = get_target_service() + request_target_obj = target_service.get_target_object( + target_registry_name=request.target_registry_name + ) + if request_target_obj: + request_target_id = request_target_obj.get_identifier() + # Compare class, endpoint, and model – sufficient to catch + # cross-target mistakes while allowing config-level changes. + if ( + stored_target_id.class_name != request_target_id.class_name + or (stored_target_id.params.get("endpoint") or "") != (request_target_id.params.get("endpoint") or "") + or (stored_target_id.params.get("model_name") or "") != (request_target_id.params.get("model_name") or "") + ): + raise ValueError( + f"Target mismatch: attack was created with " + f"{stored_target_id.class_name}/{stored_target_id.params.get('model_name')} " + f"but request uses {request_target_id.class_name}/{request_target_id.params.get('model_name')}. " + f"Create a new attack to use a different target." + ) + + # --- Guard: prevent different operator from modifying the attack ------ + # If existing messages have an operator label, the new message must + # come from the same operator. + existing_pieces_for_guard = self._memory.get_message_pieces(conversation_id=main_conversation_id) + existing_operator = next( + (p.labels.get("op_name") for p in existing_pieces_for_guard if p.labels and p.labels.get("op_name")), + None, + ) + if existing_operator and request.labels: + request_operator = request.labels.get("op_name") + if request_operator and request_operator != existing_operator: + raise ValueError( + f"Operator mismatch: attack belongs to operator '{existing_operator}' " + f"but request is from '{request_operator}'. " + f"Create a new attack to continue." + ) + + # Use the explicitly-provided conversation_id for message storage + msg_conversation_id = request.target_conversation_id + + # The frontend must supply the target registry name so the backend + # stays stateless — no reverse lookups, no in-memory mapping. + target_registry_name = request.target_registry_name + if request.send and not target_registry_name: + raise ValueError("target_registry_name is required when send=True") # Get existing messages to determine sequence. # NOTE: This read-then-write is not atomic (TOCTOU). Fine for the # current single-user UI, but would need a DB-level sequence # generator or optimistic locking if concurrent writes are supported. - existing = self._memory.get_message_pieces(conversation_id=conversation_id) + existing = self._memory.get_message_pieces(conversation_id=msg_conversation_id) sequence = max((p.sequence for p in existing), default=-1) + 1 - # Inherit labels from existing pieces so new messages stay consistent - attack_labels = next((p.labels for p in existing if getattr(p, "labels", None)), None) + # Inherit labels from existing pieces so new messages stay consistent. + # Try the target conversation first, fall back to the main conversation, + # then fall back to labels provided explicitly in the request. + # Use explicit len() check because {} is falsy but a valid labels value. + attack_labels = next((p.labels for p in existing if p.labels and len(p.labels) > 0), None) + if not attack_labels: + main_pieces = self._memory.get_message_pieces(conversation_id=main_conversation_id) + attack_labels = next((p.labels for p in main_pieces if p.labels and len(p.labels) > 0), None) + if not attack_labels: + attack_labels = dict(request.labels) if request.labels else {} if request.send: + assert target_registry_name is not None # validated above await self._send_and_store_message( - conversation_id, target_unique_name, request, sequence, labels=attack_labels + conversation_id=msg_conversation_id, + target_registry_name=target_registry_name, + request=request, + sequence=sequence, + labels=attack_labels, ) else: - await self._store_message_only(conversation_id, request, sequence, labels=attack_labels) + await self._store_message_only( + conversation_id=msg_conversation_id, + request=request, + sequence=sequence, + labels=attack_labels, + ) + + # Persist updated timestamp so the history list reflects recent activity + updated_metadata = dict(ar.metadata or {}) + updated_metadata["updated_at"] = datetime.now(timezone.utc).isoformat() + + update_fields: Dict[str, Any] = {"attack_metadata": updated_metadata} + + # Track converters used in this turn on the AttackResult. + # Always propagate when converter_ids are provided, regardless of + # whether the frontend already applied them (converted_value set). + if request.converter_ids: + converter_objs = get_converter_service().get_converter_objects_for_ids(converter_ids=request.converter_ids) + new_converter_ids = [c.get_identifier() for c in converter_objs] + aid = ar.attack_identifier + if aid: + existing_converters: List[ComponentIdentifier] = list(aid.get_child_list("request_converters")) + existing_hashes = {c.hash for c in existing_converters} + merged = existing_converters + [c for c in new_converter_ids if c.hash not in existing_hashes] + new_children = dict(aid.children) + if merged: + new_children["request_converters"] = merged + new_aid = ComponentIdentifier( + class_name=aid.class_name, + class_module=aid.class_module, + params=dict(aid.params), + children=new_children, + ) + update_fields["attack_identifier"] = new_aid.to_dict() - # Update attack timestamp - ar.metadata["updated_at"] = datetime.now(timezone.utc).isoformat() + self._memory.update_attack_result_by_id( + attack_result_id=attack_result_id, + update_fields=update_fields, + ) - attack_detail = await self.get_attack_async(conversation_id=conversation_id) + attack_detail = await self.get_attack_async(attack_result_id=attack_result_id) if attack_detail is None: - raise ValueError(f"Attack '{conversation_id}' not found after update") + raise ValueError(f"Attack '{attack_result_id}' not found after update") - attack_messages = await self.get_attack_messages_async(conversation_id=conversation_id) + # Return messages for the conversation that was written to + attack_messages = await self.get_conversation_messages_async( + attack_result_id=attack_result_id, + conversation_id=msg_conversation_id, + ) if attack_messages is None: - raise ValueError(f"Attack '{conversation_id}' messages not found after update") + raise ValueError(f"Attack '{attack_result_id}' messages not found after update") return AddMessageResponse(attack=attack_detail, messages=attack_messages) - # ======================================================================== - # Private Helper Methods - Identifier Access - # ======================================================================== - # ======================================================================== # Private Helper Methods - Pagination # ======================================================================== @@ -354,7 +704,7 @@ def _paginate_attack_results( start_idx = 0 if cursor: for i, item in enumerate(items): - if item.conversation_id == cursor: + if item.attack_result_id == cursor: start_idx = i + 1 break @@ -362,10 +712,133 @@ def _paginate_attack_results( has_more = len(items) > start_idx + limit return page, has_more + # ======================================================================== + # Private Helper Methods - Conversation Info + # ======================================================================== + + @staticmethod + def _get_last_message_preview(pieces: Sequence[PromptMemoryEntry]) -> Optional[str]: + """Return a truncated preview of the last message piece's text.""" + if not pieces: + return None + last = max(pieces, key=lambda p: p.sequence) + text = last.converted_value or "" + return text[:100] + "..." if len(text) > 100 else text + + @staticmethod + def _count_messages(pieces: Sequence[PromptMemoryEntry]) -> int: + """ + Count distinct messages (by sequence number) in a list of pieces. + + Returns: + The number of unique sequence values. + """ + return len(set(p.sequence for p in pieces)) + + @staticmethod + def _get_earliest_timestamp(pieces: Sequence[PromptMemoryEntry]) -> Optional[datetime]: + """Return the earliest timestamp from a list of message pieces.""" + if not pieces: + return None + timestamps: List[datetime] = [p.timestamp for p in pieces if p.timestamp is not None] + return min(timestamps) if timestamps else None + + # ======================================================================== + # Private Helper Methods - Duplicate / Branch + # ======================================================================== + + def _duplicate_conversation_up_to( + self, + *, + source_conversation_id: str, + cutoff_index: int, + labels_override: Optional[Dict[str, str]] = None, + remap_assistant_to_simulated: bool = False, + ) -> str: + """ + Duplicate messages from a conversation up to and including a turn index. + + Uses the memory layer's ``duplicate_messages`` so that each new + piece gets a fresh ``id`` and ``timestamp`` while preserving + ``original_prompt_id`` for tracking lineage. + + Args: + source_conversation_id: The conversation to copy from. + cutoff_index: Include messages with sequence <= cutoff_index. + labels_override: When provided, the duplicated pieces' labels are + replaced with these values. Used when branching into a new + attack that belongs to a different operator. + remap_assistant_to_simulated: When True, pieces with role + ``assistant`` are changed to ``simulated_assistant`` so the + branched context is inert and won't confuse the target. + + Returns: + The new conversation ID containing the duplicated messages. + """ + messages = self._memory.get_conversation(conversation_id=source_conversation_id) + messages_to_copy = [m for m in messages if m.sequence <= cutoff_index] + + new_conversation_id, all_pieces = self._memory.duplicate_messages(messages=messages_to_copy) + + # Apply optional overrides to the fresh pieces before persisting + for piece in all_pieces: + if labels_override is not None: + piece.labels = dict(labels_override) + if remap_assistant_to_simulated and piece.role == "assistant": + piece.role = "simulated_assistant" + + if all_pieces: + self._memory.add_message_pieces_to_memory(message_pieces=list(all_pieces)) + + return new_conversation_id + # ======================================================================== # Private Helper Methods - Store Messages # ======================================================================== + @staticmethod + async def _persist_base64_pieces(request: AddMessageRequest) -> None: + """ + Persist base64-encoded non-text pieces to disk, updating values in-place. + + The frontend sends binary media (images, audio, etc.) as base64 strings + with a ``*_path`` data_type. The PyRIT target layer expects ``*_path`` + values to be **file paths**, so we decode the base64 data, write it to + the results store, and replace the request values with the resulting + file path before the message is built. + + If the value is already an HTTP(S) URL (e.g. an Azure Blob Storage URL + from a remixed/copied message), it is kept as-is since the file already + exists in storage. + """ + for piece in request.pieces: + if piece.data_type == "text" or piece.data_type == "error": + continue + + # Already a remote URL (e.g. signed blob URL from a remix) — keep as-is + if piece.original_value.startswith(("http://", "https://")): + if piece.converted_value is None: + piece.converted_value = piece.original_value + continue + + # Derive file extension from the MIME type sent by the frontend + ext = None + if piece.mime_type: + ext = mimetypes.guess_extension(piece.mime_type, strict=False) + if not ext: + ext = ".bin" + + serializer = data_serializer_factory( + category="prompt-memory-entries", + data_type=cast(PromptDataType, piece.data_type), + extension=ext, + ) + await serializer.save_b64_image(data=piece.original_value) + file_path = serializer.value + piece.original_value = file_path + if piece.converted_value is None: + piece.converted_value = file_path + async def _store_prepended_messages( self, conversation_id: str, @@ -386,17 +859,19 @@ async def _store_prepended_messages( async def _send_and_store_message( self, + *, conversation_id: str, - target_unique_name: str, + target_registry_name: str, request: AddMessageRequest, sequence: int, - *, - labels: Optional[dict[str, str]] = None, + labels: Optional[Dict[str, str]] = None, ) -> None: """Send message to target via normalizer and store response.""" - target_obj = get_target_service().get_target_object(target_unique_name=target_unique_name) + target_obj = get_target_service().get_target_object(target_registry_name=target_registry_name) if not target_obj: - raise ValueError(f"Target object for '{target_unique_name}' not found") + raise ValueError(f"Target object for '{target_registry_name}' not found") + + await self._persist_base64_pieces(request) pyrit_message = request_to_pyrit_message( request=request, @@ -404,6 +879,11 @@ async def _send_and_store_message( sequence=sequence, labels=labels, ) + + # Propagate video_id from the most recent video response so the target + # can perform a remix instead of generating from scratch. + self._inject_video_id_from_history(conversation_id=conversation_id, message=pyrit_message) + converter_configs = self._get_converter_configs(request) normalizer = PromptNormalizer() @@ -416,15 +896,78 @@ async def _send_and_store_message( ) # PromptNormalizer stores both request and response in memory automatically + def _inject_video_id_from_history(self, *, conversation_id: str, message: PyritMessage) -> None: + """ + Find the most recent video_id and attach it to the text piece's + prompt_metadata so the video target can remix. + + When a video_id is found and injected, any video_path pieces are + removed from the message since the target uses the video_id for + remix instead of re-uploading the video content. + + Lookup order: + 1. original_prompt_id on any piece in the message (traces back to + a copied/remixed piece whose metadata may contain the video_id). + 2. Conversation history (newest first) for a piece with video_id. + """ + text_piece = None + for p in message.message_pieces: + if p.original_value_data_type == "text": + text_piece = p + break + + if not text_piece: + return + + # Already has a video_id — don't override + if text_piece.prompt_metadata and text_piece.prompt_metadata.get("video_id"): + self._strip_video_pieces(message) + return + + video_id = None + + # 1. Check original_prompt_id on any piece (e.g. copied video attachment) + for p in message.message_pieces: + if p.original_prompt_id: + source_pieces = self._memory.get_message_pieces(prompt_ids=[str(p.original_prompt_id)]) + for src in source_pieces: + if src.prompt_metadata and src.prompt_metadata.get("video_id"): + video_id = src.prompt_metadata["video_id"] + break + if video_id: + break + + # 2. Search conversation history (newest first) for a video_id + if not video_id: + existing = self._memory.get_message_pieces(conversation_id=conversation_id) + for piece in reversed(existing): + if piece.prompt_metadata and piece.prompt_metadata.get("video_id"): + video_id = piece.prompt_metadata["video_id"] + break + + if video_id: + if text_piece.prompt_metadata is None: + text_piece.prompt_metadata = {} + text_piece.prompt_metadata["video_id"] = video_id + self._strip_video_pieces(message) + + @staticmethod + def _strip_video_pieces(message: PyritMessage) -> None: + """Remove video_path pieces from a message (video_id on text piece replaces them).""" + message.message_pieces = [ + p for p in message.message_pieces if p.original_value_data_type != "video_path" + ] + async def _store_message_only( self, + *, conversation_id: str, request: AddMessageRequest, sequence: int, - *, - labels: Optional[dict[str, str]] = None, + labels: Optional[Dict[str, str]] = None, ) -> None: """Store message without sending (send=False).""" + await self._persist_base64_pieces(request) for p in request.pieces: piece = request_piece_to_pyrit_message_piece( piece=p, diff --git a/pyrit/backend/services/target_service.py b/pyrit/backend/services/target_service.py index 84d440de15..41d7164970 100644 --- a/pyrit/backend/services/target_service.py +++ b/pyrit/backend/services/target_service.py @@ -82,14 +82,14 @@ def _get_target_class(self, *, target_type: str) -> type: ) return cls - def _build_instance_from_object(self, *, target_unique_name: str, target_obj: Any) -> TargetInstance: + def _build_instance_from_object(self, *, target_registry_name: str, target_obj: Any) -> TargetInstance: """ Build a TargetInstance from a registry object. Returns: TargetInstance with metadata derived from the object. """ - return target_object_to_instance(target_unique_name, target_obj) + return target_object_to_instance(target_registry_name, target_obj) async def list_targets_async( self, @@ -102,17 +102,17 @@ async def list_targets_async( Args: limit: Maximum items to return. - cursor: Pagination cursor (target_unique_name to start after). + cursor: Pagination cursor (target_registry_name to start after). Returns: TargetListResponse containing paginated targets. """ items = [ - self._build_instance_from_object(target_unique_name=name, target_obj=obj) + self._build_instance_from_object(target_registry_name=name, target_obj=obj) for name, obj in self._registry.get_all_instances().items() ] page, has_more = self._paginate(items, cursor, limit) - next_cursor = page[-1].target_unique_name if has_more and page else None + next_cursor = page[-1].target_registry_name if has_more and page else None return TargetListResponse( items=page, pagination=PaginationInfo(limit=limit, has_more=has_more, next_cursor=next_cursor, prev_cursor=cursor), @@ -129,7 +129,7 @@ def _paginate(items: list[TargetInstance], cursor: Optional[str], limit: int) -> start_idx = 0 if cursor: for i, item in enumerate(items): - if item.target_unique_name == cursor: + if item.target_registry_name == cursor: start_idx = i + 1 break @@ -137,33 +137,33 @@ def _paginate(items: list[TargetInstance], cursor: Optional[str], limit: int) -> has_more = len(items) > start_idx + limit return page, has_more - async def get_target_async(self, *, target_unique_name: str) -> Optional[TargetInstance]: + async def get_target_async(self, *, target_registry_name: str) -> Optional[TargetInstance]: """ - Get a target instance by unique name. + Get a target instance by registry name. Returns: TargetInstance if found, None otherwise. """ - obj = self._registry.get_instance_by_name(target_unique_name) + obj = self._registry.get_instance_by_name(target_registry_name) if obj is None: return None - return self._build_instance_from_object(target_unique_name=target_unique_name, target_obj=obj) + return self._build_instance_from_object(target_registry_name=target_registry_name, target_obj=obj) - def get_target_object(self, *, target_unique_name: str) -> Optional[Any]: + def get_target_object(self, *, target_registry_name: str) -> Optional[Any]: """ Get the actual target object for use in attacks. Returns: The PromptTarget object if found, None otherwise. """ - return self._registry.get_instance_by_name(target_unique_name) + return self._registry.get_instance_by_name(target_registry_name) async def create_target_async(self, *, request: CreateTargetRequest) -> TargetInstance: """ Create a new target instance from API request. Instantiates the target with the given type and params, - then registers it in the registry under its unique_name. + then registers it in the registry under its registry name. Args: request: The create target request with type and params. @@ -180,8 +180,8 @@ async def create_target_async(self, *, request: CreateTargetRequest) -> TargetIn self._registry.register_instance(target_obj) # Build response from the registered instance - target_unique_name = target_obj.get_identifier().unique_name - return self._build_instance_from_object(target_unique_name=target_unique_name, target_obj=target_obj) + target_registry_name = target_obj.get_identifier().unique_name + return self._build_instance_from_object(target_registry_name=target_registry_name, target_obj=target_obj) @lru_cache(maxsize=1) diff --git a/tests/unit/backend/test_api_routes.py b/tests/unit/backend/test_api_routes.py index 44ad3f34bb..1b092dfdca 100644 --- a/tests/unit/backend/test_api_routes.py +++ b/tests/unit/backend/test_api_routes.py @@ -19,8 +19,8 @@ from pyrit.backend.models.attacks import ( AddMessageResponse, AttackListResponse, - AttackMessagesResponse, AttackSummary, + ConversationMessagesResponse, CreateAttackResponse, Message, MessagePiece, @@ -86,13 +86,13 @@ def test_list_attacks_with_filters(self, client: TestClient) -> None: response = client.get( "/api/attacks", - params={"attack_class": "CrescendoAttack", "outcome": "success", "limit": 10}, + params={"attack_type": "CrescendoAttack", "outcome": "success", "limit": 10}, ) assert response.status_code == status.HTTP_200_OK mock_service.list_attacks_async.assert_called_once_with( - attack_class="CrescendoAttack", - converter_classes=None, + attack_type="CrescendoAttack", + converter_types=None, outcome="success", labels=None, min_turns=None, @@ -109,6 +109,7 @@ def test_create_attack_success(self, client: TestClient) -> None: mock_service = MagicMock() mock_service.create_attack_async = AsyncMock( return_value=CreateAttackResponse( + attack_result_id="ar-attack-1", conversation_id="attack-1", created_at=now, ) @@ -117,7 +118,7 @@ def test_create_attack_success(self, client: TestClient) -> None: response = client.post( "/api/attacks", - json={"target_unique_name": "target-1", "name": "Test Attack"}, + json={"target_registry_name": "target-1", "name": "Test Attack"}, ) assert response.status_code == status.HTTP_201_CREATED @@ -133,7 +134,7 @@ def test_create_attack_target_not_found(self, client: TestClient) -> None: response = client.post( "/api/attacks", - json={"target_unique_name": "nonexistent"}, + json={"target_registry_name": "nonexistent"}, ) assert response.status_code == status.HTTP_404_NOT_FOUND @@ -146,6 +147,7 @@ def test_get_attack_success(self, client: TestClient) -> None: mock_service = MagicMock() mock_service.get_attack_async = AsyncMock( return_value=AttackSummary( + attack_result_id="ar-attack-1", conversation_id="attack-1", attack_type="TestAttack", outcome=None, @@ -182,6 +184,7 @@ def test_update_attack_success(self, client: TestClient) -> None: mock_service = MagicMock() mock_service.update_attack_async = AsyncMock( return_value=AttackSummary( + attack_result_id="ar-attack-1", conversation_id="attack-1", attack_type="TestAttack", outcome="success", @@ -207,6 +210,7 @@ def test_add_message_success(self, client: TestClient) -> None: now = datetime.now(timezone.utc) attack_summary = AttackSummary( + attack_result_id="ar-attack-1", conversation_id="attack-1", attack_type="TestAttack", outcome=None, @@ -216,7 +220,7 @@ def test_add_message_success(self, client: TestClient) -> None: updated_at=now, ) - attack_messages = AttackMessagesResponse( + attack_messages = ConversationMessagesResponse( conversation_id="attack-1", messages=[ Message( @@ -256,7 +260,7 @@ def test_add_message_success(self, client: TestClient) -> None: response = client.post( "/api/attacks/attack-1/messages", - json={"pieces": [{"original_value": "Hello"}]}, + json={"pieces": [{"original_value": "Hello"}], "target_conversation_id": "attack-1"}, ) assert response.status_code == status.HTTP_200_OK @@ -286,7 +290,7 @@ def test_add_message_attack_not_found(self, client: TestClient) -> None: response = client.post( "/api/attacks/nonexistent/messages", - json={"pieces": [{"original_value": "Hello"}]}, + json={"pieces": [{"original_value": "Hello"}], "target_conversation_id": "nonexistent"}, ) assert response.status_code == status.HTTP_404_NOT_FOUND @@ -300,7 +304,7 @@ def test_add_message_target_not_found(self, client: TestClient) -> None: response = client.post( "/api/attacks/attack-1/messages", - json={"pieces": [{"original_value": "Hello"}]}, + json={"pieces": [{"original_value": "Hello"}], "target_conversation_id": "attack-1"}, ) assert response.status_code == status.HTTP_404_NOT_FOUND @@ -314,7 +318,7 @@ def test_add_message_bad_request(self, client: TestClient) -> None: response = client.post( "/api/attacks/attack-1/messages", - json={"pieces": [{"original_value": "Hello"}]}, + json={"pieces": [{"original_value": "Hello"}], "target_conversation_id": "attack-1"}, ) assert response.status_code == status.HTTP_400_BAD_REQUEST @@ -328,19 +332,19 @@ def test_add_message_internal_error(self, client: TestClient) -> None: response = client.post( "/api/attacks/attack-1/messages", - json={"pieces": [{"original_value": "Hello"}]}, + json={"pieces": [{"original_value": "Hello"}], "target_conversation_id": "attack-1"}, ) assert response.status_code == status.HTTP_500_INTERNAL_SERVER_ERROR - def test_get_attack_messages_success(self, client: TestClient) -> None: + def test_get_conversation_messages_success(self, client: TestClient) -> None: """Test getting attack messages.""" now = datetime.now(timezone.utc) with patch("pyrit.backend.routes.attacks.get_attack_service") as mock_get_service: mock_service = MagicMock() - mock_service.get_attack_messages_async = AsyncMock( - return_value=AttackMessagesResponse( + mock_service.get_conversation_messages_async = AsyncMock( + return_value=ConversationMessagesResponse( conversation_id="attack-1", messages=[ Message( @@ -354,21 +358,21 @@ def test_get_attack_messages_success(self, client: TestClient) -> None: ) mock_get_service.return_value = mock_service - response = client.get("/api/attacks/attack-1/messages") + response = client.get("/api/attacks/attack-1/messages", params={"conversation_id": "attack-1"}) assert response.status_code == status.HTTP_200_OK data = response.json() assert data["conversation_id"] == "attack-1" assert len(data["messages"]) == 1 - def test_get_attack_messages_not_found(self, client: TestClient) -> None: + def test_get_conversation_messages_not_found(self, client: TestClient) -> None: """Test getting messages for non-existent attack returns 404.""" with patch("pyrit.backend.routes.attacks.get_attack_service") as mock_get_service: mock_service = MagicMock() - mock_service.get_attack_messages_async = AsyncMock(return_value=None) + mock_service.get_conversation_messages_async = AsyncMock(return_value=None) mock_get_service.return_value = mock_service - response = client.get("/api/attacks/nonexistent/messages") + response = client.get("/api/attacks/nonexistent/messages", params={"conversation_id": "nonexistent"}) assert response.status_code == status.HTTP_404_NOT_FOUND @@ -382,6 +386,7 @@ def test_list_attacks_with_labels(self, client: TestClient) -> None: return_value=AttackListResponse( items=[ AttackSummary( + attack_result_id="ar-attack-1", conversation_id="attack-1", attack_type="TestAttack", outcome=None, @@ -416,7 +421,7 @@ def test_get_attack_options(self, client: TestClient) -> None: assert response.status_code == status.HTTP_200_OK data = response.json() - assert data["attack_classes"] == ["CrescendoAttack", "ManualAttack"] + assert data["attack_types"] == ["CrescendoAttack", "ManualAttack"] def test_get_converter_options(self, client: TestClient) -> None: """Test getting converter options from attack results.""" @@ -429,7 +434,7 @@ def test_get_converter_options(self, client: TestClient) -> None: assert response.status_code == status.HTTP_200_OK data = response.json() - assert data["converter_classes"] == ["Base64Converter", "ROT13Converter"] + assert data["converter_types"] == ["Base64Converter", "ROT13Converter"] def test_parse_labels_skips_param_without_colon(self, client: TestClient) -> None: """Test that _parse_labels skips label params that have no colon.""" @@ -486,8 +491,8 @@ def test_parse_labels_value_with_extra_colons(self, client: TestClient) -> None: call_kwargs = mock_service.list_attacks_async.call_args[1] assert call_kwargs["labels"] == {"url": "http://example.com:8080"} - def test_list_attacks_forwards_converter_classes_param(self, client: TestClient) -> None: - """Test that converter_classes query params are forwarded to service.""" + def test_parse_labels_passes_keys_through_without_normalization(self, client: TestClient) -> None: + """Test that label keys are passed through as-is (DB stores canonical keys after migration).""" with patch("pyrit.backend.routes.attacks.get_attack_service") as mock_get_service: mock_service = MagicMock() mock_service.list_attacks_async = AsyncMock( @@ -498,11 +503,145 @@ def test_list_attacks_forwards_converter_classes_param(self, client: TestClient) ) mock_get_service.return_value = mock_service - response = client.get("/api/attacks?converter_classes=Base64&converter_classes=ROT13") + response = client.get("/api/attacks?label=operator:alice&label=operation:redteam") assert response.status_code == status.HTTP_200_OK call_kwargs = mock_service.list_attacks_async.call_args[1] - assert call_kwargs["converter_classes"] == ["Base64", "ROT13"] + assert call_kwargs["labels"] == {"operator": "alice", "operation": "redteam"} + + def test_list_attacks_forwards_converter_types_param(self, client: TestClient) -> None: + """Test that converter_types query params are forwarded to service.""" + with patch("pyrit.backend.routes.attacks.get_attack_service") as mock_get_service: + mock_service = MagicMock() + mock_service.list_attacks_async = AsyncMock( + return_value=AttackListResponse( + items=[], + pagination=PaginationInfo(limit=20, has_more=False, next_cursor=None, prev_cursor=None), + ) + ) + mock_get_service.return_value = mock_service + + response = client.get("/api/attacks?converter_types=Base64&converter_types=ROT13") + + assert response.status_code == status.HTTP_200_OK + call_kwargs = mock_service.list_attacks_async.call_args[1] + assert call_kwargs["converter_types"] == ["Base64", "ROT13"] + + def test_get_conversations_success(self, client: TestClient) -> None: + """Test getting attack conversations returns service response.""" + with patch("pyrit.backend.routes.attacks.get_attack_service") as mock_get_service: + mock_service = MagicMock() + mock_service.get_conversations_async = AsyncMock( + return_value={ + "attack_result_id": "ar-attack-1", + "main_conversation_id": "attack-1", + "conversations": [ + { + "conversation_id": "attack-1", + "message_count": 2, + "last_message_preview": "hello", + "created_at": "2026-01-01T00:00:00Z", + } + ], + } + ) + mock_get_service.return_value = mock_service + + response = client.get("/api/attacks/ar-attack-1/conversations") + + assert response.status_code == status.HTTP_200_OK + data = response.json() + assert data["attack_result_id"] == "ar-attack-1" + assert data["main_conversation_id"] == "attack-1" + + def test_get_conversations_not_found(self, client: TestClient) -> None: + """Test getting conversations for missing attack returns 404.""" + with patch("pyrit.backend.routes.attacks.get_attack_service") as mock_get_service: + mock_service = MagicMock() + mock_service.get_conversations_async = AsyncMock(return_value=None) + mock_get_service.return_value = mock_service + + response = client.get("/api/attacks/missing/conversations") + + assert response.status_code == status.HTTP_404_NOT_FOUND + + def test_create_related_conversation_success(self, client: TestClient) -> None: + """Test creating related conversation returns 201 response.""" + with patch("pyrit.backend.routes.attacks.get_attack_service") as mock_get_service: + mock_service = MagicMock() + mock_service.create_related_conversation_async = AsyncMock( + return_value={ + "conversation_id": "branch-1", + "created_at": "2026-01-01T00:00:00Z", + } + ) + mock_get_service.return_value = mock_service + + response = client.post("/api/attacks/ar-attack-1/conversations", json={}) + + assert response.status_code == status.HTTP_201_CREATED + data = response.json() + assert data["conversation_id"] == "branch-1" + + def test_create_related_conversation_not_found(self, client: TestClient) -> None: + """Test creating related conversation for missing attack returns 404.""" + with patch("pyrit.backend.routes.attacks.get_attack_service") as mock_get_service: + mock_service = MagicMock() + mock_service.create_related_conversation_async = AsyncMock(return_value=None) + mock_get_service.return_value = mock_service + + response = client.post("/api/attacks/missing/conversations", json={}) + + assert response.status_code == status.HTTP_404_NOT_FOUND + + def test_change_main_conversation_success(self, client: TestClient) -> None: + """Test changing main conversation returns service response.""" + with patch("pyrit.backend.routes.attacks.get_attack_service") as mock_get_service: + mock_service = MagicMock() + mock_service.change_main_conversation_async = AsyncMock( + return_value={ + "attack_result_id": "ar-attack-1", + "conversation_id": "branch-1", + } + ) + mock_get_service.return_value = mock_service + + response = client.post( + "/api/attacks/ar-attack-1/change-main-conversation", + json={"conversation_id": "branch-1"}, + ) + + assert response.status_code == status.HTTP_200_OK + data = response.json() + assert data["conversation_id"] == "branch-1" + + def test_change_main_conversation_bad_request(self, client: TestClient) -> None: + """Test changing main conversation with invalid conversation returns 400.""" + with patch("pyrit.backend.routes.attacks.get_attack_service") as mock_get_service: + mock_service = MagicMock() + mock_service.change_main_conversation_async = AsyncMock(side_effect=ValueError("invalid conversation")) + mock_get_service.return_value = mock_service + + response = client.post( + "/api/attacks/ar-attack-1/change-main-conversation", + json={"conversation_id": "missing-conv"}, + ) + + assert response.status_code == status.HTTP_400_BAD_REQUEST + + def test_change_main_conversation_not_found(self, client: TestClient) -> None: + """Test changing main conversation for missing attack returns 404.""" + with patch("pyrit.backend.routes.attacks.get_attack_service") as mock_get_service: + mock_service = MagicMock() + mock_service.change_main_conversation_async = AsyncMock(return_value=None) + mock_get_service.return_value = mock_service + + response = client.post( + "/api/attacks/missing/change-main-conversation", + json={"conversation_id": "branch-1"}, + ) + + assert response.status_code == status.HTTP_404_NOT_FOUND # ============================================================================ @@ -538,7 +677,7 @@ def test_create_target_success(self, client: TestClient) -> None: mock_service = MagicMock() mock_service.create_target_async = AsyncMock( return_value=TargetInstance( - target_unique_name="target-1", + target_registry_name="target-1", target_type="TextTarget", ) ) @@ -551,7 +690,7 @@ def test_create_target_success(self, client: TestClient) -> None: assert response.status_code == status.HTTP_201_CREATED data = response.json() - assert data["target_unique_name"] == "target-1" + assert data["target_registry_name"] == "target-1" def test_create_target_invalid_type(self, client: TestClient) -> None: """Test target creation with invalid type.""" @@ -587,7 +726,7 @@ def test_get_target_success(self, client: TestClient) -> None: mock_service = MagicMock() mock_service.get_target_async = AsyncMock( return_value=TargetInstance( - target_unique_name="target-1", + target_registry_name="target-1", target_type="TextTarget", ) ) @@ -597,7 +736,7 @@ def test_get_target_success(self, client: TestClient) -> None: assert response.status_code == status.HTTP_200_OK data = response.json() - assert data["target_unique_name"] == "target-1" + assert data["target_registry_name"] == "target-1" def test_get_target_not_found(self, client: TestClient) -> None: """Test getting a non-existent target.""" @@ -933,6 +1072,23 @@ def test_get_labels_multiple_values(self, client: TestClient) -> None: assert set(data["labels"]["env"]) == {"prod", "staging"} assert data["labels"]["team"] == ["blue"] + def test_get_labels_returns_keys_without_normalization(self, client: TestClient) -> None: + """Test that label keys are returned as-is from the DB (canonical after migration).""" + with patch("pyrit.backend.routes.labels.CentralMemory") as mock_memory_class: + mock_memory = MagicMock() + mock_memory.get_unique_attack_labels.return_value = { + "operator": ["alice", "bob"], + "operation": ["hunt", "scan"], + } + mock_memory_class.get_memory_instance.return_value = mock_memory + + response = client.get("/api/labels") + + assert response.status_code == status.HTTP_200_OK + data = response.json() + assert set(data["labels"]["operator"]) == {"alice", "bob"} + assert set(data["labels"]["operation"]) == {"hunt", "scan"} + @pytest.mark.asyncio async def test_get_label_options_unsupported_source_returns_empty_labels(self) -> None: """Test that get_label_options returns empty labels for unsupported source types.""" diff --git a/tests/unit/backend/test_attack_service.py b/tests/unit/backend/test_attack_service.py index e184f8ad47..affc5a1eae 100644 --- a/tests/unit/backend/test_attack_service.py +++ b/tests/unit/backend/test_attack_service.py @@ -7,6 +7,7 @@ The attack service uses PyRIT memory with AttackResult as the source of truth. """ +import uuid from datetime import datetime, timezone from unittest.mock import AsyncMock, MagicMock, patch @@ -14,6 +15,7 @@ from pyrit.backend.models.attacks import ( AddMessageRequest, + ChangeMainConversationRequest, CreateAttackRequest, MessagePieceRequest, PrependedMessageRequest, @@ -25,6 +27,7 @@ ) from pyrit.identifiers import ComponentIdentifier from pyrit.models import AttackOutcome, AttackResult +from pyrit.models.conversation_stats import ConversationStats @pytest.fixture @@ -34,6 +37,7 @@ def mock_memory(): memory.get_attack_results.return_value = [] memory.get_conversation.return_value = [] memory.get_message_pieces.return_value = [] + memory.get_conversation_stats.return_value = {} return memory @@ -49,6 +53,7 @@ def attack_service(mock_memory): def make_attack_result( *, conversation_id: str = "attack-1", + attack_result_id: str = "", objective: str = "Test objective", has_target: bool = True, name: str = "Test Attack", @@ -61,6 +66,9 @@ def make_attack_result( created = created_at or now updated = updated_at or now + # Default attack_result_id to "ar-" when not explicit. + effective_ar_id = attack_result_id or f"ar-{conversation_id}" + target_identifier = ( ComponentIdentifier( class_name="TextTarget", @@ -79,6 +87,7 @@ def make_attack_result( children={"objective_target": target_identifier} if target_identifier else {}, ), outcome=outcome, + attack_result_id=effective_ar_id, metadata={ "created_at": created.isoformat(), "updated_at": updated.isoformat(), @@ -86,6 +95,16 @@ def make_attack_result( ) +def _make_matching_target_mock() -> MagicMock: + """Create a mock target object whose get_identifier() matches make_attack_result's default target.""" + mock_target = MagicMock() + mock_target.get_identifier.return_value = ComponentIdentifier( + class_name="TextTarget", + class_module="pyrit.prompt_target", + ) + return mock_target + + def make_mock_piece( *, conversation_id: str, @@ -173,45 +192,45 @@ async def test_list_attacks_returns_attacks(self, attack_service, mock_memory) - assert result.items[0].attack_type == "Test Attack" @pytest.mark.asyncio - async def test_list_attacks_filters_by_attack_class_exact(self, attack_service, mock_memory) -> None: - """Test that list_attacks passes attack_class to memory layer.""" + async def test_list_attacks_filters_by_attack_type_exact(self, attack_service, mock_memory) -> None: + """Test that list_attacks passes attack_type to memory layer.""" ar1 = make_attack_result(conversation_id="attack-1", name="CrescendoAttack") mock_memory.get_attack_results.return_value = [ar1] mock_memory.get_message_pieces.return_value = [] - result = await attack_service.list_attacks_async(attack_class="CrescendoAttack") + result = await attack_service.list_attacks_async(attack_type="CrescendoAttack") assert len(result.items) == 1 assert result.items[0].conversation_id == "attack-1" - # Verify attack_class was forwarded to the memory layer + # Verify attack_type was forwarded to the memory layer call_kwargs = mock_memory.get_attack_results.call_args[1] - assert call_kwargs["attack_class"] == "CrescendoAttack" + assert call_kwargs["attack_type"] == "CrescendoAttack" @pytest.mark.asyncio - async def test_list_attacks_attack_class_passed_to_memory(self, attack_service, mock_memory) -> None: - """Test that attack_class is forwarded to memory for DB-level filtering.""" + async def test_list_attacks_attack_type_passed_to_memory(self, attack_service, mock_memory) -> None: + """Test that attack_type is forwarded to memory for DB-level filtering.""" mock_memory.get_attack_results.return_value = [] mock_memory.get_message_pieces.return_value = [] - await attack_service.list_attacks_async(attack_class="Crescendo") + await attack_service.list_attacks_async(attack_type="Crescendo") call_kwargs = mock_memory.get_attack_results.call_args[1] - assert call_kwargs["attack_class"] == "Crescendo" + assert call_kwargs["attack_type"] == "Crescendo" @pytest.mark.asyncio async def test_list_attacks_filters_by_no_converters(self, attack_service, mock_memory) -> None: - """Test that converter_classes=[] is forwarded to memory for DB-level filtering.""" + """Test that converter_types=[] is forwarded to memory for DB-level filtering.""" mock_memory.get_attack_results.return_value = [] mock_memory.get_message_pieces.return_value = [] - await attack_service.list_attacks_async(converter_classes=[]) + await attack_service.list_attacks_async(converter_types=[]) call_kwargs = mock_memory.get_attack_results.call_args[1] - assert call_kwargs["converter_classes"] == [] + assert call_kwargs["converter_types"] == [] @pytest.mark.asyncio - async def test_list_attacks_filters_by_converter_classes_and_logic(self, attack_service, mock_memory) -> None: - """Test that list_attacks passes converter_classes to memory layer.""" + async def test_list_attacks_filters_by_converter_types_and_logic(self, attack_service, mock_memory) -> None: + """Test that list_attacks passes converter_types to memory layer.""" ar1 = make_attack_result(conversation_id="attack-1", name="Attack One") ar1.attack_identifier = ComponentIdentifier( class_name="Attack One", @@ -240,13 +259,13 @@ async def test_list_attacks_filters_by_converter_classes_and_logic(self, attack_ mock_memory.get_attack_results.return_value = [ar1] mock_memory.get_message_pieces.return_value = [] - result = await attack_service.list_attacks_async(converter_classes=["Base64Converter", "ROT13Converter"]) + result = await attack_service.list_attacks_async(converter_types=["Base64Converter", "ROT13Converter"]) assert len(result.items) == 1 assert result.items[0].conversation_id == "attack-1" - # Verify converter_classes was forwarded to the memory layer + # Verify converter_types was forwarded to the memory layer call_kwargs = mock_memory.get_attack_results.call_args[1] - assert call_kwargs["converter_classes"] == ["Base64Converter", "ROT13Converter"] + assert call_kwargs["converter_types"] == ["Base64Converter", "ROT13Converter"] @pytest.mark.asyncio async def test_list_attacks_filters_by_min_turns(self, attack_service, mock_memory) -> None: @@ -280,20 +299,42 @@ async def test_list_attacks_filters_by_max_turns(self, attack_service, mock_memo @pytest.mark.asyncio async def test_list_attacks_includes_labels_in_summary(self, attack_service, mock_memory) -> None: - """Test that list_attacks includes labels from message pieces in summaries.""" + """Test that list_attacks includes labels from conversation stats in summaries.""" ar = make_attack_result( conversation_id="attack-1", ) mock_memory.get_attack_results.return_value = [ar] - piece = make_mock_piece(conversation_id="attack-1") - piece.labels = {"env": "prod", "team": "red"} - mock_memory.get_message_pieces.return_value = [piece] + mock_memory.get_conversation_stats.return_value = { + "attack-1": ConversationStats( + message_count=1, + last_message_preview="test", + labels={"env": "prod", "team": "red"}, + ), + } result = await attack_service.list_attacks_async() assert len(result.items) == 1 assert result.items[0].labels == {"env": "prod", "team": "red"} + @pytest.mark.asyncio + async def test_list_attacks_filters_by_labels_directly(self, attack_service, mock_memory) -> None: + """Test that label filters are passed directly to the DB query (no legacy expansion).""" + ar = make_attack_result(conversation_id="attack-canonical") + + mock_memory.get_attack_results.return_value = [ar] + mock_memory.get_conversation_stats.side_effect = lambda conversation_ids: { + cid: ConversationStats(message_count=1, labels={"operator": "alice", "operation": "red"}) + for cid in conversation_ids + } + + result = await attack_service.list_attacks_async(labels={"operator": "alice", "operation": "red"}) + + assert len(result.items) == 1 + mock_memory.get_attack_results.assert_called_once() + call_kwargs = mock_memory.get_attack_results.call_args[1] + assert call_kwargs["labels"] == {"operator": "alice", "operation": "red"} + @pytest.mark.asyncio async def test_list_attacks_combined_min_and_max_turns(self, attack_service, mock_memory) -> None: """Test that list_attacks filters by both min_turns and max_turns together.""" @@ -324,22 +365,22 @@ class TestAttackOptions: @pytest.mark.asyncio async def test_returns_empty_when_no_attacks(self, attack_service, mock_memory) -> None: """Test that attack options returns empty list when no attacks exist.""" - mock_memory.get_unique_attack_class_names.return_value = [] + mock_memory.get_unique_attack_type_names.return_value = [] result = await attack_service.get_attack_options_async() assert result == [] - mock_memory.get_unique_attack_class_names.assert_called_once() + mock_memory.get_unique_attack_type_names.assert_called_once() @pytest.mark.asyncio async def test_returns_result_from_memory(self, attack_service, mock_memory) -> None: """Test that attack options delegates to memory layer.""" - mock_memory.get_unique_attack_class_names.return_value = ["CrescendoAttack", "ManualAttack"] + mock_memory.get_unique_attack_type_names.return_value = ["CrescendoAttack", "ManualAttack"] result = await attack_service.get_attack_options_async() assert result == ["CrescendoAttack", "ManualAttack"] - mock_memory.get_unique_attack_class_names.assert_called_once() + mock_memory.get_unique_attack_type_names.assert_called_once() # ============================================================================ @@ -354,22 +395,22 @@ class TestConverterOptions: @pytest.mark.asyncio async def test_returns_empty_when_no_attacks(self, attack_service, mock_memory) -> None: """Test that converter options returns empty list when no attacks exist.""" - mock_memory.get_unique_converter_class_names.return_value = [] + mock_memory.get_unique_converter_type_names.return_value = [] result = await attack_service.get_converter_options_async() assert result == [] - mock_memory.get_unique_converter_class_names.assert_called_once() + mock_memory.get_unique_converter_type_names.assert_called_once() @pytest.mark.asyncio async def test_returns_result_from_memory(self, attack_service, mock_memory) -> None: """Test that converter options delegates to memory layer.""" - mock_memory.get_unique_converter_class_names.return_value = ["Base64Converter", "ROT13Converter"] + mock_memory.get_unique_converter_type_names.return_value = ["Base64Converter", "ROT13Converter"] result = await attack_service.get_converter_options_async() assert result == ["Base64Converter", "ROT13Converter"] - mock_memory.get_unique_converter_class_names.assert_called_once() + mock_memory.get_unique_converter_type_names.assert_called_once() # ============================================================================ @@ -386,7 +427,7 @@ async def test_get_attack_returns_none_for_nonexistent(self, attack_service, moc """Test that get_attack returns None when AttackResult doesn't exist.""" mock_memory.get_attack_results.return_value = [] - result = await attack_service.get_attack_async(conversation_id="nonexistent") + result = await attack_service.get_attack_async(attack_result_id="nonexistent") assert result is None @@ -400,7 +441,7 @@ async def test_get_attack_returns_attack_details(self, attack_service, mock_memo mock_memory.get_attack_results.return_value = [ar] mock_memory.get_conversation.return_value = [] - result = await attack_service.get_attack_async(conversation_id="test-id") + result = await attack_service.get_attack_async(attack_result_id="test-id") assert result is not None assert result.conversation_id == "test-id" @@ -408,36 +449,53 @@ async def test_get_attack_returns_attack_details(self, attack_service, mock_memo # ============================================================================ -# Get Attack Messages Tests +# Get Conversation Messages Tests # ============================================================================ @pytest.mark.usefixtures("patch_central_database") -class TestGetAttackMessages: - """Tests for get_attack_messages method.""" +class TestGetConversationMessages: + """Tests for get_conversation_messages method.""" @pytest.mark.asyncio - async def test_get_attack_messages_returns_none_for_nonexistent(self, attack_service, mock_memory) -> None: - """Test that get_attack_messages returns None when attack doesn't exist.""" + async def test_get_conversation_messages_returns_none_for_nonexistent(self, attack_service, mock_memory) -> None: + """Test that get_conversation_messages returns None when attack doesn't exist.""" mock_memory.get_attack_results.return_value = [] - result = await attack_service.get_attack_messages_async(conversation_id="nonexistent") + result = await attack_service.get_conversation_messages_async( + attack_result_id="nonexistent", conversation_id="any-id" + ) assert result is None @pytest.mark.asyncio - async def test_get_attack_messages_returns_messages(self, attack_service, mock_memory) -> None: - """Test that get_attack_messages returns messages for existing attack.""" + async def test_get_conversation_messages_returns_messages(self, attack_service, mock_memory) -> None: + """Test that get_conversation_messages returns messages for existing attack.""" ar = make_attack_result(conversation_id="test-id") mock_memory.get_attack_results.return_value = [ar] mock_memory.get_conversation.return_value = [] - result = await attack_service.get_attack_messages_async(conversation_id="test-id") + result = await attack_service.get_conversation_messages_async( + attack_result_id="test-id", conversation_id="test-id" + ) assert result is not None assert result.conversation_id == "test-id" assert result.messages == [] + @pytest.mark.asyncio + async def test_get_conversation_messages_raises_for_unrelated_conversation( + self, attack_service, mock_memory + ) -> None: + """Test that get_conversation_messages raises ValueError for a conversation not belonging to the attack.""" + ar = make_attack_result(conversation_id="test-id") + mock_memory.get_attack_results.return_value = [ar] + + with pytest.raises(ValueError, match="not part of attack"): + await attack_service.get_conversation_messages_async( + attack_result_id="test-id", conversation_id="other-conv" + ) + # ============================================================================ # Create Attack Tests @@ -457,7 +515,9 @@ async def test_create_attack_validates_target_exists(self, attack_service) -> No mock_get_target_service.return_value = mock_target_service with pytest.raises(ValueError, match="not found"): - await attack_service.create_attack_async(request=CreateAttackRequest(target_unique_name="nonexistent")) + await attack_service.create_attack_async( + request=CreateAttackRequest(target_registry_name="nonexistent") + ) @pytest.mark.asyncio async def test_create_attack_stores_attack_result(self, attack_service, mock_memory) -> None: @@ -473,7 +533,7 @@ async def test_create_attack_stores_attack_result(self, attack_service, mock_mem mock_get_target_service.return_value = mock_target_service result = await attack_service.create_attack_async( - request=CreateAttackRequest(target_unique_name="target-1", name="My Attack") + request=CreateAttackRequest(target_registry_name="target-1", name="My Attack") ) assert result.conversation_id is not None @@ -501,7 +561,7 @@ async def test_create_attack_stores_prepended_conversation(self, attack_service, ] result = await attack_service.create_attack_async( - request=CreateAttackRequest(target_unique_name="target-1", prepended_conversation=prepended) + request=CreateAttackRequest(target_registry_name="target-1", prepended_conversation=prepended) ) assert result.conversation_id is not None @@ -524,7 +584,7 @@ async def test_create_attack_does_not_store_labels_in_metadata(self, attack_serv await attack_service.create_attack_async( request=CreateAttackRequest( - target_unique_name="target-1", + target_registry_name="target-1", name="Labeled Attack", labels={"env": "prod", "team": "red"}, ) @@ -556,7 +616,7 @@ async def test_create_attack_stamps_labels_on_prepended_pieces(self, attack_serv await attack_service.create_attack_async( request=CreateAttackRequest( - target_unique_name="target-1", + target_registry_name="target-1", labels={"env": "prod"}, prepended_conversation=prepended, ) @@ -609,7 +669,7 @@ async def test_create_attack_prepended_messages_have_incrementing_sequences( ] await attack_service.create_attack_async( - request=CreateAttackRequest(target_unique_name="target-1", prepended_conversation=prepended) + request=CreateAttackRequest(target_registry_name="target-1", prepended_conversation=prepended) ) # Each message stored separately with incrementing sequence @@ -655,7 +715,7 @@ async def test_create_attack_preserves_user_supplied_source_label(self, attack_s await attack_service.create_attack_async( request=CreateAttackRequest( - target_unique_name="target-1", + target_registry_name="target-1", labels={"source": "api-test"}, prepended_conversation=prepended, ) @@ -677,7 +737,7 @@ async def test_create_attack_default_name(self, attack_service, mock_memory) -> mock_target_service.get_target_object.return_value = mock_target_obj mock_get_target_service.return_value = mock_target_service - await attack_service.create_attack_async(request=CreateAttackRequest(target_unique_name="target-1")) + await attack_service.create_attack_async(request=CreateAttackRequest(target_registry_name="target-1")) call_args = mock_memory.add_attack_results_to_memory.call_args stored_ar = call_args[1]["attack_results"][0] @@ -700,7 +760,7 @@ async def test_update_attack_returns_none_for_nonexistent(self, attack_service, mock_memory.get_attack_results.return_value = [] result = await attack_service.update_attack_async( - conversation_id="nonexistent", request=UpdateAttackRequest(outcome="success") + attack_result_id="nonexistent", request=UpdateAttackRequest(outcome="success") ) assert result is None @@ -713,11 +773,13 @@ async def test_update_attack_updates_outcome_success(self, attack_service, mock_ mock_memory.get_conversation.return_value = [] await attack_service.update_attack_async( - conversation_id="test-id", request=UpdateAttackRequest(outcome="success") + attack_result_id="test-id", request=UpdateAttackRequest(outcome="success") ) - stored_ar = mock_memory.add_attack_results_to_memory.call_args[1]["attack_results"][0] - assert stored_ar.outcome == AttackOutcome.SUCCESS + mock_memory.update_attack_result_by_id.assert_called_once() + call_kwargs = mock_memory.update_attack_result_by_id.call_args[1] + assert call_kwargs["attack_result_id"] == "test-id" + assert call_kwargs["update_fields"]["outcome"] == "success" @pytest.mark.asyncio async def test_update_attack_updates_outcome_failure(self, attack_service, mock_memory) -> None: @@ -727,11 +789,11 @@ async def test_update_attack_updates_outcome_failure(self, attack_service, mock_ mock_memory.get_conversation.return_value = [] await attack_service.update_attack_async( - conversation_id="test-id", request=UpdateAttackRequest(outcome="failure") + attack_result_id="test-id", request=UpdateAttackRequest(outcome="failure") ) - stored_ar = mock_memory.add_attack_results_to_memory.call_args[1]["attack_results"][0] - assert stored_ar.outcome == AttackOutcome.FAILURE + call_kwargs = mock_memory.update_attack_result_by_id.call_args[1] + assert call_kwargs["update_fields"]["outcome"] == "failure" @pytest.mark.asyncio async def test_update_attack_updates_outcome_undetermined(self, attack_service, mock_memory) -> None: @@ -741,11 +803,11 @@ async def test_update_attack_updates_outcome_undetermined(self, attack_service, mock_memory.get_conversation.return_value = [] await attack_service.update_attack_async( - conversation_id="test-id", request=UpdateAttackRequest(outcome="undetermined") + attack_result_id="test-id", request=UpdateAttackRequest(outcome="undetermined") ) - stored_ar = mock_memory.add_attack_results_to_memory.call_args[1]["attack_results"][0] - assert stored_ar.outcome == AttackOutcome.UNDETERMINED + call_kwargs = mock_memory.update_attack_result_by_id.call_args[1] + assert call_kwargs["update_fields"]["outcome"] == "undetermined" @pytest.mark.asyncio async def test_update_attack_refreshes_updated_at(self, attack_service, mock_memory) -> None: @@ -756,11 +818,11 @@ async def test_update_attack_refreshes_updated_at(self, attack_service, mock_mem mock_memory.get_conversation.return_value = [] await attack_service.update_attack_async( - conversation_id="test-id", request=UpdateAttackRequest(outcome="success") + attack_result_id="test-id", request=UpdateAttackRequest(outcome="success") ) - stored_ar = mock_memory.add_attack_results_to_memory.call_args[1]["attack_results"][0] - assert stored_ar.metadata["updated_at"] != old_time.isoformat() + call_kwargs = mock_memory.update_attack_result_by_id.call_args[1] + assert call_kwargs["update_fields"]["attack_metadata"]["updated_at"] != old_time.isoformat() # ============================================================================ @@ -779,10 +841,11 @@ async def test_add_message_raises_for_nonexistent_attack(self, attack_service, m request = AddMessageRequest( pieces=[MessagePieceRequest(original_value="Hello")], + target_conversation_id="test-id", ) with pytest.raises(ValueError, match="not found"): - await attack_service.add_message_async(conversation_id="nonexistent", request=request) + await attack_service.add_message_async(attack_result_id="nonexistent", request=request) @pytest.mark.asyncio async def test_add_message_without_send_stamps_labels_on_pieces(self, attack_service, mock_memory) -> None: @@ -798,10 +861,11 @@ async def test_add_message_without_send_stamps_labels_on_pieces(self, attack_ser request = AddMessageRequest( role="user", pieces=[MessagePieceRequest(original_value="Hello")], + target_conversation_id="test-id", send=False, ) - result = await attack_service.add_message_async(conversation_id="test-id", request=request) + result = await attack_service.add_message_async(attack_result_id="test-id", request=request) stored_piece = mock_memory.add_message_pieces_to_memory.call_args[1]["message_pieces"][0] assert stored_piece.labels == {"env": "prod"} @@ -823,7 +887,7 @@ async def test_add_message_with_send_passes_labels_to_normalizer(self, attack_se patch("pyrit.backend.services.attack_service.PromptNormalizer") as mock_normalizer_cls, ): mock_target_svc = MagicMock() - mock_target_svc.get_target_object.return_value = MagicMock() + mock_target_svc.get_target_object.return_value = _make_matching_target_mock() mock_get_target_svc.return_value = mock_target_svc mock_normalizer = MagicMock() @@ -832,29 +896,51 @@ async def test_add_message_with_send_passes_labels_to_normalizer(self, attack_se request = AddMessageRequest( pieces=[MessagePieceRequest(original_value="Hello")], + target_conversation_id="test-id", send=True, + target_registry_name="test-target", ) - await attack_service.add_message_async(conversation_id="test-id", request=request) + await attack_service.add_message_async(attack_result_id="test-id", request=request) call_kwargs = mock_normalizer.send_prompt_async.call_args[1] assert call_kwargs["labels"] == {"env": "staging"} @pytest.mark.asyncio - async def test_add_message_raises_when_no_target_id(self, attack_service, mock_memory) -> None: - """Test that add_message raises ValueError when attack has no target configured.""" - ar = make_attack_result(conversation_id="test-id", has_target=False) + async def test_add_message_raises_when_send_without_registry_name(self, attack_service, mock_memory) -> None: + """Test that add_message raises ValueError when send=True but target_registry_name missing.""" + ar = make_attack_result(conversation_id="test-id") mock_memory.get_attack_results.return_value = [ar] request = AddMessageRequest( pieces=[MessagePieceRequest(original_value="Hello")], + target_conversation_id="test-id", + send=True, ) - with pytest.raises(ValueError, match="has no target configured"): - await attack_service.add_message_async(conversation_id="test-id", request=request) + with pytest.raises(ValueError, match="target_registry_name is required when send=True"): + await attack_service.add_message_async(attack_result_id="test-id", request=request) @pytest.mark.asyncio - async def test_add_message_with_send_calls_normalizer(self, attack_service, mock_memory) -> None: + async def test_add_message_send_false_without_registry_name_succeeds(self, attack_service, mock_memory) -> None: + """Test that add_message with send=False does not require target_registry_name.""" + ar = make_attack_result(conversation_id="test-id") + mock_memory.get_attack_results.return_value = [ar] + mock_memory.get_message_pieces.return_value = [] + mock_memory.get_conversation.return_value = [] + + request = AddMessageRequest( + role="system", + pieces=[MessagePieceRequest(original_value="Hello")], + target_conversation_id="test-id", + send=False, + ) + + result = await attack_service.add_message_async(attack_result_id="test-id", request=request) + assert result.attack is not None + + @pytest.mark.asyncio + async def test_add_message_with_send_sends_via_normalizer(self, attack_service, mock_memory) -> None: """Test that add_message with send=True sends message via normalizer.""" ar = make_attack_result(conversation_id="test-id") mock_memory.get_attack_results.return_value = [ar] @@ -866,7 +952,7 @@ async def test_add_message_with_send_calls_normalizer(self, attack_service, mock patch("pyrit.backend.services.attack_service.PromptNormalizer") as mock_normalizer_cls, ): mock_target_svc = MagicMock() - mock_target_svc.get_target_object.return_value = MagicMock() + mock_target_svc.get_target_object.return_value = _make_matching_target_mock() mock_get_target_svc.return_value = mock_target_svc mock_normalizer = MagicMock() @@ -875,10 +961,12 @@ async def test_add_message_with_send_calls_normalizer(self, attack_service, mock request = AddMessageRequest( pieces=[MessagePieceRequest(original_value="Hello")], + target_conversation_id="test-id", send=True, + target_registry_name="test-target", ) - result = await attack_service.add_message_async(conversation_id="test-id", request=request) + result = await attack_service.add_message_async(attack_result_id="test-id", request=request) mock_normalizer.send_prompt_async.assert_called_once() assert result.attack is not None @@ -897,11 +985,13 @@ async def test_add_message_with_send_raises_when_target_not_found(self, attack_s request = AddMessageRequest( pieces=[MessagePieceRequest(original_value="Hello")], + target_conversation_id="test-id", send=True, + target_registry_name="test-target", ) with pytest.raises(ValueError, match="Target object .* not found"): - await attack_service.add_message_async(conversation_id="test-id", request=request) + await attack_service.add_message_async(attack_result_id="test-id", request=request) @pytest.mark.asyncio async def test_add_message_with_converter_ids_gets_converters(self, attack_service, mock_memory) -> None: @@ -918,11 +1008,17 @@ async def test_add_message_with_converter_ids_gets_converters(self, attack_servi patch("pyrit.backend.services.attack_service.PromptConverterConfiguration") as mock_config, ): mock_target_svc = MagicMock() - mock_target_svc.get_target_object.return_value = MagicMock() + mock_target_svc.get_target_object.return_value = _make_matching_target_mock() mock_get_target_svc.return_value = mock_target_svc mock_conv_svc = MagicMock() - mock_conv_svc.get_converter_objects_for_ids.return_value = [MagicMock()] + mock_converter = MagicMock() + mock_converter.get_identifier.return_value = ComponentIdentifier( + class_name="TestConverter", + class_module="test_module", + params={"supported_input_types": ("text",), "supported_output_types": ("text",)}, + ) + mock_conv_svc.get_converter_objects_for_ids.return_value = [mock_converter] mock_get_conv_svc.return_value = mock_conv_svc mock_config.from_converters.return_value = [MagicMock()] @@ -933,13 +1029,15 @@ async def test_add_message_with_converter_ids_gets_converters(self, attack_servi request = AddMessageRequest( pieces=[MessagePieceRequest(original_value="Hello")], + target_conversation_id="test-id", send=True, converter_ids=["conv-1"], + target_registry_name="test-target", ) - await attack_service.add_message_async(conversation_id="test-id", request=request) + await attack_service.add_message_async(attack_result_id="test-id", request=request) - mock_conv_svc.get_converter_objects_for_ids.assert_called_once_with(converter_ids=["conv-1"]) + mock_conv_svc.get_converter_objects_for_ids.assert_any_call(converter_ids=["conv-1"]) @pytest.mark.asyncio async def test_add_message_raises_when_attack_not_found_after_update(self, attack_service, mock_memory) -> None: @@ -952,12 +1050,13 @@ async def test_add_message_raises_when_attack_not_found_after_update(self, attac request = AddMessageRequest( role="system", pieces=[MessagePieceRequest(original_value="Hello")], + target_conversation_id="test-id", send=False, ) with patch.object(attack_service, "get_attack_async", new=AsyncMock(return_value=None)): with pytest.raises(ValueError, match="not found after update"): - await attack_service.add_message_async(conversation_id="test-id", request=request) + await attack_service.add_message_async(attack_result_id="test-id", request=request) @pytest.mark.asyncio async def test_add_message_raises_when_messages_not_found_after_update(self, attack_service, mock_memory) -> None: @@ -970,33 +1069,70 @@ async def test_add_message_raises_when_messages_not_found_after_update(self, att request = AddMessageRequest( role="system", pieces=[MessagePieceRequest(original_value="Hello")], + target_conversation_id="test-id", send=False, ) with ( patch.object(attack_service, "get_attack_async", new=AsyncMock(return_value=MagicMock())), - patch.object(attack_service, "get_attack_messages_async", new=AsyncMock(return_value=None)), + patch.object(attack_service, "get_conversation_messages_async", new=AsyncMock(return_value=None)), ): with pytest.raises(ValueError, match="messages not found after update"): - await attack_service.add_message_async(conversation_id="test-id", request=request) + await attack_service.add_message_async(attack_result_id="test-id", request=request) @pytest.mark.asyncio - async def test_get_converter_configs_skips_when_preconverted(self, attack_service, mock_memory) -> None: - """Test that _get_converter_configs returns [] when pieces have converted_value set.""" + async def test_add_message_persists_updated_at_timestamp(self, attack_service, mock_memory) -> None: + """Should persist updated_at in attack_metadata via update_attack_result.""" ar = make_attack_result(conversation_id="test-id") + ar.metadata = {"created_at": "2026-01-01T00:00:00+00:00"} mock_memory.get_attack_results.return_value = [ar] mock_memory.get_message_pieces.return_value = [] mock_memory.get_conversation.return_value = [] + request = AddMessageRequest( + role="user", + pieces=[MessagePieceRequest(original_value="Hello")], + target_conversation_id="test-id", + send=False, + ) + + await attack_service.add_message_async(attack_result_id="test-id", request=request) + + mock_memory.update_attack_result_by_id.assert_called_once() + call_kwargs = mock_memory.update_attack_result_by_id.call_args[1] + assert call_kwargs["attack_result_id"] == "test-id" + persisted_metadata = call_kwargs["update_fields"]["attack_metadata"] + assert "updated_at" in persisted_metadata + assert persisted_metadata["created_at"] == "2026-01-01T00:00:00+00:00" + + @pytest.mark.asyncio + async def test_converter_ids_propagate_even_when_preconverted(self, attack_service, mock_memory) -> None: + """Test that converter identifiers propagate to attack_identifier even when pieces are preconverted.""" + ar = make_attack_result(conversation_id="test-id") + mock_memory.get_attack_results.return_value = [ar] + mock_memory.get_message_pieces.return_value = [] + mock_memory.get_conversation.return_value = [] + + mock_converter = MagicMock() + mock_converter.get_identifier.return_value = ComponentIdentifier( + class_name="Base64Converter", + class_module="pyrit.prompt_converter", + params={"supported_input_types": ("text",), "supported_output_types": ("text",)}, + ) + with ( patch("pyrit.backend.services.attack_service.get_target_service") as mock_get_target_svc, patch("pyrit.backend.services.attack_service.get_converter_service") as mock_get_conv_svc, patch("pyrit.backend.services.attack_service.PromptNormalizer") as mock_normalizer_cls, ): mock_target_svc = MagicMock() - mock_target_svc.get_target_object.return_value = MagicMock() + mock_target_svc.get_target_object.return_value = _make_matching_target_mock() mock_get_target_svc.return_value = mock_target_svc + mock_conv_svc = MagicMock() + mock_conv_svc.get_converter_objects_for_ids.return_value = [mock_converter] + mock_get_conv_svc.return_value = mock_conv_svc + mock_normalizer = MagicMock() mock_normalizer.send_prompt_async = AsyncMock() mock_normalizer_cls.return_value = mock_normalizer @@ -1004,20 +1140,68 @@ async def test_get_converter_configs_skips_when_preconverted(self, attack_servic request = AddMessageRequest( pieces=[MessagePieceRequest(original_value="Hello", converted_value="SGVsbG8=")], send=True, + target_conversation_id="test-id", converter_ids=["conv-1"], + target_registry_name="test-target", ) - await attack_service.add_message_async(conversation_id="test-id", request=request) + await attack_service.add_message_async(attack_result_id="test-id", request=request) - # Converter service should NOT be called since pieces are preconverted - mock_get_conv_svc.assert_not_called() - # Normalizer should still be called with empty converter configs + # Converter service IS called to resolve identifiers for the attack_identifier + mock_get_conv_svc.assert_called() + # Normalizer should still get empty converter configs since pieces are preconverted call_kwargs = mock_normalizer.send_prompt_async.call_args[1] assert call_kwargs["request_converter_configurations"] == [] + # attack_identifier should be updated with converter identifiers + update_call = mock_memory.update_attack_result_by_id.call_args[1] + assert "attack_identifier" in update_call["update_fields"] + + @pytest.mark.asyncio + async def test_add_message_no_existing_pieces_uses_request_labels(self, attack_service, mock_memory) -> None: + """Test that add_message with no existing pieces falls back to request.labels.""" + ar = make_attack_result(conversation_id="test-id") + mock_memory.get_attack_results.return_value = [ar] + mock_memory.get_message_pieces.return_value = [] # No existing pieces + mock_memory.get_conversation.return_value = [] + + request = AddMessageRequest( + role="user", + pieces=[MessagePieceRequest(original_value="Hello")], + target_conversation_id="test-id", + send=False, + labels={"env": "prod", "source": "gui"}, + ) + + result = await attack_service.add_message_async(attack_result_id="test-id", request=request) + + stored_piece = mock_memory.add_message_pieces_to_memory.call_args[1]["message_pieces"][0] + assert stored_piece.labels == {"env": "prod", "source": "gui"} + assert result.attack is not None + + @pytest.mark.asyncio + async def test_add_message_no_existing_pieces_uses_request_labels_as_is(self, attack_service, mock_memory) -> None: + """Test that add_message passes request labels through as-is when stamping new pieces.""" + ar = make_attack_result(conversation_id="test-id") + mock_memory.get_attack_results.return_value = [ar] + mock_memory.get_message_pieces.return_value = [] + mock_memory.get_conversation.return_value = [] + + request = AddMessageRequest( + role="user", + pieces=[MessagePieceRequest(original_value="Hello")], + target_conversation_id="test-id", + send=False, + labels={"operator": "alice", "operation": "red"}, + ) + + await attack_service.add_message_async(attack_result_id="test-id", request=request) + + stored_piece = mock_memory.add_message_pieces_to_memory.call_args[1]["message_pieces"][0] + assert stored_piece.labels == {"operator": "alice", "operation": "red"} @pytest.mark.asyncio - async def test_add_message_no_existing_pieces_labels_none(self, attack_service, mock_memory) -> None: - """Test that add_message with no existing pieces passes labels=None to storage.""" + async def test_add_message_no_existing_pieces_no_request_labels(self, attack_service, mock_memory) -> None: + """Test that add_message with no existing pieces and no request.labels passes None.""" ar = make_attack_result(conversation_id="test-id") mock_memory.get_attack_results.return_value = [ar] mock_memory.get_message_pieces.return_value = [] # No existing pieces @@ -1026,13 +1210,13 @@ async def test_add_message_no_existing_pieces_labels_none(self, attack_service, request = AddMessageRequest( role="user", pieces=[MessagePieceRequest(original_value="Hello")], + target_conversation_id="test-id", send=False, ) - result = await attack_service.add_message_async(conversation_id="test-id", request=request) + result = await attack_service.add_message_async(attack_result_id="test-id", request=request) stored_piece = mock_memory.add_message_pieces_to_memory.call_args[1]["message_pieces"][0] - # No labels inherited from existing pieces (no existing pieces had labels) assert stored_piece.labels is None or stored_piece.labels == {} assert result.attack is not None @@ -1092,24 +1276,25 @@ async def test_list_attacks_cursor_skips_to_correct_position(self, attack_servic mock_memory.get_attack_results.return_value = [ar1, ar2, ar3] mock_memory.get_message_pieces.return_value = [] - # Cursor = attack-1 should skip attack-1 and return from attack-2 onward - result = await attack_service.list_attacks_async(cursor="attack-1", limit=10) + # Cursor = ar-attack-1 should skip attack-1 and return from attack-2 onward + result = await attack_service.list_attacks_async(cursor="ar-attack-1", limit=10) attack_ids = [item.conversation_id for item in result.items] assert "attack-1" not in attack_ids assert len(result.items) == 2 @pytest.mark.asyncio - async def test_list_attacks_fetches_pieces_only_for_page(self, attack_service, mock_memory) -> None: - """Test that pieces are fetched only for the paginated page, not all attacks.""" + async def test_list_attacks_uses_conversation_stats_not_pieces(self, attack_service, mock_memory) -> None: + """Test that list_attacks uses get_conversation_stats instead of loading full pieces.""" attacks = [make_attack_result(conversation_id=f"attack-{i}") for i in range(5)] mock_memory.get_attack_results.return_value = attacks - mock_memory.get_message_pieces.return_value = [] await attack_service.list_attacks_async(limit=2) - # get_message_pieces should be called only for the 2 items on the page, not all 5 - assert mock_memory.get_message_pieces.call_count == 2 + # get_conversation_stats should be called once (batched), not per-attack + mock_memory.get_conversation_stats.assert_called_once() + # get_message_pieces should NOT be called by list_attacks + mock_memory.get_message_pieces.assert_not_called() @pytest.mark.asyncio async def test_pagination_cursor_not_found_returns_from_start(self, attack_service, mock_memory) -> None: @@ -1145,7 +1330,7 @@ async def test_pagination_cursor_at_last_item_returns_empty(self, attack_service mock_memory.get_message_pieces.return_value = [] # Cursor = last sorted item (attack-2 has the oldest updated_at, so it's last) - result = await attack_service.list_attacks_async(cursor="attack-2", limit=10) + result = await attack_service.list_attacks_async(cursor="ar-attack-2", limit=10) assert len(result.items) == 0 assert result.pagination.has_more is False @@ -1162,7 +1347,7 @@ class TestMessageBuilding: @pytest.mark.asyncio async def test_get_attack_with_messages_translates_correctly(self, attack_service, mock_memory) -> None: - """Test that get_attack_messages translates PyRIT messages to backend format.""" + """Test that get_conversation_messages translates PyRIT messages to backend format.""" ar = make_attack_result(conversation_id="test-id") mock_memory.get_attack_results.return_value = [ar] @@ -1185,7 +1370,9 @@ async def test_get_attack_with_messages_translates_correctly(self, attack_servic mock_memory.get_conversation.return_value = [mock_msg] - result = await attack_service.get_attack_messages_async(conversation_id="test-id") + result = await attack_service.get_conversation_messages_async( + attack_result_id="test-id", conversation_id="test-id" + ) assert result is not None assert len(result.messages) == 1 @@ -1219,3 +1406,817 @@ def test_get_attack_service_returns_same_instance(self) -> None: service1 = get_attack_service() service2 = get_attack_service() assert service1 is service2 + + +# ============================================================================ +# Persist Base64 Pieces Tests +# ============================================================================ + + +@pytest.mark.usefixtures("patch_central_database") +class TestPersistBase64Pieces: + """Tests for _persist_base64_pieces helper.""" + + @pytest.mark.asyncio + async def test_text_pieces_are_unchanged(self, attack_service) -> None: + """Text pieces should not be modified.""" + request = AddMessageRequest( + role="user", + pieces=[MessagePieceRequest(data_type="text", original_value="hello")], + send=False, + target_conversation_id="test-id", + ) + await AttackService._persist_base64_pieces(request) + assert request.pieces[0].original_value == "hello" + + @pytest.mark.asyncio + async def test_image_piece_is_saved_to_file(self, attack_service) -> None: + """Base64 image data should be saved to disk and value replaced with file path.""" + request = AddMessageRequest( + role="user", + pieces=[ + MessagePieceRequest( + data_type="image_path", + original_value="aW1hZ2VkYXRh", # base64 for "imagedata" + mime_type="image/png", + ), + ], + send=False, + target_conversation_id="test-id", + ) + + mock_serializer = MagicMock() + mock_serializer.save_b64_image = AsyncMock() + mock_serializer.value = "/saved/image.png" + + with patch( + "pyrit.backend.services.attack_service.data_serializer_factory", + return_value=mock_serializer, + ) as factory_mock: + await AttackService._persist_base64_pieces(request) + + factory_mock.assert_called_once_with( + category="prompt-memory-entries", + data_type="image_path", + extension=".png", + ) + mock_serializer.save_b64_image.assert_awaited_once_with(data="aW1hZ2VkYXRh") + assert request.pieces[0].original_value == "/saved/image.png" + + @pytest.mark.asyncio + async def test_mixed_pieces_only_persists_non_text(self, attack_service) -> None: + """Only non-text pieces should be persisted; text pieces stay untouched.""" + request = AddMessageRequest( + role="user", + pieces=[ + MessagePieceRequest(data_type="text", original_value="describe this"), + MessagePieceRequest( + data_type="image_path", + original_value="base64data", + mime_type="image/jpeg", + ), + ], + send=False, + target_conversation_id="test-id", + ) + + mock_serializer = MagicMock() + mock_serializer.save_b64_image = AsyncMock() + mock_serializer.value = "/saved/photo.jpg" + + with patch( + "pyrit.backend.services.attack_service.data_serializer_factory", + return_value=mock_serializer, + ): + await AttackService._persist_base64_pieces(request) + + assert request.pieces[0].original_value == "describe this" + assert request.pieces[1].original_value == "/saved/photo.jpg" + + @pytest.mark.asyncio + async def test_unknown_mime_type_uses_bin_extension(self, attack_service) -> None: + """When mime_type is missing, .bin should be used as fallback extension.""" + request = AddMessageRequest( + role="user", + pieces=[ + MessagePieceRequest( + data_type="binary_path", + original_value="base64data", + ), + ], + send=False, + target_conversation_id="test-id", + ) + + mock_serializer = MagicMock() + mock_serializer.save_b64_image = AsyncMock() + mock_serializer.value = "/saved/file.bin" + + with patch( + "pyrit.backend.services.attack_service.data_serializer_factory", + return_value=mock_serializer, + ) as factory_mock: + await AttackService._persist_base64_pieces(request) + + factory_mock.assert_called_once_with( + category="prompt-memory-entries", + data_type="binary_path", + extension=".bin", + ) + + +# ============================================================================ +# Related Conversations Tests +# ============================================================================ + + +@pytest.mark.usefixtures("patch_central_database") +class TestGetConversations: + """Tests for get_conversations_async.""" + + @pytest.mark.asyncio + async def test_returns_none_when_attack_not_found(self, attack_service, mock_memory): + """Should return None when the attack doesn't exist.""" + mock_memory.get_attack_results.return_value = [] + + result = await attack_service.get_conversations_async(attack_result_id="missing") + + assert result is None + + @pytest.mark.asyncio + async def test_returns_main_conversation_only(self, attack_service, mock_memory): + """Should return only the main conversation when no related conversations exist.""" + ar = make_attack_result(conversation_id="attack-1") + mock_memory.get_attack_results.return_value = [ar] + mock_memory.get_conversation_stats.return_value = { + "attack-1": ConversationStats(message_count=2, last_message_preview="test"), + } + + result = await attack_service.get_conversations_async(attack_result_id="attack-1") + + assert result is not None + assert result.main_conversation_id == "attack-1" + assert len(result.conversations) == 1 + assert result.conversations[0].message_count == 2 + + @pytest.mark.asyncio + async def test_returns_main_and_related_conversations(self, attack_service, mock_memory): + """Should return main and PRUNED conversations sorted by timestamp.""" + from pyrit.models.conversation_reference import ConversationReference, ConversationType + + ar = make_attack_result(conversation_id="attack-1") + ar.related_conversations.add( + ConversationReference( + conversation_id="branch-1", + conversation_type=ConversationType.PRUNED, + description="Branch 1", + ) + ) + ar.related_conversations.add( + ConversationReference( + conversation_id="score-1", + conversation_type=ConversationType.SCORE, + description="Scoring conversation", + ) + ) + + mock_memory.get_attack_results.return_value = [ar] + + t1 = datetime(2026, 1, 1, 10, 0, 0, tzinfo=timezone.utc) + t2 = datetime(2026, 1, 1, 9, 30, 0, tzinfo=timezone.utc) # earlier than t1 + + mock_memory.get_conversation_stats.return_value = { + "attack-1": ConversationStats(message_count=1, last_message_preview="test", created_at=t1), + "branch-1": ConversationStats(message_count=2, last_message_preview="test", created_at=t2), + "score-1": ConversationStats(message_count=0), + } + + result = await attack_service.get_conversations_async(attack_result_id="attack-1") + + assert result is not None + assert result.main_conversation_id == "attack-1" + assert len(result.conversations) == 2 + + main_conv = next(c for c in result.conversations if c.conversation_id == "attack-1") + assert main_conv.message_count == 1 + assert main_conv.created_at is not None + + branch = next(c for c in result.conversations if c.conversation_id == "branch-1") + assert branch.message_count == 2 + + # Conversations should be sorted by created_at (branch-1 is earliest) + assert result.conversations[0].conversation_id == "branch-1" + assert result.conversations[1].conversation_id == "attack-1" + + +@pytest.mark.usefixtures("patch_central_database") +class TestCreateRelatedConversation: + """Tests for create_related_conversation_async.""" + + @pytest.mark.asyncio + async def test_returns_none_when_attack_not_found(self, attack_service, mock_memory): + """Should return None when the attack doesn't exist.""" + from pyrit.backend.models.attacks import CreateConversationRequest + + mock_memory.get_attack_results.return_value = [] + + result = await attack_service.create_related_conversation_async( + attack_result_id="missing", + request=CreateConversationRequest(), + ) + + assert result is None + + @pytest.mark.asyncio + async def test_creates_conversation_and_adds_to_related(self, attack_service, mock_memory): + """Should create a new conversation and add it to pruned_conversation_ids.""" + from pyrit.backend.models.attacks import CreateConversationRequest + + ar = make_attack_result(conversation_id="attack-1") + mock_memory.get_attack_results.return_value = [ar] + mock_memory.get_message_pieces.return_value = [] + + request = CreateConversationRequest() + + result = await attack_service.create_related_conversation_async( + attack_result_id="attack-1", + request=request, + ) + + assert result is not None + assert result.conversation_id is not None + assert result.conversation_id != "attack-1" + + # Should have called update_attack_result to persist in DB column + mock_memory.update_attack_result_by_id.assert_called_once() + call_kwargs = mock_memory.update_attack_result_by_id.call_args[1] + assert call_kwargs["attack_result_id"] == "attack-1" + assert result.conversation_id in call_kwargs["update_fields"]["pruned_conversation_ids"] + assert "updated_at" in call_kwargs["update_fields"]["attack_metadata"] + + +# ============================================================================ +# Change Main Conversation Tests +# ============================================================================ + + +@pytest.mark.usefixtures("patch_central_database") +class TestChangeMainConversation: + """Tests for change_main_conversation_async (promote related conversation to main).""" + + @pytest.mark.asyncio + async def test_returns_none_when_attack_not_found(self, attack_service, mock_memory): + """Should return None when the attack doesn't exist.""" + mock_memory.get_attack_results.return_value = [] + + result = await attack_service.change_main_conversation_async( + attack_result_id="missing", + request=ChangeMainConversationRequest(conversation_id="conv-1"), + ) + + assert result is None + + @pytest.mark.asyncio + async def test_noop_when_target_is_already_main(self, attack_service, mock_memory): + """When target is already the main conversation, return immediately without update.""" + ar = make_attack_result(conversation_id="attack-1") + mock_memory.get_attack_results.return_value = [ar] + + result = await attack_service.change_main_conversation_async( + attack_result_id="ar-attack-1", + request=ChangeMainConversationRequest(conversation_id="attack-1"), + ) + + assert result is not None + assert result.conversation_id == "attack-1" + mock_memory.update_attack_result_by_id.assert_not_called() + + @pytest.mark.asyncio + async def test_raises_when_conversation_not_part_of_attack(self, attack_service, mock_memory): + """Should raise ValueError when conversation is not in the attack.""" + ar = make_attack_result(conversation_id="attack-1") + mock_memory.get_attack_results.return_value = [ar] + + with pytest.raises(ValueError, match="not part of this attack"): + await attack_service.change_main_conversation_async( + attack_result_id="ar-attack-1", + request=ChangeMainConversationRequest(conversation_id="not-related"), + ) + + @pytest.mark.asyncio + async def test_swaps_main_conversation(self, attack_service, mock_memory): + """Changing the main to a related conversation should swap it with the main.""" + from pyrit.models.conversation_reference import ConversationReference, ConversationType + + ar = make_attack_result(conversation_id="attack-1") + ar.related_conversations = { + ConversationReference( + conversation_id="branch-1", + conversation_type=ConversationType.ADVERSARIAL, + description="Branch 1", + ), + } + mock_memory.get_attack_results.return_value = [ar] + + result = await attack_service.change_main_conversation_async( + attack_result_id="ar-attack-1", + request=ChangeMainConversationRequest(conversation_id="branch-1"), + ) + + assert result is not None + assert result.attack_result_id == "ar-attack-1" + assert result.conversation_id == "branch-1" + + # Should update via update_attack_result_by_id + mock_memory.update_attack_result_by_id.assert_called_once() + call_kwargs = mock_memory.update_attack_result_by_id.call_args[1] + assert call_kwargs["attack_result_id"] == "ar-attack-1" + assert call_kwargs["update_fields"]["conversation_id"] == "branch-1" + + # Old main should now be in adversarial_chat_conversation_ids + adversarial = call_kwargs["update_fields"]["adversarial_chat_conversation_ids"] + assert "attack-1" in adversarial + assert "branch-1" not in adversarial + + +@pytest.mark.usefixtures("patch_central_database") +class TestAddMessageTargetConversation: + """Tests for add_message_async with target_conversation_id.""" + + @pytest.mark.asyncio + async def test_stores_message_in_target_conversation(self, attack_service, mock_memory): + """When target_conversation_id is set, messages should go to that conversation.""" + from pyrit.backend.models.attacks import AttackSummary, ConversationMessagesResponse + + ar = make_attack_result(conversation_id="attack-1") + mock_memory.get_attack_results.return_value = [ar] + mock_memory.get_message_pieces.return_value = [] + mock_memory.get_conversation.return_value = [] + + request = AddMessageRequest( + role="user", + pieces=[MessagePieceRequest(data_type="text", original_value="Hello")], + send=False, + target_conversation_id="branch-1", + ) + + now = datetime.now(timezone.utc) + mock_summary = AttackSummary( + attack_result_id="ar-attack-1", + conversation_id="attack-1", + attack_type="ManualAttack", + converters=[], + message_count=1, + labels={}, + created_at=now, + updated_at=now, + ) + mock_messages = ConversationMessagesResponse( + conversation_id="branch-1", + messages=[], + ) + + with ( + patch.object(attack_service, "get_attack_async", return_value=mock_summary), + patch.object(attack_service, "get_conversation_messages_async", return_value=mock_messages) as mock_msgs, + ): + await attack_service.add_message_async(attack_result_id="attack-1", request=request) + + # get_conversation_messages_async should be called with conversation_id=branch-1 + mock_msgs.assert_called_once_with( + attack_result_id="attack-1", + conversation_id="branch-1", + ) + + +@pytest.mark.usefixtures("patch_central_database") +class TestConversationCount: + """Tests verifying conversation count is accurate in attack list.""" + + @pytest.mark.asyncio + async def test_list_attacks_includes_related_conversation_ids(self, attack_service, mock_memory): + """Attacks with related conversations should expose them in the summary.""" + from pyrit.models.conversation_reference import ConversationReference, ConversationType + + ar = make_attack_result(conversation_id="attack-1") + ar.related_conversations = { + ConversationReference( + conversation_id="branch-1", + conversation_type=ConversationType.ADVERSARIAL, + ), + ConversationReference( + conversation_id="branch-2", + conversation_type=ConversationType.ADVERSARIAL, + ), + } + mock_memory.get_attack_results.return_value = [ar] + mock_memory.get_message_pieces.return_value = [] + + result = await attack_service.list_attacks_async() + + assert len(result.items) == 1 + assert sorted(result.items[0].related_conversation_ids) == ["branch-1", "branch-2"] + + @pytest.mark.asyncio + async def test_list_attacks_no_related_returns_empty_list(self, attack_service, mock_memory): + """An attack with no related conversations should return empty list.""" + ar = make_attack_result(conversation_id="attack-1") + mock_memory.get_attack_results.return_value = [ar] + mock_memory.get_message_pieces.return_value = [] + + result = await attack_service.list_attacks_async() + + assert result.items[0].related_conversation_ids == [] + + @pytest.mark.asyncio + async def test_create_conversation_increments_count(self, attack_service, mock_memory): + """Creating a related conversation should add to pruned_conversation_ids.""" + from pyrit.backend.models.attacks import CreateConversationRequest + + ar = make_attack_result(conversation_id="attack-1") + mock_memory.get_attack_results.return_value = [ar] + mock_memory.get_message_pieces.return_value = [] + + result = await attack_service.create_related_conversation_async( + attack_result_id="attack-1", + request=CreateConversationRequest(), + ) + + call_kwargs = mock_memory.update_attack_result_by_id.call_args[1] + ids = call_kwargs["update_fields"]["pruned_conversation_ids"] + assert result.conversation_id in ids + assert len(ids) == 1 + + @pytest.mark.asyncio + async def test_create_second_conversation_preserves_first(self, attack_service, mock_memory): + """Creating a second related conversation should keep the first one.""" + from pyrit.backend.models.attacks import CreateConversationRequest + from pyrit.models.conversation_reference import ConversationReference, ConversationType + + ar = make_attack_result(conversation_id="attack-1") + ar.related_conversations = { + ConversationReference( + conversation_id="conv-existing", + conversation_type=ConversationType.PRUNED, + ), + } + mock_memory.get_attack_results.return_value = [ar] + mock_memory.get_message_pieces.return_value = [] + + result = await attack_service.create_related_conversation_async( + attack_result_id="attack-1", + request=CreateConversationRequest(), + ) + + call_kwargs = mock_memory.update_attack_result_by_id.call_args[1] + ids = call_kwargs["update_fields"]["pruned_conversation_ids"] + assert "conv-existing" in ids + assert result.conversation_id in ids + assert len(ids) == 2 + + +@pytest.mark.usefixtures("patch_central_database") +class TestConversationSorting: + """Tests verifying conversations are sorted correctly.""" + + @pytest.mark.asyncio + async def test_conversations_sorted_by_created_at_earliest_first(self, attack_service, mock_memory): + """Conversations should be sorted by created_at with earliest first.""" + from pyrit.models.conversation_reference import ConversationReference, ConversationType + + ar = make_attack_result(conversation_id="attack-1") + ar.related_conversations = { + ConversationReference( + conversation_id="branch-1", + conversation_type=ConversationType.PRUNED, + ), + } + mock_memory.get_attack_results.return_value = [ar] + + t_early = datetime(2026, 1, 1, 9, 0, 0, tzinfo=timezone.utc) + t_late = datetime(2026, 1, 1, 11, 0, 0, tzinfo=timezone.utc) + + mock_memory.get_conversation_stats.return_value = { + "attack-1": ConversationStats(message_count=1, last_message_preview="test", created_at=t_late), + "branch-1": ConversationStats(message_count=1, last_message_preview="test", created_at=t_early), + } + + result = await attack_service.get_conversations_async(attack_result_id="attack-1") + + assert result is not None + # branch-1 (earlier) should come before attack-1 (later) + assert result.conversations[0].conversation_id == "branch-1" + assert result.conversations[1].conversation_id == "attack-1" + + @pytest.mark.asyncio + async def test_empty_conversations_sorted_last(self, attack_service, mock_memory): + """Conversations with no timestamp should appear at the bottom.""" + from pyrit.models.conversation_reference import ConversationReference, ConversationType + + ar = make_attack_result(conversation_id="attack-1") + ar.related_conversations = { + ConversationReference( + conversation_id="empty-conv", + conversation_type=ConversationType.PRUNED, + ), + } + mock_memory.get_attack_results.return_value = [ar] + + t = datetime(2026, 1, 1, 9, 0, 0, tzinfo=timezone.utc) + + mock_memory.get_conversation_stats.return_value = { + "attack-1": ConversationStats(message_count=1, last_message_preview="test", created_at=t), + } + + result = await attack_service.get_conversations_async(attack_result_id="attack-1") + + assert result is not None + # attack-1 (has timestamp) should come before empty-conv (no timestamp) + assert result.conversations[0].conversation_id == "attack-1" + assert result.conversations[1].conversation_id == "empty-conv" + + @pytest.mark.asyncio + async def test_empty_conversations_all_sort_last(self, attack_service, mock_memory): + """Multiple empty conversations should all have created_at=None.""" + from pyrit.models.conversation_reference import ConversationReference, ConversationType + + ar = make_attack_result(conversation_id="attack-1") + ar.related_conversations = { + ConversationReference( + conversation_id="new-conv", + conversation_type=ConversationType.PRUNED, + ), + } + mock_memory.get_attack_results.return_value = [ar] + mock_memory.get_conversation_stats.return_value = {} # Both have no stats + + result = await attack_service.get_conversations_async(attack_result_id="attack-1") + + assert result is not None + # Both empty conversations should have created_at=None + for conv in result.conversations: + assert conv.created_at is None + + +@pytest.mark.usefixtures("patch_central_database") +class TestAttackServiceAdditionalCoverage: + """Targeted branch coverage tests for attack service helpers and converter merge logic.""" + + @pytest.mark.asyncio + async def test_create_related_conversation_uses_duplicate_branch(self, attack_service, mock_memory): + """When source_conversation_id and cutoff_index are provided, duplication path is used.""" + from pyrit.backend.models.attacks import CreateConversationRequest + + ar = make_attack_result(conversation_id="attack-1") + mock_memory.get_attack_results.return_value = [ar] + + with patch.object(attack_service, "_duplicate_conversation_up_to", return_value="branch-dup") as mock_dup: + result = await attack_service.create_related_conversation_async( + attack_result_id="attack-1", + request=CreateConversationRequest(source_conversation_id="attack-1", cutoff_index=2), + ) + + assert result is not None + assert result.conversation_id == "branch-dup" + mock_dup.assert_called_once_with(source_conversation_id="attack-1", cutoff_index=2) + + @pytest.mark.asyncio + async def test_add_message_merges_converter_identifiers_without_duplicates(self, attack_service, mock_memory): + """Should merge new converter identifiers with existing attack identifiers by hash.""" + from pyrit.backend.models.attacks import AttackSummary, ConversationMessagesResponse + + existing_converter = ComponentIdentifier( + class_name="ExistingConverter", + class_module="pyrit.prompt_converter", + params={"supported_input_types": ("text",), "supported_output_types": ("text",)}, + ) + duplicate_converter = ComponentIdentifier( + class_name="ExistingConverter", + class_module="pyrit.prompt_converter", + params={"supported_input_types": ("text",), "supported_output_types": ("text",)}, + ) + new_converter = ComponentIdentifier( + class_name="NewConverter", + class_module="pyrit.prompt_converter", + params={"supported_input_types": ("text",), "supported_output_types": ("text",)}, + ) + + ar = make_attack_result(conversation_id="attack-1") + ar.attack_identifier = ComponentIdentifier( + class_name="ManualAttack", + class_module="pyrit.backend", + children={ + "objective_target": ar.attack_identifier.get_child("objective_target"), + "request_converters": [existing_converter], + }, + ) + + mock_memory.get_attack_results.return_value = [ar] + mock_memory.get_message_pieces.return_value = [] + + request = AddMessageRequest( + role="user", + pieces=[MessagePieceRequest(original_value="Hello")], + target_conversation_id="attack-1", + send=False, + converter_ids=["c-1", "c-2"], + ) + + with ( + patch("pyrit.backend.services.attack_service.get_converter_service") as mock_get_converter_service, + patch.object( + attack_service, + "get_attack_async", + new=AsyncMock( + return_value=AttackSummary( + attack_result_id="ar-attack-1", + conversation_id="attack-1", + attack_type="ManualAttack", + converters=[], + message_count=0, + labels={}, + created_at=datetime.now(timezone.utc), + updated_at=datetime.now(timezone.utc), + ) + ), + ), + patch.object( + attack_service, + "get_conversation_messages_async", + new=AsyncMock(return_value=ConversationMessagesResponse(conversation_id="attack-1", messages=[])), + ), + ): + mock_converter_service = MagicMock() + mock_converter_service.get_converter_objects_for_ids.return_value = [ + MagicMock(get_identifier=MagicMock(return_value=duplicate_converter)), + MagicMock(get_identifier=MagicMock(return_value=new_converter)), + ] + mock_get_converter_service.return_value = mock_converter_service + + await attack_service.add_message_async(attack_result_id="attack-1", request=request) + + update_fields = mock_memory.update_attack_result_by_id.call_args[1]["update_fields"] + persisted_identifiers = update_fields["attack_identifier"]["children"]["request_converters"] + persisted_classes = [identifier["class_name"] for identifier in persisted_identifiers] + + assert persisted_classes.count("ExistingConverter") == 1 + assert persisted_classes.count("NewConverter") == 1 + + def test_get_last_message_preview_handles_truncation_and_empty_values(self, attack_service): + """Should truncate long previews and handle empty converted values.""" + short_piece = make_mock_piece(conversation_id="attack-1", sequence=1, converted_value="short") + long_piece = make_mock_piece(conversation_id="attack-1", sequence=2, converted_value="x" * 120) + + assert attack_service._get_last_message_preview([]) is None + assert attack_service._get_last_message_preview([short_piece]) == "short" + assert attack_service._get_last_message_preview([long_piece]) == ("x" * 100 + "...") + + def test_count_messages_and_earliest_timestamp_helpers(self, attack_service): + """Should count unique sequences and compute earliest non-null timestamp.""" + t1 = datetime(2026, 1, 1, 10, 0, 0, tzinfo=timezone.utc) + t2 = datetime(2026, 1, 1, 9, 0, 0, tzinfo=timezone.utc) + + p1 = make_mock_piece(conversation_id="attack-1", sequence=1, timestamp=t1) + p2 = make_mock_piece(conversation_id="attack-1", sequence=1, timestamp=t1) + p3 = make_mock_piece(conversation_id="attack-1", sequence=2, timestamp=t2) + p4 = make_mock_piece(conversation_id="attack-1", sequence=3, timestamp=t1) + p4.timestamp = None + + assert attack_service._count_messages([p1, p2, p3]) == 2 + assert attack_service._get_earliest_timestamp([]) is None + assert attack_service._get_earliest_timestamp([p4]) is None + assert attack_service._get_earliest_timestamp([p1, p3, p4]) == t2 + + def test_duplicate_conversation_up_to_adds_pieces_when_present(self, attack_service, mock_memory): + """Should duplicate up to cutoff and persist duplicated pieces only when returned.""" + source_messages = [ + make_mock_piece(conversation_id="attack-1", sequence=0), + make_mock_piece(conversation_id="attack-1", sequence=1), + make_mock_piece(conversation_id="attack-1", sequence=2), + ] + mock_memory.get_conversation.return_value = source_messages + duplicated_piece = make_mock_piece(conversation_id="branch-1", sequence=0) + mock_memory.duplicate_messages.return_value = ("branch-1", [duplicated_piece]) + + new_id = attack_service._duplicate_conversation_up_to(source_conversation_id="attack-1", cutoff_index=1) + + assert new_id == "branch-1" + passed_messages = mock_memory.duplicate_messages.call_args[1]["messages"] + assert [m.sequence for m in passed_messages] == [0, 1] + mock_memory.add_message_pieces_to_memory.assert_called_once() + + def test_duplicate_conversation_up_to_skips_persist_when_no_duplicated_pieces(self, attack_service, mock_memory): + """Should not write to memory when duplicate_messages returns no pieces.""" + mock_memory.get_conversation.return_value = [make_mock_piece(conversation_id="attack-1", sequence=0)] + mock_memory.duplicate_messages.return_value = ("branch-empty", []) + + new_id = attack_service._duplicate_conversation_up_to(source_conversation_id="attack-1", cutoff_index=10) + + assert new_id == "branch-empty" + mock_memory.add_message_pieces_to_memory.assert_not_called() + + +class TestAddMessageGuards: + """Tests for target-mismatch and operator-mismatch guards in add_message_async.""" + + @pytest.mark.asyncio + async def test_rejects_mismatched_target(self, attack_service, mock_memory) -> None: + """Should raise ValueError when request target differs from attack target.""" + ar = make_attack_result(conversation_id="test-id") + mock_memory.get_attack_results.return_value = [ar] + mock_memory.get_message_pieces.return_value = [] + + # Create a mock target with a different class_name + wrong_target = MagicMock() + wrong_target.get_identifier.return_value = ComponentIdentifier( + class_name="DifferentTarget", + class_module="pyrit.prompt_target", + ) + + with patch("pyrit.backend.services.attack_service.get_target_service") as mock_get_target_svc: + mock_target_svc = MagicMock() + mock_target_svc.get_target_object.return_value = wrong_target + mock_get_target_svc.return_value = mock_target_svc + + request = AddMessageRequest( + pieces=[MessagePieceRequest(original_value="Hello")], + target_conversation_id="test-id", + send=True, + target_registry_name="wrong-target", + ) + + with pytest.raises(ValueError, match="Target mismatch"): + await attack_service.add_message_async(attack_result_id="test-id", request=request) + + @pytest.mark.asyncio + async def test_allows_matching_target(self, attack_service, mock_memory) -> None: + """Should NOT raise when request target matches attack target.""" + ar = make_attack_result(conversation_id="test-id") + mock_memory.get_attack_results.return_value = [ar] + mock_memory.get_message_pieces.return_value = [] + mock_memory.get_conversation.return_value = [] + + with ( + patch("pyrit.backend.services.attack_service.get_target_service") as mock_get_target_svc, + patch("pyrit.backend.services.attack_service.PromptNormalizer") as mock_normalizer_cls, + ): + mock_target_svc = MagicMock() + mock_target_svc.get_target_object.return_value = _make_matching_target_mock() + mock_get_target_svc.return_value = mock_target_svc + + mock_normalizer = MagicMock() + mock_normalizer.send_prompt_async = AsyncMock() + mock_normalizer_cls.return_value = mock_normalizer + + request = AddMessageRequest( + pieces=[MessagePieceRequest(original_value="Hello")], + target_conversation_id="test-id", + send=True, + target_registry_name="test-target", + ) + + result = await attack_service.add_message_async(attack_result_id="test-id", request=request) + assert result.attack is not None + + @pytest.mark.asyncio + async def test_rejects_mismatched_operator(self, attack_service, mock_memory) -> None: + """Should raise ValueError when request operator differs from existing operator.""" + ar = make_attack_result(conversation_id="test-id") + mock_memory.get_attack_results.return_value = [ar] + + existing_piece = make_mock_piece(conversation_id="test-id") + existing_piece.labels = {"op_name": "alice"} + mock_memory.get_message_pieces.return_value = [existing_piece] + + request = AddMessageRequest( + role="user", + pieces=[MessagePieceRequest(original_value="Hello")], + target_conversation_id="test-id", + send=False, + labels={"op_name": "bob"}, + ) + + with pytest.raises(ValueError, match="Operator mismatch"): + await attack_service.add_message_async(attack_result_id="test-id", request=request) + + @pytest.mark.asyncio + async def test_allows_matching_operator(self, attack_service, mock_memory) -> None: + """Should NOT raise when request operator matches existing operator.""" + ar = make_attack_result(conversation_id="test-id") + mock_memory.get_attack_results.return_value = [ar] + + existing_piece = make_mock_piece(conversation_id="test-id") + existing_piece.labels = {"op_name": "alice"} + mock_memory.get_message_pieces.return_value = [existing_piece] + mock_memory.get_conversation.return_value = [] + + request = AddMessageRequest( + role="user", + pieces=[MessagePieceRequest(original_value="Hello")], + target_conversation_id="test-id", + send=False, + labels={"op_name": "alice"}, + ) + + result = await attack_service.add_message_async(attack_result_id="test-id", request=request) + assert result.attack is not None diff --git a/tests/unit/backend/test_main.py b/tests/unit/backend/test_main.py index 6bc21ceb3c..c4f12792c1 100644 --- a/tests/unit/backend/test_main.py +++ b/tests/unit/backend/test_main.py @@ -8,7 +8,7 @@ """ import os -from unittest.mock import AsyncMock, MagicMock, patch +from unittest.mock import MagicMock, patch import pytest @@ -19,28 +19,23 @@ class TestLifespan: """Tests for the application lifespan context manager.""" @pytest.mark.asyncio - async def test_lifespan_initializes_pyrit_and_yields(self) -> None: - """Test that lifespan calls initialize_pyrit_async on startup when memory is not set.""" - with ( - patch("pyrit.backend.main.CentralMemory._memory_instance", None), - patch("pyrit.backend.main.initialize_pyrit_async", new_callable=AsyncMock) as mock_init, - ): + async def test_lifespan_yields(self) -> None: + """Test that lifespan yields without performing initialization (handled by CLI).""" + with patch("pyrit.memory.CentralMemory._memory_instance", MagicMock()): async with lifespan(app): - pass # The body of the context manager is the "yield" phase - - mock_init.assert_awaited_once_with(memory_db_type="SQLite") + pass # Should complete without error @pytest.mark.asyncio - async def test_lifespan_skips_init_when_already_initialized(self) -> None: - """Test that lifespan skips initialization when CentralMemory is already set.""" + async def test_lifespan_warns_when_memory_not_initialized(self) -> None: + """Test that lifespan logs a warning when CentralMemory is not set.""" with ( - patch("pyrit.backend.main.CentralMemory._memory_instance", MagicMock()), - patch("pyrit.backend.main.initialize_pyrit_async", new_callable=AsyncMock) as mock_init, + patch("pyrit.memory.CentralMemory._memory_instance", None), + patch("logging.Logger.warning") as mock_warning, ): async with lifespan(app): pass - mock_init.assert_not_awaited() + mock_warning.assert_called_once() class TestSetupFrontend: diff --git a/tests/unit/backend/test_mappers.py b/tests/unit/backend/test_mappers.py index b62c37bc0a..463094ea2e 100644 --- a/tests/unit/backend/test_mappers.py +++ b/tests/unit/backend/test_mappers.py @@ -8,14 +8,22 @@ without any database or service dependencies. """ +import dataclasses +import os +import tempfile +import uuid +import pytest from datetime import datetime, timezone -from unittest.mock import MagicMock +from unittest.mock import AsyncMock, MagicMock, patch from pyrit.backend.mappers.attack_mappers import ( - _collect_labels_from_pieces, + _build_filename, + _fetch_blob_as_data_uri_async, _infer_mime_type, + _is_azure_blob_url, + _sign_blob_url_async, attack_result_to_summary, - pyrit_messages_to_dto, + pyrit_messages_to_dto_async, pyrit_scores_to_dto, request_piece_to_pyrit_message_piece, request_to_pyrit_message, @@ -24,6 +32,7 @@ from pyrit.backend.mappers.target_mappers import target_object_to_instance from pyrit.identifiers import ComponentIdentifier from pyrit.models import AttackOutcome, AttackResult +from pyrit.models.conversation_stats import ConversationStats # ============================================================================ # Helpers @@ -120,71 +129,85 @@ class TestAttackResultToSummary: def test_basic_mapping(self) -> None: """Test that all fields are mapped correctly.""" ar = _make_attack_result(name="My Attack") - pieces = [_make_mock_piece(sequence=0), _make_mock_piece(sequence=1)] + stats = ConversationStats(message_count=2) - summary = attack_result_to_summary(ar, pieces=pieces) + summary = attack_result_to_summary(ar, stats=stats) assert summary.conversation_id == ar.conversation_id assert summary.outcome == "undetermined" assert summary.message_count == 2 # Attack metadata should be extracted into explicit fields assert summary.attack_type == "My Attack" - assert summary.target_type == "TextTarget" - assert summary.target_unique_name is not None + assert summary.target is not None + assert summary.target.target_type == "TextTarget" def test_empty_pieces_gives_zero_messages(self) -> None: """Test mapping with no message pieces.""" ar = _make_attack_result() + stats = ConversationStats(message_count=0) - summary = attack_result_to_summary(ar, pieces=[]) + summary = attack_result_to_summary(ar, stats=stats) assert summary.message_count == 0 assert summary.last_message_preview is None def test_last_message_preview_truncated(self) -> None: - """Test that long messages are truncated to 100 chars + ellipsis.""" + """Test that long messages are truncated in stats.""" ar = _make_attack_result() long_text = "x" * 200 - pieces = [_make_mock_piece(converted_value=long_text)] + stats = ConversationStats(message_count=1, last_message_preview=long_text[:100] + "...") - summary = attack_result_to_summary(ar, pieces=pieces) + summary = attack_result_to_summary(ar, stats=stats) assert summary.last_message_preview is not None assert len(summary.last_message_preview) == 103 # 100 + "..." assert summary.last_message_preview.endswith("...") def test_labels_are_mapped(self) -> None: - """Test that labels are derived from pieces.""" + """Test that labels are derived from stats.""" ar = _make_attack_result() - piece = _make_mock_piece() - piece.labels = {"env": "prod", "team": "red"} + stats = ConversationStats(message_count=1, labels={"env": "prod", "team": "red"}) - summary = attack_result_to_summary(ar, pieces=[piece]) + summary = attack_result_to_summary(ar, stats=stats) assert summary.labels == {"env": "prod", "team": "red"} + def test_labels_passed_through_without_normalization(self) -> None: + """Test that labels are passed through as-is (DB stores canonical keys after migration).""" + ar = _make_attack_result() + stats = ConversationStats( + message_count=1, + labels={"operator": "alice", "operation": "op_red", "env": "prod"}, + ) + + summary = attack_result_to_summary(ar, stats=stats) + + assert summary.labels == {"operator": "alice", "operation": "op_red", "env": "prod"} + def test_outcome_success(self) -> None: """Test that success outcome is mapped.""" ar = _make_attack_result(outcome=AttackOutcome.SUCCESS) + stats = ConversationStats(message_count=0) - summary = attack_result_to_summary(ar, pieces=[]) + summary = attack_result_to_summary(ar, stats=stats) assert summary.outcome == "success" def test_no_target_returns_none_fields(self) -> None: """Test that target fields are None when no target identifier exists.""" ar = _make_attack_result(has_target=False) + stats = ConversationStats(message_count=0) - summary = attack_result_to_summary(ar, pieces=[]) + summary = attack_result_to_summary(ar, stats=stats) - assert summary.target_unique_name is None - assert summary.target_type is None + assert summary.target is None def test_attack_specific_params_passed_through(self) -> None: """Test that attack_specific_params are extracted from identifier.""" ar = _make_attack_result() + stats = ConversationStats(message_count=0) - summary = attack_result_to_summary(ar, pieces=[]) + summary = attack_result_to_summary(ar, stats=stats) assert summary.attack_specific_params == {"source": "gui"} @@ -222,20 +245,57 @@ def test_converters_extracted_from_identifier(self) -> None: metadata={"created_at": now.isoformat(), "updated_at": now.isoformat()}, ) - summary = attack_result_to_summary(ar, pieces=[]) + summary = attack_result_to_summary(ar, stats=ConversationStats(message_count=0)) assert summary.converters == ["Base64Converter", "ROT13Converter"] def test_no_converters_returns_empty_list(self) -> None: """Test that converters is empty list when no converters in identifier.""" ar = _make_attack_result() + stats = ConversationStats(message_count=0) - summary = attack_result_to_summary(ar, pieces=[]) + summary = attack_result_to_summary(ar, stats=stats) assert summary.converters == [] + def test_related_conversation_ids_from_related_conversations(self) -> None: + """Test that related_conversation_ids includes all related conversation IDs.""" + from pyrit.models.conversation_reference import ConversationReference, ConversationType + + ar = _make_attack_result() + ar.related_conversations = { + ConversationReference( + conversation_id="branch-1", + conversation_type=ConversationType.ADVERSARIAL, + ), + ConversationReference( + conversation_id="pruned-1", + conversation_type=ConversationType.PRUNED, + ), + } + + summary = attack_result_to_summary(ar, stats=ConversationStats(message_count=0)) + + assert sorted(summary.related_conversation_ids) == ["branch-1", "pruned-1"] + + def test_related_conversation_ids_empty_when_no_related(self) -> None: + """Test that related_conversation_ids is empty when no related conversations exist.""" + ar = _make_attack_result() + stats = ConversationStats(message_count=0) + + summary = attack_result_to_summary(ar, stats=stats) + + assert summary.related_conversation_ids == [] + + def test_message_count_from_stats(self) -> None: + """Test that message_count comes from stats.""" + ar = _make_attack_result() + stats = ConversationStats(message_count=5) + + summary = attack_result_to_summary(ar, stats=stats) + + assert summary.message_count == 5 -class TestPyritScoresToDto: """Tests for pyrit_scores_to_dto function.""" def test_maps_scores(self) -> None: @@ -255,17 +315,30 @@ def test_empty_scores(self) -> None: result = pyrit_scores_to_dto([]) assert result == [] + def test_invalid_score_values_are_skipped(self) -> None: + """Test that non-numeric score values are ignored instead of raising.""" + valid_score = _make_mock_score() + invalid_score = _make_mock_score() + invalid_score.id = "score-invalid" + invalid_score.score_value = "false" + + result = pyrit_scores_to_dto([valid_score, invalid_score]) + + assert len(result) == 1 + assert result[0].score_id == "score-1" + class TestPyritMessagesToDto: - """Tests for pyrit_messages_to_dto function.""" + """Tests for pyrit_messages_to_dto_async function.""" - def test_maps_single_message(self) -> None: + @pytest.mark.asyncio + async def test_maps_single_message(self) -> None: """Test mapping a single message with one piece.""" piece = _make_mock_piece(original_value="hi", converted_value="hi") msg = MagicMock() msg.message_pieces = [piece] - result = pyrit_messages_to_dto([msg]) + result = await pyrit_messages_to_dto_async([msg]) assert len(result) == 1 assert result[0].role == "user" @@ -273,7 +346,8 @@ def test_maps_single_message(self) -> None: assert result[0].pieces[0].original_value == "hi" assert result[0].pieces[0].converted_value == "hi" - def test_maps_data_types_separately(self) -> None: + @pytest.mark.asyncio + async def test_maps_data_types_separately(self) -> None: """Test that original and converted data types are mapped independently.""" piece = _make_mock_piece(original_value="describe this", converted_value="base64data") piece.original_value_data_type = "text" @@ -281,17 +355,19 @@ def test_maps_data_types_separately(self) -> None: msg = MagicMock() msg.message_pieces = [piece] - result = pyrit_messages_to_dto([msg]) + result = await pyrit_messages_to_dto_async([msg]) assert result[0].pieces[0].original_value_data_type == "text" assert result[0].pieces[0].converted_value_data_type == "image" - def test_maps_empty_list(self) -> None: + @pytest.mark.asyncio + async def test_maps_empty_list(self) -> None: """Test mapping an empty messages list.""" - result = pyrit_messages_to_dto([]) + result = await pyrit_messages_to_dto_async([]) assert result == [] - def test_populates_mime_type_for_image(self) -> None: + @pytest.mark.asyncio + async def test_populates_mime_type_for_image(self) -> None: """Test that MIME types are inferred for image pieces.""" piece = _make_mock_piece(original_value="/path/to/photo.png", converted_value="/path/to/photo.jpg") piece.original_value_data_type = "image" @@ -299,23 +375,25 @@ def test_populates_mime_type_for_image(self) -> None: msg = MagicMock() msg.message_pieces = [piece] - result = pyrit_messages_to_dto([msg]) + result = await pyrit_messages_to_dto_async([msg]) assert result[0].pieces[0].original_value_mime_type == "image/png" assert result[0].pieces[0].converted_value_mime_type == "image/jpeg" - def test_mime_type_none_for_text(self) -> None: + @pytest.mark.asyncio + async def test_mime_type_none_for_text(self) -> None: """Test that MIME type is None for text pieces.""" piece = _make_mock_piece(original_value="hello", converted_value="hello") msg = MagicMock() msg.message_pieces = [piece] - result = pyrit_messages_to_dto([msg]) + result = await pyrit_messages_to_dto_async([msg]) assert result[0].pieces[0].original_value_mime_type is None assert result[0].pieces[0].converted_value_mime_type is None - def test_mime_type_for_audio(self) -> None: + @pytest.mark.asyncio + async def test_mime_type_for_audio(self) -> None: """Test that MIME types are inferred for audio pieces.""" piece = _make_mock_piece(original_value="/tmp/speech.wav", converted_value="/tmp/speech.mp3") piece.original_value_data_type = "audio" @@ -323,12 +401,256 @@ def test_mime_type_for_audio(self) -> None: msg = MagicMock() msg.message_pieces = [piece] - result = pyrit_messages_to_dto([msg]) + result = await pyrit_messages_to_dto_async([msg]) # Python 3.10 returns "audio/wav", 3.11+ returns "audio/x-wav" assert result[0].pieces[0].original_value_mime_type in ("audio/wav", "audio/x-wav") assert result[0].pieces[0].converted_value_mime_type == "audio/mpeg" + @pytest.mark.asyncio + async def test_encodes_existing_media_file_to_data_uri(self) -> None: + """Test that local media files are base64-encoded into data URIs.""" + with tempfile.NamedTemporaryFile(suffix=".png", delete=False) as tmp: + tmp.write(b"PNGDATA") + tmp_path = tmp.name + + try: + piece = _make_mock_piece(original_value=tmp_path, converted_value=tmp_path) + piece.original_value_data_type = "image_path" + piece.converted_value_data_type = "image_path" + msg = MagicMock() + msg.message_pieces = [piece] + + result = await pyrit_messages_to_dto_async([msg]) + + assert result[0].pieces[0].original_value is not None + assert result[0].pieces[0].original_value.startswith("data:image/png;base64,") + assert result[0].pieces[0].converted_value.startswith("data:image/png;base64,") + finally: + os.unlink(tmp_path) + + @pytest.mark.asyncio + async def test_data_uri_passthrough(self) -> None: + """Test that pre-encoded data URIs are not re-encoded.""" + piece = _make_mock_piece( + original_value="data:image/png;base64,AAAA", + converted_value="data:image/jpeg;base64,BBBB", + ) + piece.original_value_data_type = "image_path" + piece.converted_value_data_type = "image_path" + msg = MagicMock() + msg.message_pieces = [piece] + + result = await pyrit_messages_to_dto_async([msg]) + + assert result[0].pieces[0].original_value == "data:image/png;base64,AAAA" + assert result[0].pieces[0].converted_value == "data:image/jpeg;base64,BBBB" + + @pytest.mark.asyncio + async def test_non_blob_http_url_passthrough(self) -> None: + """Test that non-Azure-Blob HTTP URLs are passed through as-is.""" + piece = _make_mock_piece( + original_value="http://example.com/image.png", + converted_value="http://example.com/image.png", + ) + piece.original_value_data_type = "image_path" + piece.converted_value_data_type = "image_path" + msg = MagicMock() + msg.message_pieces = [piece] + + result = await pyrit_messages_to_dto_async([msg]) + + assert result[0].pieces[0].original_value == "http://example.com/image.png" + assert result[0].pieces[0].converted_value == "http://example.com/image.png" + + @pytest.mark.asyncio + async def test_azure_blob_url_is_fetched_as_data_uri(self) -> None: + """Test that Azure Blob Storage URLs are fetched and returned as data URIs.""" + blob_url = "https://myaccount.blob.core.windows.net/dbdata/prompt-memory-entries/images/test.png" + piece = _make_mock_piece( + original_value=blob_url, + converted_value=blob_url, + ) + piece.original_value_data_type = "image_path" + piece.converted_value_data_type = "image_path" + msg = MagicMock() + msg.message_pieces = [piece] + + with patch( + "pyrit.backend.mappers.attack_mappers._fetch_blob_as_data_uri_async", + new_callable=AsyncMock, + return_value="data:image/png;base64,ABCD", + ): + result = await pyrit_messages_to_dto_async([msg]) + + assert result[0].pieces[0].original_value == "data:image/png;base64,ABCD" + assert result[0].pieces[0].converted_value == "data:image/png;base64,ABCD" + + @pytest.mark.asyncio + async def test_azure_blob_url_fetch_failure_returns_raw_url(self) -> None: + """Test that blob fetch failure falls back to the raw blob URL.""" + blob_url = "https://myaccount.blob.core.windows.net/dbdata/images/test.png" + piece = _make_mock_piece( + original_value=blob_url, + converted_value=blob_url, + ) + piece.original_value_data_type = "image_path" + piece.converted_value_data_type = "image_path" + msg = MagicMock() + msg.message_pieces = [piece] + + with patch( + "pyrit.backend.mappers.attack_mappers._fetch_blob_as_data_uri_async", + new_callable=AsyncMock, + return_value=blob_url, # falls back to raw URL + ): + result = await pyrit_messages_to_dto_async([msg]) + + assert result[0].pieces[0].original_value == blob_url + assert result[0].pieces[0].converted_value == blob_url + + @pytest.mark.asyncio + async def test_media_read_failure_returns_raw_path(self) -> None: + """Test that unreadable local media files fall back to raw path values.""" + piece = _make_mock_piece(original_value="/tmp/file.png", converted_value="/tmp/file.png") + piece.original_value_data_type = "image_path" + piece.converted_value_data_type = "image_path" + msg = MagicMock() + msg.message_pieces = [piece] + + with ( + patch("pyrit.backend.mappers.attack_mappers.os.path.isfile", return_value=True), + patch("pyrit.backend.mappers.attack_mappers.open", side_effect=OSError("cannot read")), + ): + result = await pyrit_messages_to_dto_async([msg]) + + assert result[0].pieces[0].original_value == "/tmp/file.png" + assert result[0].pieces[0].converted_value == "/tmp/file.png" + + +class TestIsAzureBlobUrl: + """Tests for _is_azure_blob_url helper.""" + + def test_azure_blob_url_detected(self) -> None: + assert _is_azure_blob_url("https://account.blob.core.windows.net/container/blob.png") is True + + def test_http_non_blob_url_not_detected(self) -> None: + assert _is_azure_blob_url("http://example.com/image.png") is False + + def test_https_non_blob_url_not_detected(self) -> None: + assert _is_azure_blob_url("https://example.com/image.png") is False + + def test_data_uri_not_detected(self) -> None: + assert _is_azure_blob_url("data:image/png;base64,AAAA") is False + + def test_local_path_not_detected(self) -> None: + assert _is_azure_blob_url("/tmp/test.png") is False + + +class TestSignBlobUrlAsync: + """Tests for _sign_blob_url_async helper.""" + + @pytest.mark.asyncio + async def test_non_blob_url_unchanged(self) -> None: + """Non-Azure URLs pass through without signing.""" + result = await _sign_blob_url_async(blob_url="http://example.com/img.png") + assert result == "http://example.com/img.png" + + @pytest.mark.asyncio + async def test_already_signed_url_unchanged(self) -> None: + """URLs that already have query params (SAS) are not re-signed.""" + url = "https://acct.blob.core.windows.net/c/b.png?sv=2024&sig=abc" + result = await _sign_blob_url_async(blob_url=url) + assert result == url + + @pytest.mark.asyncio + async def test_appends_sas_token(self) -> None: + """SAS token is appended to unsigned blob URLs.""" + url = "https://acct.blob.core.windows.net/container/path/blob.png" + with patch( + "pyrit.backend.mappers.attack_mappers._get_sas_for_container_async", + new_callable=AsyncMock, + return_value="sv=2024&sig=test", + ) as mock_sas: + result = await _sign_blob_url_async(blob_url=url) + + assert result == f"{url}?sv=2024&sig=test" + mock_sas.assert_called_once_with(container_url="https://acct.blob.core.windows.net/container") + + @pytest.mark.asyncio + async def test_sas_failure_returns_original(self) -> None: + """SAS generation failure falls back to the unsigned URL.""" + url = "https://acct.blob.core.windows.net/c/b.png" + with patch( + "pyrit.backend.mappers.attack_mappers._get_sas_for_container_async", + new_callable=AsyncMock, + side_effect=RuntimeError("auth error"), + ): + result = await _sign_blob_url_async(blob_url=url) + + assert result == url + + +class TestFetchBlobAsDataUriAsync: + """Tests for _fetch_blob_as_data_uri_async helper.""" + + @pytest.mark.asyncio + async def test_fetches_blob_and_returns_data_uri(self) -> None: + """Blob content is fetched, base64-encoded, and returned as a data URI.""" + import httpx + + blob_url = "https://acct.blob.core.windows.net/container/image.png" + fake_resp = httpx.Response( + status_code=200, + content=b"\x89PNG", + headers={"content-type": "image/png"}, + request=httpx.Request("GET", blob_url), + ) + + with ( + patch( + "pyrit.backend.mappers.attack_mappers._sign_blob_url_async", + new_callable=AsyncMock, + return_value=blob_url + "?sig=abc", + ), + patch("pyrit.backend.mappers.attack_mappers.httpx.AsyncClient") as mock_client_cls, + ): + mock_client = AsyncMock() + mock_client.get = AsyncMock(return_value=fake_resp) + mock_client.__aenter__ = AsyncMock(return_value=mock_client) + mock_client.__aexit__ = AsyncMock(return_value=False) + mock_client_cls.return_value = mock_client + + result = await _fetch_blob_as_data_uri_async(blob_url=blob_url) + + import base64 + + expected_b64 = base64.b64encode(b"\x89PNG").decode("ascii") + assert result == f"data:image/png;base64,{expected_b64}" + + @pytest.mark.asyncio + async def test_fetch_failure_returns_raw_url(self) -> None: + """Fetch failure falls back to the unsigned blob URL.""" + blob_url = "https://acct.blob.core.windows.net/container/file.wav" + + with ( + patch( + "pyrit.backend.mappers.attack_mappers._sign_blob_url_async", + new_callable=AsyncMock, + return_value=blob_url + "?sig=abc", + ), + patch("pyrit.backend.mappers.attack_mappers.httpx.AsyncClient") as mock_client_cls, + ): + mock_client = AsyncMock() + mock_client.get = AsyncMock(side_effect=Exception("network error")) + mock_client.__aenter__ = AsyncMock(return_value=mock_client) + mock_client.__aexit__ = AsyncMock(return_value=False) + mock_client_cls.return_value = mock_client + + result = await _fetch_blob_as_data_uri_async(blob_url=blob_url) + + assert result == blob_url + class TestRequestToPyritMessage: """Tests for request_to_pyrit_message function.""" @@ -485,8 +807,6 @@ def test_original_prompt_id_forwarded_when_provided(self) -> None: sequence=0, ) - import uuid - assert result.original_prompt_id == uuid.UUID("aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee") # New piece should have its own id, different from original_prompt_id assert result.id != result.original_prompt_id @@ -549,36 +869,50 @@ def test_infers_mp4(self) -> None: assert _infer_mime_type(value="/tmp/video.mp4", data_type="video") == "video/mp4" -class TestCollectLabelsFromPieces: - """Tests for _collect_labels_from_pieces helper.""" +class TestBuildFilename: + """Tests for _build_filename helper function.""" + + def test_image_path_with_hash(self) -> None: + result = _build_filename(data_type="image_path", sha256="abcdef1234567890", value="/tmp/photo.png") + assert result == "image_abcdef12.png" + + def test_audio_path_with_hash(self) -> None: + result = _build_filename(data_type="audio_path", sha256="1234abcd5678efgh", value="/tmp/speech.wav") + assert result == "audio_1234abcd.wav" - def test_returns_labels_from_first_piece(self) -> None: - """Returns labels from the first piece that has them.""" - p1 = MagicMock() - p1.labels = {"env": "prod"} - p2 = MagicMock() - p2.labels = {"env": "staging"} + def test_video_path_with_hash(self) -> None: + result = _build_filename(data_type="video_path", sha256="deadbeef00000000", value="/tmp/clip.mp4") + assert result == "video_deadbeef.mp4" + + def test_binary_path_with_hash(self) -> None: + result = _build_filename(data_type="binary_path", sha256="cafe0123babe4567", value="/tmp/doc.pdf") + assert result == "file_cafe0123.pdf" + + def test_returns_none_for_text(self) -> None: + assert _build_filename(data_type="text", sha256="abc123", value="hello") is None - assert _collect_labels_from_pieces([p1, p2]) == {"env": "prod"} + def test_returns_none_for_reasoning(self) -> None: + assert _build_filename(data_type="reasoning", sha256="abc123", value="thinking") is None - def test_returns_empty_when_no_pieces(self) -> None: - """Returns empty dict for empty list.""" - assert _collect_labels_from_pieces([]) == {} + def test_fallback_ext_when_no_value(self) -> None: + result = _build_filename(data_type="image_path", sha256="abcdef1234567890", value=None) + assert result == "image_abcdef12.png" - def test_returns_empty_when_pieces_have_no_labels(self) -> None: - """Returns empty dict when pieces have None/empty labels.""" - p = MagicMock() - p.labels = None - assert _collect_labels_from_pieces([p]) == {} + def test_fallback_ext_for_data_uri(self) -> None: + result = _build_filename(data_type="audio_path", sha256="abcdef1234567890", value="data:audio/wav;base64,AAA=") + assert result == "audio_abcdef12.wav" - def test_skips_pieces_with_empty_labels(self) -> None: - """Skips pieces with empty/falsy labels.""" - p1 = MagicMock() - p1.labels = {} - p2 = MagicMock() - p2.labels = {"env": "prod"} + def test_random_hash_when_no_sha256(self) -> None: + result = _build_filename(data_type="image_path", sha256=None, value="/tmp/photo.png") + assert result is not None + assert result.startswith("image_") + assert result.endswith(".png") + assert len(result) == len("image_12345678.png") - assert _collect_labels_from_pieces([p1, p2]) == {"env": "prod"} + def test_blob_url_extension(self) -> None: + url = "https://account.blob.core.windows.net/container/images/photo.jpg" + result = _build_filename(data_type="image_path", sha256="abcdef1234567890", value=url) + assert result == "image_abcdef12.jpg" # ============================================================================ @@ -605,7 +939,7 @@ def test_maps_target_with_identifier(self) -> None: result = target_object_to_instance("t-1", target_obj) - assert result.target_unique_name == "t-1" + assert result.target_registry_name == "t-1" assert result.target_type == "OpenAIChatTarget" assert result.endpoint == "http://test" assert result.model_name == "gpt-4" @@ -638,6 +972,40 @@ def test_no_get_identifier_uses_class_name(self) -> None: assert result.endpoint is None assert result.model_name is None + def test_supports_multiturn_chat_true_for_prompt_chat_target(self) -> None: + """Test that PromptChatTarget subclasses have supports_multiturn_chat=True.""" + from pyrit.prompt_target import PromptChatTarget + + target_obj = MagicMock(spec=PromptChatTarget) + mock_identifier = ComponentIdentifier( + class_name="OpenAIChatTarget", + class_module="pyrit.prompt_target", + params={ + "endpoint": "https://api.openai.com", + "model_name": "gpt-4", + }, + ) + target_obj.get_identifier.return_value = mock_identifier + + result = target_object_to_instance("t-1", target_obj) + + assert result.supports_multiturn_chat is True + + def test_supports_multiturn_chat_false_for_plain_prompt_target(self) -> None: + """Test that plain PromptTarget (non-chat) has supports_multiturn_chat=False.""" + from pyrit.prompt_target import PromptTarget + + target_obj = MagicMock(spec=PromptTarget) + mock_identifier = ComponentIdentifier( + class_name="TextTarget", + class_module="pyrit.prompt_target", + ) + target_obj.get_identifier.return_value = mock_identifier + + result = target_object_to_instance("t-1", target_obj) + + assert result.supports_multiturn_chat is False + # ============================================================================ # Converter Mapper Tests @@ -703,3 +1071,33 @@ def test_none_input_output_types_returns_empty_lists(self) -> None: assert result.supported_output_types == [] assert result.converter_specific_params is None assert result.sub_converter_ids is None + + + +# ============================================================================ +# Drift Detection Tests – verify mapper-accessed fields exist on domain models +# ============================================================================ + + +class TestDomainModelFieldsExist: + """Lightweight safety-net: ensure fields the mappers access still exist on the domain dataclasses. + + If a domain model field is renamed or removed, these tests fail immediately – + before a mapper silently starts returning incorrect data. + """ + + # -- ComponentIdentifier fields used in attack_mappers.py ----------------- + + @pytest.mark.parametrize( + "field_name", + [ + "class_name", + "params", + "children", + ], + ) + def test_component_identifier_has_field(self, field_name: str) -> None: + field_names = {f.name for f in dataclasses.fields(ComponentIdentifier)} + assert field_name in field_names, ( + f"ComponentIdentifier is missing '{field_name}' – mappers depend on this field" + ) diff --git a/tests/unit/backend/test_target_service.py b/tests/unit/backend/test_target_service.py index ea72dd5f2d..74477300e1 100644 --- a/tests/unit/backend/test_target_service.py +++ b/tests/unit/backend/test_target_service.py @@ -67,7 +67,7 @@ async def test_list_targets_returns_targets_from_registry(self) -> None: result = await service.list_targets_async() assert len(result.items) == 1 - assert result.items[0].target_unique_name == "target-1" + assert result.items[0].target_registry_name == "target-1" assert result.items[0].target_type == "MockTarget" assert result.pagination.has_more is False @@ -86,7 +86,7 @@ async def test_list_targets_paginates_with_limit(self) -> None: assert len(result.items) == 3 assert result.pagination.limit == 3 assert result.pagination.has_more is True - assert result.pagination.next_cursor == result.items[-1].target_unique_name + assert result.pagination.next_cursor == result.items[-1].target_registry_name @pytest.mark.asyncio async def test_list_targets_cursor_returns_next_page(self) -> None: @@ -102,7 +102,7 @@ async def test_list_targets_cursor_returns_next_page(self) -> None: second_page = await service.list_targets_async(limit=2, cursor=first_page.pagination.next_cursor) assert len(second_page.items) == 2 - assert second_page.items[0].target_unique_name != first_page.items[0].target_unique_name + assert second_page.items[0].target_registry_name != first_page.items[0].target_registry_name assert second_page.pagination.has_more is True @pytest.mark.asyncio @@ -131,7 +131,7 @@ async def test_get_target_returns_none_for_nonexistent(self) -> None: """Test that get_target returns None for non-existent target.""" service = TargetService() - result = await service.get_target_async(target_unique_name="nonexistent-id") + result = await service.get_target_async(target_registry_name="nonexistent-id") assert result is None @@ -144,10 +144,10 @@ async def test_get_target_returns_target_from_registry(self) -> None: mock_target.get_identifier.return_value = _mock_target_identifier() service._registry.register_instance(mock_target, name="target-1") - result = await service.get_target_async(target_unique_name="target-1") + result = await service.get_target_async(target_registry_name="target-1") assert result is not None - assert result.target_unique_name == "target-1" + assert result.target_registry_name == "target-1" assert result.target_type == "MockTarget" @@ -158,7 +158,7 @@ def test_get_target_object_returns_none_for_nonexistent(self) -> None: """Test that get_target_object returns None for non-existent target.""" service = TargetService() - result = service.get_target_object(target_unique_name="nonexistent-id") + result = service.get_target_object(target_registry_name="nonexistent-id") assert result is None @@ -168,7 +168,7 @@ def test_get_target_object_returns_object_from_registry(self) -> None: mock_target = MagicMock() service._registry.register_instance(mock_target, name="target-1") - result = service.get_target_object(target_unique_name="target-1") + result = service.get_target_object(target_registry_name="target-1") assert result is mock_target @@ -201,7 +201,7 @@ async def test_create_target_success(self, sqlite_instance) -> None: result = await service.create_target_async(request=request) - assert result.target_unique_name is not None + assert result.target_registry_name is not None assert result.target_type == "TextTarget" @pytest.mark.asyncio @@ -217,7 +217,7 @@ async def test_create_target_registers_in_registry(self, sqlite_instance) -> Non result = await service.create_target_async(request=request) # Object should be retrievable from registry - target_obj = service.get_target_object(target_unique_name=result.target_unique_name) + target_obj = service.get_target_object(target_registry_name=result.target_registry_name) assert target_obj is not None From 0a4280d23daaf7b27df8f5480401b131f6ba5f53 Mon Sep 17 00:00:00 2001 From: Roman Lutz Date: Mon, 2 Mar 2026 14:52:34 -0800 Subject: [PATCH 4/7] fix: auto ruff format fixes --- pyrit/backend/mappers/attack_mappers.py | 10 ++--- pyrit/backend/models/attacks.py | 25 ++++++------ pyrit/backend/models/targets.py | 4 +- pyrit/backend/services/attack_service.py | 47 +++++++++++------------ pyrit/memory/sqlite_memory.py | 2 +- pyrit/models/conversation_stats.py | 7 ++-- pyrit/setup/initializers/airt.py | 2 +- pyrit/setup/initializers/airt_targets.py | 4 +- tests/unit/backend/test_attack_service.py | 1 - tests/unit/backend/test_mappers.py | 4 +- 10 files changed, 53 insertions(+), 53 deletions(-) diff --git a/pyrit/backend/mappers/attack_mappers.py b/pyrit/backend/mappers/attack_mappers.py index fcb9a1ccf7..70ee1d9d70 100644 --- a/pyrit/backend/mappers/attack_mappers.py +++ b/pyrit/backend/mappers/attack_mappers.py @@ -18,8 +18,9 @@ import os import time import uuid +from collections.abc import Sequence from datetime import datetime, timedelta, timezone -from typing import TYPE_CHECKING, Dict, List, Optional, Sequence, Tuple, cast +from typing import TYPE_CHECKING, Optional, cast from urllib.parse import urlparse import httpx @@ -61,7 +62,7 @@ # Azure Blob SAS token cache # --------------------------------------------------------------------------- # Container URL -> (sas_token_query_string, expiry_epoch) -_sas_token_cache: Dict[str, Tuple[str, float]] = {} +_sas_token_cache: dict[str, tuple[str, float]] = {} _SAS_TTL_SECONDS = 3500 # cache for ~58 min; tokens are valid for 1 hour @@ -280,7 +281,7 @@ def pyrit_scores_to_dto(scores: list[PyritScore]) -> list[Score]: Returns: List of Score DTOs for the API. """ - mapped_scores: List[Score] = [] + mapped_scores: list[Score] = [] for score in scores: try: score_value = float(score.score_value) @@ -373,7 +374,7 @@ def _build_filename( return f"{prefix}_{short_hash}{ext}" -async def pyrit_messages_to_dto_async(pyrit_messages: List[PyritMessage]) -> List[Message]: +async def pyrit_messages_to_dto_async(pyrit_messages: list[PyritMessage]) -> list[Message]: """ Translate PyRIT messages to backend Message DTOs. @@ -518,7 +519,6 @@ def request_to_pyrit_message( return PyritMessage(pieces) - # ============================================================================ # Private Helpers # ============================================================================ diff --git a/pyrit/backend/models/attacks.py b/pyrit/backend/models/attacks.py index d14b878f1f..018c26115c 100644 --- a/pyrit/backend/models/attacks.py +++ b/pyrit/backend/models/attacks.py @@ -9,7 +9,7 @@ """ from datetime import datetime -from typing import Any, Dict, List, Literal, Optional +from typing import Any, Literal, Optional from pydantic import BaseModel, Field @@ -89,9 +89,9 @@ class AttackSummary(BaseModel): attack_result_id: str = Field(..., description="Database-assigned unique ID for this AttackResult") conversation_id: str = Field(..., description="Primary conversation of this attack result") attack_type: str = Field(..., description="Attack class name (e.g., 'CrescendoAttack', 'ManualAttack')") - attack_specific_params: Optional[Dict[str, Any]] = Field(None, description="Additional attack-specific parameters") + attack_specific_params: Optional[dict[str, Any]] = Field(None, description="Additional attack-specific parameters") target: Optional[TargetInfo] = Field(None, description="Target information from the stored identifier") - converters: List[str] = Field( + converters: list[str] = Field( default_factory=list, description="Request converter class names applied in this attack" ) outcome: Optional[Literal["undetermined", "success", "failure"]] = Field( @@ -101,10 +101,10 @@ class AttackSummary(BaseModel): None, description="Preview of the last message (truncated to ~100 chars)" ) message_count: int = Field(0, description="Total number of messages in the attack") - related_conversation_ids: List[str] = Field( + related_conversation_ids: list[str] = Field( default_factory=list, description="IDs of related conversations within this attack" ) - labels: Dict[str, str] = Field(default_factory=dict, description="User-defined labels for filtering") + labels: dict[str, str] = Field(default_factory=dict, description="User-defined labels for filtering") created_at: datetime = Field(..., description="Attack creation timestamp") updated_at: datetime = Field(..., description="Last update timestamp") @@ -118,7 +118,7 @@ class ConversationMessagesResponse(BaseModel): """Response containing all messages for a conversation.""" conversation_id: str = Field(..., description="Conversation identifier") - messages: List[Message] = Field(default_factory=list, description="All messages in order") + messages: list[Message] = Field(default_factory=list, description="All messages in order") # ============================================================================ @@ -136,13 +136,13 @@ class AttackListResponse(BaseModel): class AttackOptionsResponse(BaseModel): """Response containing unique attack type names used across attacks.""" - attack_types: List[str] = Field(..., description="Sorted list of unique attack type names found in attack results") + attack_types: list[str] = Field(..., description="Sorted list of unique attack type names found in attack results") class ConverterOptionsResponse(BaseModel): """Response containing unique converter type names used across attacks.""" - converter_types: List[str] = Field( + converter_types: list[str] = Field( ..., description="Sorted list of unique converter type names found in attack results" ) @@ -179,7 +179,8 @@ class PrependedMessageRequest(BaseModel): class CreateAttackRequest(BaseModel): - """Request to create a new attack. + """ + Request to create a new attack. For branching from an existing conversation into a new attack, provide ``source_conversation_id`` and ``cutoff_index``. The backend will @@ -240,7 +241,7 @@ class AttackConversationsResponse(BaseModel): attack_result_id: str = Field(..., description="The AttackResult ID") main_conversation_id: str = Field(..., description="The attack's primary conversation_id") - conversations: List[ConversationSummary] = Field( + conversations: list[ConversationSummary] = Field( default_factory=list, description="All conversations including main" ) @@ -304,7 +305,7 @@ class AddMessageRequest(BaseModel): None, description="Target registry name. Required when send=True so the backend knows which target to use.", ) - converter_ids: Optional[List[str]] = Field( + converter_ids: Optional[list[str]] = Field( None, description="Converter instance IDs to apply (overrides attack-level)" ) target_conversation_id: str = Field( @@ -312,7 +313,7 @@ class AddMessageRequest(BaseModel): description="The conversation_id to store and send messages under. " "Usually the attack's main conversation, but can be a related conversation.", ) - labels: Optional[Dict[str, str]] = Field( + labels: Optional[dict[str, str]] = Field( None, description="Labels to stamp on every message piece. " "Falls back to labels from existing pieces in the conversation.", diff --git a/pyrit/backend/models/targets.py b/pyrit/backend/models/targets.py index d2d98fe931..d021189df3 100644 --- a/pyrit/backend/models/targets.py +++ b/pyrit/backend/models/targets.py @@ -11,7 +11,7 @@ This module defines the Instance models for runtime target management. """ -from typing import Any, Dict, Optional +from typing import Any, Optional from pydantic import BaseModel, Field @@ -36,7 +36,7 @@ class TargetInstance(BaseModel): supports_multiturn_chat: bool = Field( True, description="Whether the target supports multi-turn conversation history" ) - target_specific_params: Optional[Dict[str, Any]] = Field(None, description="Additional target-specific parameters") + target_specific_params: Optional[dict[str, Any]] = Field(None, description="Additional target-specific parameters") class TargetListResponse(BaseModel): diff --git a/pyrit/backend/services/attack_service.py b/pyrit/backend/services/attack_service.py index 07c97dc9bc..a8ac106b28 100644 --- a/pyrit/backend/services/attack_service.py +++ b/pyrit/backend/services/attack_service.py @@ -17,9 +17,10 @@ import mimetypes import uuid +from collections.abc import Sequence from datetime import datetime, timezone from functools import lru_cache -from typing import Any, Dict, List, Literal, Optional, Sequence, cast +from typing import Any, Literal, Optional, cast from pyrit.backend.mappers.attack_mappers import ( attack_result_to_summary, @@ -54,10 +55,12 @@ AttackResult, ConversationStats, ConversationType, - Message as PyritMessage, PromptDataType, data_serializer_factory, ) +from pyrit.models import ( + Message as PyritMessage, +) from pyrit.prompt_normalizer import PromptConverterConfiguration, PromptNormalizer @@ -80,7 +83,7 @@ async def list_attacks_async( self, *, attack_type: Optional[str] = None, - converter_types: Optional[List[str]] = None, + converter_types: Optional[list[str]] = None, outcome: Optional[Literal["undetermined", "success", "failure"]] = None, labels: Optional[dict[str, str]] = None, min_turns: Optional[int] = None, @@ -136,7 +139,7 @@ async def list_attacks_async( # Phase 2: Lightweight DB aggregation for the page only. # Collect conversation IDs we care about (main + pruned, not adversarial). - all_conv_ids: List[str] = [] + all_conv_ids: list[str] = [] for ar in page_results: all_conv_ids.append(ar.conversation_id) all_conv_ids.extend( @@ -148,7 +151,7 @@ async def list_attacks_async( stats_map = self._memory.get_conversation_stats(conversation_ids=all_conv_ids) if all_conv_ids else {} # Phase 2: Fetch pieces only for the page we're returning - page: List[AttackSummary] = [] + page: list[AttackSummary] = [] for ar in page_results: # Merge stats for the main conversation and its pruned relatives. main_stats = stats_map.get(ar.conversation_id) @@ -396,7 +399,7 @@ async def get_conversations_async(self, *, attack_result_id: str) -> Optional[At all_conv_ids = [ar.conversation_id] + pruned_related_ids stats_map = self._memory.get_conversation_stats(conversation_ids=all_conv_ids) - conversations: List[ConversationSummary] = [] + conversations: list[ConversationSummary] = [] for conv_id in all_conv_ids: stats = stats_map.get(conv_id) created_at = stats.created_at.isoformat() if stats and stats.created_at else None @@ -450,9 +453,7 @@ async def create_related_conversation_async( # Add to pruned_conversation_ids so user-created branches are visible in the GUI history panel. existing_pruned = [ - ref.conversation_id - for ref in ar.related_conversations - if ref.conversation_type == ConversationType.PRUNED + ref.conversation_id for ref in ar.related_conversations if ref.conversation_type == ConversationType.PRUNED ] updated_metadata = dict(ar.metadata or {}) @@ -558,17 +559,17 @@ async def add_message_async(self, *, attack_result_id: str, request: AddMessageR stored_target_id = aid.get_child("objective_target") if aid else None if stored_target_id: target_service = get_target_service() - request_target_obj = target_service.get_target_object( - target_registry_name=request.target_registry_name - ) + request_target_obj = target_service.get_target_object(target_registry_name=request.target_registry_name) if request_target_obj: request_target_id = request_target_obj.get_identifier() # Compare class, endpoint, and model – sufficient to catch # cross-target mistakes while allowing config-level changes. if ( stored_target_id.class_name != request_target_id.class_name - or (stored_target_id.params.get("endpoint") or "") != (request_target_id.params.get("endpoint") or "") - or (stored_target_id.params.get("model_name") or "") != (request_target_id.params.get("model_name") or "") + or (stored_target_id.params.get("endpoint") or "") + != (request_target_id.params.get("endpoint") or "") + or (stored_target_id.params.get("model_name") or "") + != (request_target_id.params.get("model_name") or "") ): raise ValueError( f"Target mismatch: attack was created with " @@ -642,7 +643,7 @@ async def add_message_async(self, *, attack_result_id: str, request: AddMessageR updated_metadata = dict(ar.metadata or {}) updated_metadata["updated_at"] = datetime.now(timezone.utc).isoformat() - update_fields: Dict[str, Any] = {"attack_metadata": updated_metadata} + update_fields: dict[str, Any] = {"attack_metadata": updated_metadata} # Track converters used in this turn on the AttackResult. # Always propagate when converter_ids are provided, regardless of @@ -652,7 +653,7 @@ async def add_message_async(self, *, attack_result_id: str, request: AddMessageR new_converter_ids = [c.get_identifier() for c in converter_objs] aid = ar.attack_identifier if aid: - existing_converters: List[ComponentIdentifier] = list(aid.get_child_list("request_converters")) + existing_converters: list[ComponentIdentifier] = list(aid.get_child_list("request_converters")) existing_hashes = {c.hash for c in existing_converters} merged = existing_converters + [c for c in new_converter_ids if c.hash not in existing_hashes] new_children = dict(aid.children) @@ -740,7 +741,7 @@ def _get_earliest_timestamp(pieces: Sequence[PromptMemoryEntry]) -> Optional[dat """Return the earliest timestamp from a list of message pieces.""" if not pieces: return None - timestamps: List[datetime] = [p.timestamp for p in pieces if p.timestamp is not None] + timestamps: list[datetime] = [p.timestamp for p in pieces if p.timestamp is not None] return min(timestamps) if timestamps else None # ======================================================================== @@ -752,7 +753,7 @@ def _duplicate_conversation_up_to( *, source_conversation_id: str, cutoff_index: int, - labels_override: Optional[Dict[str, str]] = None, + labels_override: Optional[dict[str, str]] = None, remap_assistant_to_simulated: bool = False, ) -> str: """ @@ -830,7 +831,7 @@ async def _persist_base64_pieces(request: AddMessageRequest) -> None: serializer = data_serializer_factory( category="prompt-memory-entries", - data_type=cast(PromptDataType, piece.data_type), + data_type=cast("PromptDataType", piece.data_type), extension=ext, ) await serializer.save_b64_image(data=piece.original_value) @@ -864,7 +865,7 @@ async def _send_and_store_message( target_registry_name: str, request: AddMessageRequest, sequence: int, - labels: Optional[Dict[str, str]] = None, + labels: Optional[dict[str, str]] = None, ) -> None: """Send message to target via normalizer and store response.""" target_obj = get_target_service().get_target_object(target_registry_name=target_registry_name) @@ -954,9 +955,7 @@ def _inject_video_id_from_history(self, *, conversation_id: str, message: PyritM @staticmethod def _strip_video_pieces(message: PyritMessage) -> None: """Remove video_path pieces from a message (video_id on text piece replaces them).""" - message.message_pieces = [ - p for p in message.message_pieces if p.original_value_data_type != "video_path" - ] + message.message_pieces = [p for p in message.message_pieces if p.original_value_data_type != "video_path"] async def _store_message_only( self, @@ -964,7 +963,7 @@ async def _store_message_only( conversation_id: str, request: AddMessageRequest, sequence: int, - labels: Optional[Dict[str, str]] = None, + labels: Optional[dict[str, str]] = None, ) -> None: """Store message without sending (send=False).""" await self._persist_base64_pieces(request) diff --git a/pyrit/memory/sqlite_memory.py b/pyrit/memory/sqlite_memory.py index 375c348e9d..099fe6334a 100644 --- a/pyrit/memory/sqlite_memory.py +++ b/pyrit/memory/sqlite_memory.py @@ -10,7 +10,7 @@ from pathlib import Path from typing import Any, Optional, TypeVar, Union -from sqlalchemy import and_, create_engine, exists, func, or_, text +from sqlalchemy import and_, create_engine, func, or_, text from sqlalchemy.engine.base import Engine from sqlalchemy.exc import SQLAlchemyError from sqlalchemy.orm import joinedload, sessionmaker diff --git a/pyrit/models/conversation_stats.py b/pyrit/models/conversation_stats.py index c67f3d8427..992be697a9 100644 --- a/pyrit/models/conversation_stats.py +++ b/pyrit/models/conversation_stats.py @@ -5,12 +5,13 @@ from dataclasses import dataclass, field from datetime import datetime -from typing import ClassVar, Dict, Optional +from typing import ClassVar, Optional @dataclass(frozen=True) class ConversationStats: - """Lightweight aggregate statistics for a conversation. + """ + Lightweight aggregate statistics for a conversation. Used to build attack summaries without loading full message pieces. """ @@ -19,5 +20,5 @@ class ConversationStats: message_count: int = 0 last_message_preview: Optional[str] = None - labels: Dict[str, str] = field(default_factory=dict) + labels: dict[str, str] = field(default_factory=dict) created_at: Optional[datetime] = None diff --git a/pyrit/setup/initializers/airt.py b/pyrit/setup/initializers/airt.py index cd990a87de..7513ecd28d 100644 --- a/pyrit/setup/initializers/airt.py +++ b/pyrit/setup/initializers/airt.py @@ -9,7 +9,7 @@ """ import os -from typing import Callable +from collections.abc import Callable from pyrit.auth import get_azure_openai_auth, get_azure_token_provider from pyrit.common.apply_defaults import set_default_value, set_global_variable diff --git a/pyrit/setup/initializers/airt_targets.py b/pyrit/setup/initializers/airt_targets.py index 0f6f2f7c6f..06a94f9025 100644 --- a/pyrit/setup/initializers/airt_targets.py +++ b/pyrit/setup/initializers/airt_targets.py @@ -15,7 +15,7 @@ import logging import os from dataclasses import dataclass, field -from typing import Any, Dict, List, Optional, Type +from typing import Any, Optional from pyrit.prompt_target import ( AzureMLChatTarget, @@ -45,7 +45,7 @@ class TargetConfig: key_var: str = "" # Empty string means no auth required model_var: Optional[str] = None underlying_model_var: Optional[str] = None - extra_kwargs: Dict[str, Any] = field(default_factory=dict) + extra_kwargs: dict[str, Any] = field(default_factory=dict) # Define all supported target configurations. diff --git a/tests/unit/backend/test_attack_service.py b/tests/unit/backend/test_attack_service.py index affc5a1eae..b4125e7a85 100644 --- a/tests/unit/backend/test_attack_service.py +++ b/tests/unit/backend/test_attack_service.py @@ -7,7 +7,6 @@ The attack service uses PyRIT memory with AttackResult as the source of truth. """ -import uuid from datetime import datetime, timezone from unittest.mock import AsyncMock, MagicMock, patch diff --git a/tests/unit/backend/test_mappers.py b/tests/unit/backend/test_mappers.py index 463094ea2e..ba80c8eb31 100644 --- a/tests/unit/backend/test_mappers.py +++ b/tests/unit/backend/test_mappers.py @@ -12,10 +12,11 @@ import os import tempfile import uuid -import pytest from datetime import datetime, timezone from unittest.mock import AsyncMock, MagicMock, patch +import pytest + from pyrit.backend.mappers.attack_mappers import ( _build_filename, _fetch_blob_as_data_uri_async, @@ -1073,7 +1074,6 @@ def test_none_input_output_types_returns_empty_lists(self) -> None: assert result.sub_converter_ids is None - # ============================================================================ # Drift Detection Tests – verify mapper-accessed fields exist on domain models # ============================================================================ From 96d583964cb1237a5167af5812f4529349735244 Mon Sep 17 00:00:00 2001 From: Roman Lutz Date: Mon, 2 Mar 2026 14:54:24 -0800 Subject: [PATCH 5/7] fix: address ruff and mypy lint issues --- pyrit/backend/mappers/attack_mappers.py | 10 +++++++--- pyrit/backend/routes/attacks.py | 2 +- pyrit/backend/services/attack_service.py | 2 +- pyrit/memory/azure_sql_memory.py | 6 ++---- pyrit/memory/memory_interface.py | 2 +- pyrit/memory/sqlite_memory.py | 10 ++++------ pyrit/models/conversation_stats.py | 6 ++++-- .../openai/openai_response_target.py | 19 +++++++------------ pyrit/setup/initializers/airt.py | 7 ++++--- 9 files changed, 31 insertions(+), 33 deletions(-) diff --git a/pyrit/backend/mappers/attack_mappers.py b/pyrit/backend/mappers/attack_mappers.py index 70ee1d9d70..3f52c8015e 100644 --- a/pyrit/backend/mappers/attack_mappers.py +++ b/pyrit/backend/mappers/attack_mappers.py @@ -41,13 +41,14 @@ from pyrit.models import Message as PyritMessage from pyrit.models import MessagePiece as PyritMessagePiece from pyrit.models import Score as PyritScore -from pyrit.models.conversation_stats import ConversationStats logger = logging.getLogger(__name__) if TYPE_CHECKING: from collections.abc import Sequence + from pyrit.models.conversation_stats import ConversationStats + # ============================================================================ # Domain → DTO (for API responses) # ============================================================================ @@ -105,11 +106,11 @@ async def _get_sas_for_container_async(*, container_url: str) -> str: key_start_time=start_time, key_expiry_time=expiry_time, ) - sas_token: str = generate_container_sas( # type: ignore[assignment] + sas_token: str = generate_container_sas( account_name=storage_account_name, container_name=container_name, user_delegation_key=delegation_key, - permission=ContainerSasPermissions(read=True), # type: ignore[no-untyped-call, unused-ignore] + permission=ContainerSasPermissions(read=True), expiry=expiry_time, start=start_time, ) @@ -344,6 +345,9 @@ def _build_filename( data_type: The prompt data type (e.g. ``image_path``, ``audio_path``). sha256: The SHA256 hash of the content, if available. value: The original value (path or URL) used to infer file extension. + + Returns: + Optional[str]: A filename like ``image_a1b2c3d4.png``, or ``None`` for text-like types. """ # Map data types to friendly prefixes _PREFIX_MAP = { diff --git a/pyrit/backend/routes/attacks.py b/pyrit/backend/routes/attacks.py index 60169576c1..1c2e36bf1e 100644 --- a/pyrit/backend/routes/attacks.py +++ b/pyrit/backend/routes/attacks.py @@ -352,7 +352,7 @@ async def change_main_conversation( raise HTTPException( status_code=status.HTTP_400_BAD_REQUEST, detail=str(e), - ) + ) from e if not result: raise HTTPException( diff --git a/pyrit/backend/services/attack_service.py b/pyrit/backend/services/attack_service.py index a8ac106b28..c5b01994f6 100644 --- a/pyrit/backend/services/attack_service.py +++ b/pyrit/backend/services/attack_service.py @@ -734,7 +734,7 @@ def _count_messages(pieces: Sequence[PromptMemoryEntry]) -> int: Returns: The number of unique sequence values. """ - return len(set(p.sequence for p in pieces)) + return len({p.sequence for p in pieces}) @staticmethod def _get_earliest_timestamp(pieces: Sequence[PromptMemoryEntry]) -> Optional[datetime]: diff --git a/pyrit/memory/azure_sql_memory.py b/pyrit/memory/azure_sql_memory.py index d441197492..6b31cd1f8b 100644 --- a/pyrit/memory/azure_sql_memory.py +++ b/pyrit/memory/azure_sql_memory.py @@ -5,7 +5,7 @@ import logging import struct from collections.abc import MutableSequence, Sequence -from contextlib import closing +from contextlib import closing, suppress from datetime import datetime, timedelta, timezone from typing import TYPE_CHECKING, Any, Optional, TypeVar, Union @@ -543,10 +543,8 @@ def get_conversation_stats(self, *, conversation_ids: Sequence[str]) -> dict[str labels: dict[str, str] = {} if raw_labels and raw_labels not in ("null", "{}"): - try: + with suppress(ValueError, TypeError): labels = json.loads(raw_labels) - except (ValueError, TypeError): - pass created_at = None if raw_created_at is not None: diff --git a/pyrit/memory/memory_interface.py b/pyrit/memory/memory_interface.py index c9c3753daa..31958f2e70 100644 --- a/pyrit/memory/memory_interface.py +++ b/pyrit/memory/memory_interface.py @@ -1298,7 +1298,7 @@ def add_attack_results_to_memory(self, *, attack_results: Sequence[AttackResult] session.commit() # Populate the attack_result_id back onto the domain objects so callers # can reference the DB-assigned ID immediately after insert. - for ar, entry in zip(attack_results, entries): + for ar, entry in zip(attack_results, entries, strict=True): ar.attack_result_id = str(entry.id) except SQLAlchemyError: session.rollback() diff --git a/pyrit/memory/sqlite_memory.py b/pyrit/memory/sqlite_memory.py index 099fe6334a..2515180217 100644 --- a/pyrit/memory/sqlite_memory.py +++ b/pyrit/memory/sqlite_memory.py @@ -5,7 +5,7 @@ import logging import uuid from collections.abc import MutableSequence, Sequence -from contextlib import closing +from contextlib import closing, suppress from datetime import datetime from pathlib import Path from typing import Any, Optional, TypeVar, Union @@ -483,7 +483,7 @@ def _get_attack_result_harm_category_condition(self, *, targeted_harm_categories ), ) ) - return targeted_harm_categories_subquery + return targeted_harm_categories_subquery # noqa: RET504 def _get_attack_result_label_condition(self, *, labels: dict[str, str]) -> Any: """ @@ -506,7 +506,7 @@ def _get_attack_result_label_condition(self, *, labels: dict[str, str]) -> Any: ), ) ) - return labels_subquery + return labels_subquery # noqa: RET504 def _get_attack_result_attack_type_condition(self, *, attack_type: str) -> Any: """ @@ -651,10 +651,8 @@ def get_conversation_stats(self, *, conversation_ids: Sequence[str]) -> dict[str labels: dict[str, str] = {} if raw_labels and raw_labels not in ("null", "{}"): - try: + with suppress(ValueError, TypeError): labels = json.loads(raw_labels) - except (ValueError, TypeError): - pass created_at = None if raw_created_at is not None: diff --git a/pyrit/models/conversation_stats.py b/pyrit/models/conversation_stats.py index 992be697a9..bb8283fccf 100644 --- a/pyrit/models/conversation_stats.py +++ b/pyrit/models/conversation_stats.py @@ -4,8 +4,10 @@ from __future__ import annotations from dataclasses import dataclass, field -from datetime import datetime -from typing import ClassVar, Optional +from typing import TYPE_CHECKING, ClassVar, Optional + +if TYPE_CHECKING: + from datetime import datetime @dataclass(frozen=True) diff --git a/pyrit/prompt_target/openai/openai_response_target.py b/pyrit/prompt_target/openai/openai_response_target.py index 5352573d7a..7f9445ef8b 100644 --- a/pyrit/prompt_target/openai/openai_response_target.py +++ b/pyrit/prompt_target/openai/openai_response_target.py @@ -171,21 +171,16 @@ def _build_identifier(self) -> ComponentIdentifier: Returns: ComponentIdentifier: The identifier for this target instance. """ - specific_params: dict[str, Any] = { + params: dict[str, Any] = { + "temperature": self._temperature, + "top_p": self._top_p, "max_output_tokens": self._max_output_tokens, + "reasoning_effort": self._reasoning_effort, + "reasoning_summary": self._reasoning_summary, } if self._extra_body_parameters: - specific_params["extra_body_parameters"] = self._extra_body_parameters - return self._create_identifier( - params={ - "temperature": self._temperature, - "top_p": self._top_p, - "max_output_tokens": self._max_output_tokens, - "reasoning_effort": self._reasoning_effort, - "reasoning_summary": self._reasoning_summary, - }, - target_specific_params=specific_params, - ) + params["extra_body_parameters"] = self._extra_body_parameters + return self._create_identifier(params=params) def _set_openai_env_configuration_vars(self) -> None: self.model_name_environment_variable = "OPENAI_RESPONSES_MODEL" diff --git a/pyrit/setup/initializers/airt.py b/pyrit/setup/initializers/airt.py index 7513ecd28d..23bc945a0e 100644 --- a/pyrit/setup/initializers/airt.py +++ b/pyrit/setup/initializers/airt.py @@ -10,6 +10,7 @@ import os from collections.abc import Callable +from typing import Any from pyrit.auth import get_azure_openai_auth, get_azure_token_provider from pyrit.common.apply_defaults import set_default_value, set_global_variable @@ -134,7 +135,7 @@ async def initialize_async(self) -> None: endpoint=converter_endpoint, credential=converter_auth, model_name=converter_model_name ) - def _setup_converter_target(self, *, endpoint: str, credential: Callable, model_name: str) -> None: + def _setup_converter_target(self, *, endpoint: str, credential: Callable[..., Any], model_name: str) -> None: """Set up the default converter target configuration.""" default_converter_target = OpenAIChatTarget( endpoint=endpoint, @@ -151,7 +152,7 @@ def _setup_converter_target(self, *, endpoint: str, credential: Callable, model_ ) def _setup_scorers( - self, *, endpoint: str, credential: Callable, model_name: str, content_safety_credential: Callable + self, *, endpoint: str, credential: Callable[..., Any], model_name: str, content_safety_credential: Callable[..., Any] ) -> None: """Set up the composite harm and objective scorers.""" scorer_target = OpenAIChatTarget( @@ -215,7 +216,7 @@ def _setup_scorers( value=default_objective_scorer_config, ) - def _setup_adversarial_targets(self, *, endpoint: str, credential: Callable, model_name: str) -> None: + def _setup_adversarial_targets(self, *, endpoint: str, credential: Callable[..., Any], model_name: str) -> None: """Set up the adversarial target configurations for attacks.""" adversarial_config = AttackAdversarialConfig( target=OpenAIChatTarget( From 14fb53fffdedfe624f0194ee744c1977c7caa330 Mon Sep 17 00:00:00 2001 From: Roman Lutz Date: Mon, 2 Mar 2026 14:54:47 -0800 Subject: [PATCH 6/7] fix: ruff format --- pyrit/setup/initializers/airt.py | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/pyrit/setup/initializers/airt.py b/pyrit/setup/initializers/airt.py index 23bc945a0e..c37530cc87 100644 --- a/pyrit/setup/initializers/airt.py +++ b/pyrit/setup/initializers/airt.py @@ -152,7 +152,12 @@ def _setup_converter_target(self, *, endpoint: str, credential: Callable[..., An ) def _setup_scorers( - self, *, endpoint: str, credential: Callable[..., Any], model_name: str, content_safety_credential: Callable[..., Any] + self, + *, + endpoint: str, + credential: Callable[..., Any], + model_name: str, + content_safety_credential: Callable[..., Any], ) -> None: """Set up the composite harm and objective scorers.""" scorer_target = OpenAIChatTarget( From b48e23fa9f660fe4f42abb64361d54243bd50f3d Mon Sep 17 00:00:00 2001 From: Roman Lutz Date: Mon, 2 Mar 2026 21:26:24 -0800 Subject: [PATCH 7/7] fix: address copilot comments - security, cleanup, API contract Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- pyrit/backend/mappers/attack_mappers.py | 6 +- pyrit/backend/routes/attacks.py | 13 +-- pyrit/backend/services/attack_service.py | 33 ------- .../test_interface_attack_results.py | 94 +++++++++---------- 4 files changed, 57 insertions(+), 89 deletions(-) diff --git a/pyrit/backend/mappers/attack_mappers.py b/pyrit/backend/mappers/attack_mappers.py index 32ecc6df4e..106bb2bada 100644 --- a/pyrit/backend/mappers/attack_mappers.py +++ b/pyrit/backend/mappers/attack_mappers.py @@ -69,7 +69,11 @@ def _is_azure_blob_url(value: str) -> bool: """Return True if *value* looks like an Azure Blob Storage URL.""" - return value.startswith("https://") and ".blob.core.windows.net/" in value + parsed = urlparse(value) + if parsed.scheme != "https": + return False + host = parsed.netloc.split(":")[0] # strip port + return host.endswith(".blob.core.windows.net") and bool(host.split(".")[0]) async def _get_sas_for_container_async(*, container_url: str) -> str: diff --git a/pyrit/backend/routes/attacks.py b/pyrit/backend/routes/attacks.py index 1c2e36bf1e..17bd727f58 100644 --- a/pyrit/backend/routes/attacks.py +++ b/pyrit/backend/routes/attacks.py @@ -8,7 +8,7 @@ This is the attack-centric API design. """ -import traceback +import logging from typing import Literal, Optional from fastapi import APIRouter, HTTPException, Query, status @@ -33,6 +33,8 @@ from pyrit.backend.models.common import ProblemDetail from pyrit.backend.services.attack_service import get_attack_service +logger = logging.getLogger(__name__) + router = APIRouter(prefix="/attacks", tags=["attacks"]) @@ -406,13 +408,8 @@ async def add_message( detail=error_msg, ) from e except Exception as e: - tb = traceback.format_exception(type(e), e, e.__traceback__) - # Include the root cause if chained - cause = e.__cause__ - if cause: - tb += traceback.format_exception(type(cause), cause, cause.__traceback__) - detail = "".join(tb) + logger.exception("Failed to add message to attack '%s'", attack_result_id) raise HTTPException( status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, - detail=detail, + detail="Internal server error. Check server logs for details.", ) from e diff --git a/pyrit/backend/services/attack_service.py b/pyrit/backend/services/attack_service.py index 4d8f86064c..0b232f5533 100644 --- a/pyrit/backend/services/attack_service.py +++ b/pyrit/backend/services/attack_service.py @@ -17,7 +17,6 @@ import mimetypes import uuid -from collections.abc import Sequence from datetime import datetime, timezone from functools import lru_cache from typing import Any, Literal, Optional, cast @@ -49,7 +48,6 @@ from pyrit.backend.services.target_service import get_target_service from pyrit.identifiers import ComponentIdentifier from pyrit.memory import CentralMemory -from pyrit.memory.memory_models import PromptMemoryEntry from pyrit.models import ( AttackOutcome, AttackResult, @@ -714,37 +712,6 @@ def _paginate_attack_results( has_more = len(items) > start_idx + limit return page, has_more - # ======================================================================== - # Private Helper Methods - Conversation Info - # ======================================================================== - - @staticmethod - def _get_last_message_preview(pieces: Sequence[PromptMemoryEntry]) -> Optional[str]: - """Return a truncated preview of the last message piece's text.""" - if not pieces: - return None - last = max(pieces, key=lambda p: p.sequence) - text = last.converted_value or "" - return text[:100] + "..." if len(text) > 100 else text - - @staticmethod - def _count_messages(pieces: Sequence[PromptMemoryEntry]) -> int: - """ - Count distinct messages (by sequence number) in a list of pieces. - - Returns: - The number of unique sequence values. - """ - return len({p.sequence for p in pieces}) - - @staticmethod - def _get_earliest_timestamp(pieces: Sequence[PromptMemoryEntry]) -> Optional[datetime]: - """Return the earliest timestamp from a list of message pieces.""" - if not pieces: - return None - timestamps: list[datetime] = [p.timestamp for p in pieces if p.timestamp is not None] - return min(timestamps) if timestamps else None - # ======================================================================== # Private Helper Methods - Duplicate / Branch # ======================================================================== diff --git a/tests/unit/memory/memory_interface/test_interface_attack_results.py b/tests/unit/memory/memory_interface/test_interface_attack_results.py index 72289f1aa4..30a1c600b2 100644 --- a/tests/unit/memory/memory_interface/test_interface_attack_results.py +++ b/tests/unit/memory/memory_interface/test_interface_attack_results.py @@ -1149,60 +1149,60 @@ def _make_attack_result_with_identifier( ) -def test_get_attack_results_by_attack_type(sqlite_instance: MemoryInterface): - """Test filtering attack results by attack_type matches class_name in JSON.""" +def test_get_attack_results_by_attack_class(sqlite_instance: MemoryInterface): + """Test filtering attack results by attack_class matches class_name in JSON.""" ar1 = _make_attack_result_with_identifier("conv_1", "CrescendoAttack") ar2 = _make_attack_result_with_identifier("conv_2", "ManualAttack") ar3 = _make_attack_result_with_identifier("conv_3", "CrescendoAttack") sqlite_instance.add_attack_results_to_memory(attack_results=[ar1, ar2, ar3]) - results = sqlite_instance.get_attack_results(attack_type="CrescendoAttack") + results = sqlite_instance.get_attack_results(attack_class="CrescendoAttack") assert len(results) == 2 assert {r.conversation_id for r in results} == {"conv_1", "conv_3"} -def test_get_attack_results_by_attack_type_no_match(sqlite_instance: MemoryInterface): - """Test that attack_type filter returns empty when nothing matches.""" +def test_get_attack_results_by_attack_class_no_match(sqlite_instance: MemoryInterface): + """Test that attack_class filter returns empty when nothing matches.""" ar1 = _make_attack_result_with_identifier("conv_1", "CrescendoAttack") sqlite_instance.add_attack_results_to_memory(attack_results=[ar1]) - results = sqlite_instance.get_attack_results(attack_type="NonExistentAttack") + results = sqlite_instance.get_attack_results(attack_class="NonExistentAttack") assert len(results) == 0 -def test_get_attack_results_by_attack_type_case_sensitive(sqlite_instance: MemoryInterface): - """Test that attack_type filter is case-sensitive (exact match).""" +def test_get_attack_results_by_attack_class_case_sensitive(sqlite_instance: MemoryInterface): + """Test that attack_class filter is case-sensitive (exact match).""" ar1 = _make_attack_result_with_identifier("conv_1", "CrescendoAttack") sqlite_instance.add_attack_results_to_memory(attack_results=[ar1]) - results = sqlite_instance.get_attack_results(attack_type="crescendoattack") + results = sqlite_instance.get_attack_results(attack_class="crescendoattack") assert len(results) == 0 -def test_get_attack_results_by_attack_type_no_identifier(sqlite_instance: MemoryInterface): - """Test that attacks with no attack_identifier (empty JSON) are excluded by attack_type filter.""" +def test_get_attack_results_by_attack_class_no_identifier(sqlite_instance: MemoryInterface): + """Test that attacks with no attack_identifier (empty JSON) are excluded by attack_class filter.""" ar1 = create_attack_result("conv_1", 1) # No attack_identifier → stored as {} ar2 = _make_attack_result_with_identifier("conv_2", "CrescendoAttack") sqlite_instance.add_attack_results_to_memory(attack_results=[ar1, ar2]) - results = sqlite_instance.get_attack_results(attack_type="CrescendoAttack") + results = sqlite_instance.get_attack_results(attack_class="CrescendoAttack") assert len(results) == 1 assert results[0].conversation_id == "conv_2" -def test_get_attack_results_converter_types_none_returns_all(sqlite_instance: MemoryInterface): - """Test that converter_types=None (omitted) returns all attacks unfiltered.""" +def test_get_attack_results_converter_classes_none_returns_all(sqlite_instance: MemoryInterface): + """Test that converter_classes=None (omitted) returns all attacks unfiltered.""" ar1 = _make_attack_result_with_identifier("conv_1", "Attack", ["Base64Converter"]) ar2 = _make_attack_result_with_identifier("conv_2", "Attack") # No converters (None) ar3 = create_attack_result("conv_3", 3) # No identifier at all sqlite_instance.add_attack_results_to_memory(attack_results=[ar1, ar2, ar3]) - results = sqlite_instance.get_attack_results(converter_types=None) + results = sqlite_instance.get_attack_results(converter_classes=None) assert len(results) == 3 -def test_get_attack_results_converter_types_empty_matches_no_converters(sqlite_instance: MemoryInterface): - """Test that converter_types=[] returns only attacks with no converters.""" +def test_get_attack_results_converter_classes_empty_matches_no_converters(sqlite_instance: MemoryInterface): + """Test that converter_classes=[] returns only attacks with no converters.""" ar_with_conv = _make_attack_result_with_identifier("conv_1", "Attack", ["Base64Converter"]) ar_no_conv_none = _make_attack_result_with_identifier("conv_2", "Attack") # converter_ids=None ar_no_conv_empty = _make_attack_result_with_identifier("conv_3", "Attack", []) # converter_ids=[] @@ -1211,7 +1211,7 @@ def test_get_attack_results_converter_types_empty_matches_no_converters(sqlite_i attack_results=[ar_with_conv, ar_no_conv_none, ar_no_conv_empty, ar_no_identifier] ) - results = sqlite_instance.get_attack_results(converter_types=[]) + results = sqlite_instance.get_attack_results(converter_classes=[]) conv_ids = {r.conversation_id for r in results} # Should include attacks with no converters (None key, empty array, or empty identifier) assert "conv_1" not in conv_ids, "Should not include attacks that have converters" @@ -1220,19 +1220,19 @@ def test_get_attack_results_converter_types_empty_matches_no_converters(sqlite_i assert "conv_4" in conv_ids, "Should include attacks with empty attack_identifier" -def test_get_attack_results_converter_types_single_match(sqlite_instance: MemoryInterface): +def test_get_attack_results_converter_classes_single_match(sqlite_instance: MemoryInterface): """Test that converter_types with one type returns attacks using that converter.""" ar1 = _make_attack_result_with_identifier("conv_1", "Attack", ["Base64Converter"]) ar2 = _make_attack_result_with_identifier("conv_2", "Attack", ["ROT13Converter"]) ar3 = _make_attack_result_with_identifier("conv_3", "Attack", ["Base64Converter", "ROT13Converter"]) sqlite_instance.add_attack_results_to_memory(attack_results=[ar1, ar2, ar3]) - results = sqlite_instance.get_attack_results(converter_types=["Base64Converter"]) + results = sqlite_instance.get_attack_results(converter_classes=["Base64Converter"]) conv_ids = {r.conversation_id for r in results} assert conv_ids == {"conv_1", "conv_3"} -def test_get_attack_results_converter_types_and_logic(sqlite_instance: MemoryInterface): +def test_get_attack_results_converter_classes_and_logic(sqlite_instance: MemoryInterface): """Test that multiple converter_types use AND logic — all must be present.""" ar1 = _make_attack_result_with_identifier("conv_1", "Attack", ["Base64Converter"]) ar2 = _make_attack_result_with_identifier("conv_2", "Attack", ["ROT13Converter"]) @@ -1240,32 +1240,32 @@ def test_get_attack_results_converter_types_and_logic(sqlite_instance: MemoryInt ar4 = _make_attack_result_with_identifier("conv_4", "Attack", ["Base64Converter", "ROT13Converter", "UrlConverter"]) sqlite_instance.add_attack_results_to_memory(attack_results=[ar1, ar2, ar3, ar4]) - results = sqlite_instance.get_attack_results(converter_types=["Base64Converter", "ROT13Converter"]) + results = sqlite_instance.get_attack_results(converter_classes=["Base64Converter", "ROT13Converter"]) conv_ids = {r.conversation_id for r in results} # conv_3 and conv_4 have both; conv_1 and conv_2 have only one assert conv_ids == {"conv_3", "conv_4"} -def test_get_attack_results_converter_types_case_insensitive(sqlite_instance: MemoryInterface): - """Test that converter type matching is case-insensitive.""" +def test_get_attack_results_converter_classes_case_insensitive(sqlite_instance: MemoryInterface): + """Test that converter class matching is case-insensitive.""" ar1 = _make_attack_result_with_identifier("conv_1", "Attack", ["Base64Converter"]) sqlite_instance.add_attack_results_to_memory(attack_results=[ar1]) - results = sqlite_instance.get_attack_results(converter_types=["base64converter"]) + results = sqlite_instance.get_attack_results(converter_classes=["base64converter"]) assert len(results) == 1 assert results[0].conversation_id == "conv_1" -def test_get_attack_results_converter_types_no_match(sqlite_instance: MemoryInterface): +def test_get_attack_results_converter_classes_no_match(sqlite_instance: MemoryInterface): """Test that converter_types filter returns empty when no attack has the converter.""" ar1 = _make_attack_result_with_identifier("conv_1", "Attack", ["Base64Converter"]) sqlite_instance.add_attack_results_to_memory(attack_results=[ar1]) - results = sqlite_instance.get_attack_results(converter_types=["NonExistentConverter"]) + results = sqlite_instance.get_attack_results(converter_classes=["NonExistentConverter"]) assert len(results) == 0 -def test_get_attack_results_attack_type_and_converter_types_combined(sqlite_instance: MemoryInterface): +def test_get_attack_results_attack_class_and_converter_classes_combined(sqlite_instance: MemoryInterface): """Test combining attack_type and converter_types filters.""" ar1 = _make_attack_result_with_identifier("conv_1", "CrescendoAttack", ["Base64Converter"]) ar2 = _make_attack_result_with_identifier("conv_2", "ManualAttack", ["Base64Converter"]) @@ -1273,77 +1273,77 @@ def test_get_attack_results_attack_type_and_converter_types_combined(sqlite_inst ar4 = _make_attack_result_with_identifier("conv_4", "CrescendoAttack") # No converters sqlite_instance.add_attack_results_to_memory(attack_results=[ar1, ar2, ar3, ar4]) - results = sqlite_instance.get_attack_results(attack_type="CrescendoAttack", converter_types=["Base64Converter"]) + results = sqlite_instance.get_attack_results(attack_class="CrescendoAttack", converter_classes=["Base64Converter"]) assert len(results) == 1 assert results[0].conversation_id == "conv_1" -def test_get_attack_results_attack_type_with_no_converters(sqlite_instance: MemoryInterface): - """Test combining attack_type with converter_types=[] (no converters).""" +def test_get_attack_results_attack_class_with_no_converters(sqlite_instance: MemoryInterface): + """Test combining attack_type with converter_classes=[] (no converters).""" ar1 = _make_attack_result_with_identifier("conv_1", "CrescendoAttack", ["Base64Converter"]) ar2 = _make_attack_result_with_identifier("conv_2", "CrescendoAttack") # No converters ar3 = _make_attack_result_with_identifier("conv_3", "ManualAttack") # No converters sqlite_instance.add_attack_results_to_memory(attack_results=[ar1, ar2, ar3]) - results = sqlite_instance.get_attack_results(attack_type="CrescendoAttack", converter_types=[]) + results = sqlite_instance.get_attack_results(attack_class="CrescendoAttack", converter_classes=[]) assert len(results) == 1 assert results[0].conversation_id == "conv_2" # ============================================================================ -# Unique attack type and converter type name tests +# Unique attack class and converter class name tests # ============================================================================ -def test_get_unique_attack_type_names_empty(sqlite_instance: MemoryInterface): +def test_get_unique_attack_class_names_empty(sqlite_instance: MemoryInterface): """Test that no attacks returns empty list.""" - result = sqlite_instance.get_unique_attack_type_names() + result = sqlite_instance.get_unique_attack_class_names() assert result == [] -def test_get_unique_attack_type_names_sorted_unique(sqlite_instance: MemoryInterface): - """Test that unique type names are returned sorted, with duplicates removed.""" +def test_get_unique_attack_class_names_sorted_unique(sqlite_instance: MemoryInterface): + """Test that unique class names are returned sorted, with duplicates removed.""" ar1 = _make_attack_result_with_identifier("conv_1", "CrescendoAttack") ar2 = _make_attack_result_with_identifier("conv_2", "ManualAttack") ar3 = _make_attack_result_with_identifier("conv_3", "CrescendoAttack") sqlite_instance.add_attack_results_to_memory(attack_results=[ar1, ar2, ar3]) - result = sqlite_instance.get_unique_attack_type_names() + result = sqlite_instance.get_unique_attack_class_names() assert result == ["CrescendoAttack", "ManualAttack"] -def test_get_unique_attack_type_names_skips_empty_identifier(sqlite_instance: MemoryInterface): +def test_get_unique_attack_class_names_skips_empty_identifier(sqlite_instance: MemoryInterface): """Test that attacks with empty attack_identifier (no class_name) are excluded.""" ar_no_id = create_attack_result("conv_1", 1) # No attack_identifier → stored as {} ar_with_id = _make_attack_result_with_identifier("conv_2", "CrescendoAttack") sqlite_instance.add_attack_results_to_memory(attack_results=[ar_no_id, ar_with_id]) - result = sqlite_instance.get_unique_attack_type_names() + result = sqlite_instance.get_unique_attack_class_names() assert result == ["CrescendoAttack"] -def test_get_unique_converter_type_names_empty(sqlite_instance: MemoryInterface): +def test_get_unique_converter_class_names_empty(sqlite_instance: MemoryInterface): """Test that no attacks returns empty list.""" - result = sqlite_instance.get_unique_converter_type_names() + result = sqlite_instance.get_unique_converter_class_names() assert result == [] -def test_get_unique_converter_type_names_sorted_unique(sqlite_instance: MemoryInterface): - """Test that unique converter type names are returned sorted, with duplicates removed.""" +def test_get_unique_converter_class_names_sorted_unique(sqlite_instance: MemoryInterface): + """Test that unique converter class names are returned sorted, with duplicates removed.""" ar1 = _make_attack_result_with_identifier("conv_1", "Attack", ["Base64Converter", "ROT13Converter"]) ar2 = _make_attack_result_with_identifier("conv_2", "Attack", ["Base64Converter"]) sqlite_instance.add_attack_results_to_memory(attack_results=[ar1, ar2]) - result = sqlite_instance.get_unique_converter_type_names() + result = sqlite_instance.get_unique_converter_class_names() assert result == ["Base64Converter", "ROT13Converter"] -def test_get_unique_converter_type_names_skips_no_converters(sqlite_instance: MemoryInterface): +def test_get_unique_converter_class_names_skips_no_converters(sqlite_instance: MemoryInterface): """Test that attacks with no converters don't contribute names.""" ar_no_conv = _make_attack_result_with_identifier("conv_1", "Attack") # No converters ar_with_conv = _make_attack_result_with_identifier("conv_2", "Attack", ["Base64Converter"]) ar_empty_id = create_attack_result("conv_3", 3) # Empty attack_identifier sqlite_instance.add_attack_results_to_memory(attack_results=[ar_no_conv, ar_with_conv, ar_empty_id]) - result = sqlite_instance.get_unique_converter_type_names() + result = sqlite_instance.get_unique_converter_class_names() assert result == ["Base64Converter"]