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 fa1ea39a8d..106bb2bada 100644 --- a/pyrit/backend/mappers/attack_mappers.py +++ b/pyrit/backend/mappers/attack_mappers.py @@ -4,16 +4,29 @@ """ 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. """ from __future__ import annotations +import base64 +import logging import mimetypes +import os +import time import uuid -from datetime import datetime, timezone +from collections.abc import Sequence +from datetime import datetime, timedelta, timezone from typing import TYPE_CHECKING, Optional, 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,40 +35,211 @@ 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 +logger = logging.getLogger(__name__) + if TYPE_CHECKING: from collections.abc import Sequence + from pyrit.models.conversation_stats import ConversationStats + # ============================================================================ # 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.""" + 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: + """ + 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( + account_name=storage_account_name, + container_name=container_name, + user_delegation_key=delegation_key, + permission=ContainerSasPermissions(read=True), + 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 +252,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 +286,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 +328,117 @@ 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. + + Returns: + Optional[str]: A filename like ``image_a1b2c3d4.png``, or ``None`` for text-like types. + """ + # 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( 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 fb40e0656e..018c26115c 100644 --- a/pyrit/backend/models/attacks.py +++ b/pyrit/backend/models/attacks.py @@ -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,14 +75,22 @@ 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')") + 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" ) @@ -87,20 +101,23 @@ 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( + 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") + conversation_id: str = Field(..., description="Conversation identifier") messages: list[Message] = Field(default_factory=list, description="All messages in order") @@ -130,11 +147,6 @@ class ConverterOptionsResponse(BaseModel): ) -# ============================================================================ -# Create Attack -# ============================================================================ - - # ============================================================================ # Message Input Models # ============================================================================ @@ -161,11 +173,30 @@ 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 ) @@ -175,7 +206,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") @@ -190,6 +222,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 # ============================================================================ @@ -210,9 +301,23 @@ class AddMessageRequest(BaseModel): default=True, description="If True, send to target and wait for response. If False, just store in memory.", ) + 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): @@ -225,4 +330,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..d021189df3 100644 --- a/pyrit/backend/models/targets.py +++ b/pyrit/backend/models/targets.py @@ -26,15 +26,16 @@ 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") + 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") diff --git a/pyrit/backend/routes/attacks.py b/pyrit/backend/routes/attacks.py index d5028bd6d6..17bd727f58 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 logging from typing import Literal, Optional from fastapi import APIRouter, HTTPException, Query, status @@ -15,18 +16,25 @@ 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 from pyrit.backend.services.attack_service import get_attack_service +logger = logging.getLogger(__name__) + router = APIRouter(prefix="/attacks", tags=["attacks"]) @@ -55,16 +63,14 @@ async def list_attacks( attack_type: Optional[str] = Query(None, description="Filter by exact attack type name"), converter_types: Optional[list[str]] = Query( None, - description=( - "Filter by converter type 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. @@ -104,8 +110,8 @@ async def get_attack_options() -> AttackOptionsResponse: AttackOptionsResponse: Sorted list of unique attack type names. """ service = get_attack_service() - class_names = await service.get_attack_options_async() - return AttackOptionsResponse(attack_types=class_names) + type_names = await service.get_attack_options_async() + return AttackOptionsResponse(attack_types=type_names) @router.get( @@ -123,8 +129,8 @@ async def get_converter_options() -> ConverterOptionsResponse: ConverterOptionsResponse: Sorted list of unique converter type names. """ service = get_attack_service() - class_names = await service.get_converter_options_async() - return ConverterOptionsResponse(converter_types=class_names) + type_names = await service.get_converter_options_async() + return ConverterOptionsResponse(converter_types=type_names) @router.post( @@ -142,7 +148,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. @@ -159,13 +165,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. @@ -176,25 +182,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: """ @@ -207,46 +213,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), + ) from 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"}, @@ -254,7 +374,7 @@ async def get_attack_messages(conversation_id: str) -> AttackMessagesResponse: }, ) async def add_message( - conversation_id: str, + attack_result_id: str, request: AddMessageRequest, ) -> AddMessageResponse: """ @@ -275,7 +395,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(): @@ -288,7 +408,8 @@ async def add_message( detail=error_msg, ) from e except Exception as e: + logger.exception("Failed to add message to attack '%s'", attack_result_id) raise HTTPException( status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, - detail=f"Failed to add message: {str(e)}", + detail="Internal server error. Check server logs for details.", ) 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 badc3ffe08..0b232f5533 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, Literal, Optional, 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,17 @@ 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.models import ( + AttackOutcome, + AttackResult, + ConversationStats, + ConversationType, + PromptDataType, + data_serializer_factory, +) +from pyrit.models import ( + Message as PyritMessage, +) from pyrit.prompt_normalizer import PromptConverterConfiguration, PromptNormalizer @@ -78,7 +95,7 @@ async def list_attacks_async( Queries AttackResult entries from the database. Args: - attack_type: Filter by exact attack class_name (case-sensitive). + 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). @@ -95,7 +112,7 @@ async def list_attacks_async( # Phase 1: Query + lightweight filtering (no pieces needed) attack_results = self._memory.get_attack_results( outcome=outcome, - labels=labels, + labels=labels if labels else None, attack_class=attack_type, converter_classes=converter_types, ) @@ -116,13 +133,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] = [] 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 +179,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() 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() - 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 +265,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 +319,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 +330,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 +347,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 +359,332 @@ 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 + ] - # Re-add to memory (this should update) - self._memory.add_attack_results_to_memory(attack_results=[ar]) + updated_metadata = dict(ar.metadata or {}) + updated_metadata["updated_at"] = now.isoformat() - return await self.get_attack_async(conversation_id=conversation_id) + 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, + }, + ) - async def add_message_async(self, *, conversation_id: str, request: AddMessageRequest) -> AddMessageResponse: + 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 + + # 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, + ) + + # 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, *, 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 " + f"{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, + ) - # Update attack timestamp - ar.metadata["updated_at"] = datetime.now(timezone.utc).isoformat() + # 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() - attack_detail = await self.get_attack_async(conversation_id=conversation_id) + self._memory.update_attack_result_by_id( + attack_result_id=attack_result_id, + update_fields=update_fields, + ) + + 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,102 @@ def _paginate_attack_results( has_more = len(items) > start_idx + limit return page, has_more + # ======================================================================== + # 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 +828,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, ) -> 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 +848,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 +865,76 @@ 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, ) -> 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/pyrit/cli/frontend_core.py b/pyrit/cli/frontend_core.py index b131b3cf4f..b3ad2a770e 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/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_targets.py b/pyrit/setup/initializers/airt_targets.py index 5f335eb052..bc04ec05d0 100644 --- a/pyrit/setup/initializers/airt_targets.py +++ b/pyrit/setup/initializers/airt_targets.py @@ -14,7 +14,7 @@ import logging import os -from dataclasses import dataclass +from dataclasses import dataclass, field from typing import Any, Optional from pyrit.auth import get_azure_openai_auth, get_azure_token_provider @@ -46,6 +46,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. @@ -169,6 +170,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, @@ -244,12 +254,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) @@ -311,6 +320,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 @@ -426,6 +436,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/backend/test_api_routes.py b/tests/unit/backend/test_api_routes.py index 3725dc21c7..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, @@ -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, @@ -486,6 +491,24 @@ 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_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( + 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?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["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: @@ -504,6 +527,122 @@ def test_list_attacks_forwards_converter_types_param(self, client: TestClient) - 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 + # ============================================================================ # Target Routes Tests @@ -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 7ed17497ea..da1337c71d 100644 --- a/tests/unit/backend/test_attack_service.py +++ b/tests/unit/backend/test_attack_service.py @@ -14,6 +14,7 @@ from pyrit.backend.models.attacks import ( AddMessageRequest, + ChangeMainConversationRequest, CreateAttackRequest, MessagePieceRequest, PrependedMessageRequest, @@ -25,6 +26,7 @@ ) from pyrit.identifiers import ComponentIdentifier from pyrit.models import AttackOutcome, AttackResult +from pyrit.models.conversation_stats import ConversationStats @pytest.fixture @@ -34,6 +36,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 +52,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 +65,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 +86,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 +94,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, @@ -174,7 +192,7 @@ async def test_list_attacks_returns_attacks(self, attack_service, mock_memory) - @pytest.mark.asyncio 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 as attack_class.""" + """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 = [] @@ -207,7 +225,7 @@ async def test_list_attacks_filters_by_no_converters(self, attack_service, mock_ 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_types_and_logic(self, attack_service, mock_memory) -> None: @@ -244,9 +262,9 @@ async def test_list_attacks_filters_by_converter_types_and_logic(self, attack_se assert len(result.items) == 1 assert result.items[0].conversation_id == "attack-1" - # Verify converter_types was forwarded to the memory layer as converter_classes + # 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 +298,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.""" @@ -386,7 +426,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 +440,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 +448,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 +514,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 +532,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 +560,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 +583,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 +615,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 +668,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 +714,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 +736,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 +759,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 +772,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 +788,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 +802,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 +817,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 +840,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 +860,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 +886,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 +895,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 +951,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 +960,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 +984,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 +1007,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 +1028,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 +1049,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 +1068,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 +1139,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 +1209,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 +1275,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 +1329,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 +1346,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 +1369,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 +1405,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..ba80c8eb31 100644 --- a/tests/unit/backend/test_mappers.py +++ b/tests/unit/backend/test_mappers.py @@ -8,14 +8,23 @@ without any database or service dependencies. """ +import dataclasses +import os +import tempfile +import uuid from datetime import datetime, timezone -from unittest.mock import MagicMock +from unittest.mock import AsyncMock, MagicMock, patch + +import pytest 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 +33,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 +130,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 +246,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 +316,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 +347,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 +356,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 +376,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 +402,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 +808,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 +870,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_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_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_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 +940,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 +973,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 +1072,32 @@ 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 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/memory/memory_interface/test_interface_attack_results.py b/tests/unit/memory/memory_interface/test_interface_attack_results.py index 57e6f4cf78..30a1c600b2 100644 --- a/tests/unit/memory/memory_interface/test_interface_attack_results.py +++ b/tests/unit/memory/memory_interface/test_interface_attack_results.py @@ -1221,7 +1221,7 @@ def test_get_attack_results_converter_classes_empty_matches_no_converters(sqlite def test_get_attack_results_converter_classes_single_match(sqlite_instance: MemoryInterface): - """Test that converter_classes with one class returns attacks using that converter.""" + """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"]) @@ -1233,7 +1233,7 @@ def test_get_attack_results_converter_classes_single_match(sqlite_instance: Memo def test_get_attack_results_converter_classes_and_logic(sqlite_instance: MemoryInterface): - """Test that multiple converter_classes use AND logic — all must be present.""" + """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"]) @@ -1257,7 +1257,7 @@ def test_get_attack_results_converter_classes_case_insensitive(sqlite_instance: 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.""" + """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]) @@ -1266,7 +1266,7 @@ def test_get_attack_results_converter_classes_no_match(sqlite_instance: MemoryIn def test_get_attack_results_attack_class_and_converter_classes_combined(sqlite_instance: MemoryInterface): - """Test combining attack_class and converter_classes filters.""" + """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"]) @@ -1279,7 +1279,7 @@ def test_get_attack_results_attack_class_and_converter_classes_combined(sqlite_i def test_get_attack_results_attack_class_with_no_converters(sqlite_instance: MemoryInterface): - """Test combining attack_class with converter_classes=[] (no converters).""" + """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