diff --git a/doc/code/scoring/0_scoring.ipynb b/doc/code/scoring/0_scoring.ipynb index b379fbddd2..b93e152f4a 100644 --- a/doc/code/scoring/0_scoring.ipynb +++ b/doc/code/scoring/0_scoring.ipynb @@ -402,8 +402,8 @@ "\n", "Most of the time a scorer is handed to an attack as the **objective scorer** that decides\n", "whether the objective was met. Here a `SubStringScorer` and a local `TextTarget` keep the\n", - "example offline. `TextTarget` just records the prompt and returns no assistant content, so\n", - "there is nothing substantive for the scorer to flag — swap in an LLM-backed\n", + "example offline. `TextTarget` only records the prompt and never replies, so there is no response\n", + "for the scorer to judge and the outcome is `UNDETERMINED` — swap in an LLM-backed\n", "[target](../targets/0_prompt_targets.md) (and any scorer) to score a real model response." ] }, @@ -425,9 +425,9 @@ "output_type": "stream", "text": [ "\n", - "\u001b[31m════════════════════════════════════════════════════════════════════════════════════════════════════\u001b[0m\n", - "\u001b[1m\u001b[31m ❌ ATTACK RESULT: FAILURE ❌ \u001b[0m\n", - "\u001b[31m════════════════════════════════════════════════════════════════════════════════════════════════════\u001b[0m\n", + "\u001b[33m════════════════════════════════════════════════════════════════════════════════════════════════════\u001b[0m\n", + "\u001b[1m\u001b[33m ❓ ATTACK RESULT: UNDETERMINED ❓ \u001b[0m\n", + "\u001b[33m════════════════════════════════════════════════════════════════════════════════════════════════════\u001b[0m\n", "\n", "\u001b[1m\u001b[44m\u001b[37m Attack Summary \u001b[0m\n", "\u001b[34m────────────────────────────────────────────────────────────────────────────────────────────────────\u001b[0m\n", @@ -441,14 +441,8 @@ "\u001b[32m • Execution Time: 42ms\u001b[0m\n", "\n", "\u001b[1m 🎯 Outcome\u001b[0m\n", - "\u001b[31m • Status: ❌ FAILURE\u001b[0m\n", - "\u001b[37m • Reason: Failed to achieve objective after 1 attempts\u001b[0m\n", - "\n", - "\u001b[1m Final Score\u001b[0m\n", - " Scorer: SubStringScorer\n", - "\u001b[95m • Category: ['hate']\u001b[0m\n", - "\u001b[36m • Type: true_false\u001b[0m\n", - "\u001b[31m • Value: false\u001b[0m\n", + "\u001b[33m • Status: ❓ UNDETERMINED\u001b[0m\n", + "\u001b[37m • Reason: Objective target returned no response to score\u001b[0m\n", "\n", "\u001b[1m\u001b[44m\u001b[37m Conversation History with Objective Target \u001b[0m\n", "\u001b[34m────────────────────────────────────────────────────────────────────────────────────────────────────\u001b[0m\n", diff --git a/doc/code/scoring/0_scoring.py b/doc/code/scoring/0_scoring.py index 9a243e9bef..3de91f05f4 100644 --- a/doc/code/scoring/0_scoring.py +++ b/doc/code/scoring/0_scoring.py @@ -257,8 +257,8 @@ # # Most of the time a scorer is handed to an attack as the **objective scorer** that decides # whether the objective was met. Here a `SubStringScorer` and a local `TextTarget` keep the -# example offline. `TextTarget` just records the prompt and returns no assistant content, so -# there is nothing substantive for the scorer to flag — swap in an LLM-backed +# example offline. `TextTarget` only records the prompt and never replies, so there is no response +# for the scorer to judge and the outcome is `UNDETERMINED` — swap in an LLM-backed # [target](../targets/0_prompt_targets.md) (and any scorer) to score a real model response. # %% from pyrit.executor.attack import AttackScoringConfig, PromptSendingAttack diff --git a/doc/code/targets/0_prompt_targets.md b/doc/code/targets/0_prompt_targets.md index a4e59b8128..ad22561ecc 100644 --- a/doc/code/targets/0_prompt_targets.md +++ b/doc/code/targets/0_prompt_targets.md @@ -89,7 +89,7 @@ requested temperature, resolved value, and source. Unknown provider defaults rem ## Chat-style targets vs general targets -A `PromptTarget` is a generic place to send a prompt. With PyRIT, the idea is that it will eventually be consumed by an AI application, but that doesn't have to be immediate. For example, you could have a SharePoint target. Everything you send a prompt to is a `PromptTarget`. Many attacks work generically with any `PromptTarget` including `RedTeamingAttack` and `PromptSendingAttack`. +A `PromptTarget` is a generic place to send a prompt. With PyRIT, the idea is that it will eventually be consumed by an AI application, but that doesn't have to be immediate. For example, you could have a SharePoint target. Everything you send a prompt to is a `PromptTarget`. Most attacks need the target's responses, so they require `supports_responses`. `PromptSendingAttack` and the attacks built on it also work with write-only targets such as `TextTarget` and `AzureBlobStorageTarget`: the request is never scored as a response, and only scorers that judge side effects (such as `FileWriteScorer`) decide the outcome. With some algorithms, you want to send a prompt, set a system prompt, and modify conversation history (including PAIR [@chao2023pair], TAP [@mehrotra2023tap], and flip attack [@liu2024flipattack]). These algorithms require a target whose [`TargetCapabilities`](#target-capabilities) declare both `supports_multi_turn=True` and `supports_editable_history=True` — i.e. you can modify a conversation history. Consumers express this requirement via `CHAT_TARGET_REQUIREMENTS` and validate it against `target.configuration` at construction time. See [Target Capabilities](#target-capabilities) below for the full list of capabilities and how they compose into a `TargetConfiguration`. @@ -283,6 +283,7 @@ A `TargetConfiguration` composes three concerns: | `supports_json_output` | The target supports a "json" response format that guarantees valid JSON output. | | `supports_json_schema` | The target supports constraining output to a caller-provided JSON schema. | | `supports_temperature` | The adapter and configured model mode support per-request temperature overrides. | +| `supports_responses` | The target replies to requests. Defaults to `True`; write-only targets such as `TextTarget` and `AzureBlobStorageTarget` declare `False`. | | `input_modalities` | The set of input modality combinations the target accepts (e.g. `{text}`, `{text, image_path}`). | | `output_modalities` | The set of output modality combinations the target produces. | diff --git a/pyrit/backend/services/chat_scoring_service.py b/pyrit/backend/services/chat_scoring_service.py index 2ab1eaa8e4..fa6bc76784 100644 --- a/pyrit/backend/services/chat_scoring_service.py +++ b/pyrit/backend/services/chat_scoring_service.py @@ -69,6 +69,7 @@ class ChatEvaluation: score: Score | None = None failure: ScoringFailure | None = None reused: bool = False + side_effect_evidence_only: bool = False @dataclass(frozen=True) @@ -285,6 +286,7 @@ async def evaluate_async( scorer: Scorer | None, error: str | None = None, reuse: bool = False, + side_effect_evidence_only: bool = False, ) -> ChatEvaluation: """ Evaluate a saved response, or reuse a complete stored result for the same evaluation. @@ -297,24 +299,48 @@ async def evaluate_async( scorer (Scorer | None): The resolved scorer, or None when it could not be resolved. error (str | None): Why the scorer could not be resolved. Defaults to None. reuse (bool): Return a complete stored result instead of evaluating again. Defaults to False. + side_effect_evidence_only (bool): Judge only side effects, without publishing the anchor + as a target response. Defaults to False. Returns: The score or failure, and whether a stored result was reused. """ - if reuse and scorer is not None and error is None: + if ( + reuse + and scorer is not None + and error is None + and (not side_effect_evidence_only or scorer.judges_side_effects()) + ): existing = await self._complete_result_async(scorer=scorer, selection=selection, response=response) if existing is not None: - return ChatEvaluation(selection=selection, response=response, score=existing, reused=True) + return ChatEvaluation( + selection=selection, + response=response, + score=existing, + reused=True, + side_effect_evidence_only=side_effect_evidence_only, + ) piece = response.message_pieces[0] try: if error is not None or scorer is None: raise ValueError(error or "The chat scorer is unavailable.") results = await score_attack_response_async( - response=response, objective_scorer=scorer, auxiliary_scorers=[], expectation=selection.expectation + response=response, + objective_scorer=scorer, + auxiliary_scorers=[], + expectation=selection.expectation, + side_effect_evidence_only=side_effect_evidence_only, ) if not results["objective_scores"]: + if side_effect_evidence_only: + return ChatEvaluation(selection=selection, response=response, side_effect_evidence_only=True) raise ValueError("The scorer did not return an objective score.") - return ChatEvaluation(selection=selection, response=response, score=results["objective_scores"][0]) + return ChatEvaluation( + selection=selection, + response=response, + score=results["objective_scores"][0], + side_effect_evidence_only=side_effect_evidence_only, + ) except Exception as exc: logger.exception("Chat scoring failed for response '%s'.", piece.id) failure = ScoringFailure( @@ -324,7 +350,12 @@ async def evaluate_async( conversation_id=str(piece.conversation_id), error=error or self.failure_detail(exception=exc, response_id=str(piece.id)), ) - return ChatEvaluation(selection=selection, response=response, failure=failure) + return ChatEvaluation( + selection=selection, + response=response, + failure=failure, + side_effect_evidence_only=side_effect_evidence_only, + ) async def publish_async( self, @@ -366,7 +397,7 @@ async def publish_async( if message_fields is not None: fields.update(message_fields(attack)) if current: - fields.update(self._evaluation_fields(attack=attack, evaluation=evaluation)) + fields.update(await self._evaluation_fields_async(attack=attack, evaluation=evaluation)) try: await memory.update_attack_result_conditionally_async( attack_result_id=attack_result_id, @@ -557,7 +588,7 @@ async def _complete_result_async( ) return next((score for score in matches if not score.is_undetermined), None) - def _evaluation_fields(self, *, attack: AttackResult, evaluation: ChatEvaluation) -> dict[str, Any]: + async def _evaluation_fields_async(self, *, attack: AttackResult, evaluation: ChatEvaluation) -> dict[str, Any]: """ Prepare the attack fields that record an evaluation for the current selection. @@ -573,8 +604,28 @@ def _evaluation_fields(self, *, attack: AttackResult, evaluation: ChatEvaluation fields: dict[str, Any] = {"attack_metadata": {AttackResult.SCORING_ERRORS_KEY: errors}} if not self.is_latest_response(attack=attack, piece=piece): return fields + if evaluation.side_effect_evidence_only: + memory = CentralMemory.get_memory_instance() + anchor_ids = {str(anchor.id) for anchor in evaluation.response.message_pieces} + # Storage spaces out tied piece timestamps within a message, so compare stored times on both sides. + stored_anchor = await memory.get_message_pieces_async(prompt_ids=list(anchor_ids)) + anchor_timestamp = max(anchor.timestamp for anchor in stored_anchor or evaluation.response.message_pieces) + newer = await memory.get_message_pieces_async( + attack_result_id=attack.attack_result_id, + sent_after=anchor_timestamp, + ) + conversations = attack.get_active_conversation_ids() + if any( + str(message.id) not in anchor_ids + and message.timestamp > anchor_timestamp + and str(message.conversation_id) in conversations + for message in newer + ): + return fields score = evaluation.score - fields.update(last_response_id=piece.id, automated_score_id=score.id if score else None) + fields["automated_score_id"] = score.id if score else None + if not evaluation.side_effect_evidence_only: + fields["last_response_id"] = piece.id if attack.human_score is None: fields.update( outcome=(attack_outcome_from_score(score) if score else AttackOutcome.UNDETERMINED).value, @@ -595,6 +646,7 @@ def _publication_guard(attack: AttackResult) -> dict[str, Any]: "attack_metadata": attack.metadata, "human_score_id": attack.human_score.id if attack.human_score else None, "last_response_id": attack.last_response.id if attack.last_response else None, + "automated_score_id": attack.automated_score.id if attack.automated_score else None, } async def _apply_context_async( diff --git a/pyrit/backend/services/message_send_service.py b/pyrit/backend/services/message_send_service.py index c6a4d16e3d..8bebd3a01c 100644 --- a/pyrit/backend/services/message_send_service.py +++ b/pyrit/backend/services/message_send_service.py @@ -61,7 +61,7 @@ ) from pyrit.models.component_spec import TargetBinding from pyrit.prompt_normalizer import ConverterConfiguration, PromptNormalizer -from pyrit.prompt_target import PromptTarget +from pyrit.prompt_target import CapabilityName, PromptTarget from pyrit.prompt_target.common.target_send_context import TargetSendContext from pyrit.score import Scorer @@ -791,15 +791,22 @@ async def _execute_message_async( ) if progress is not None: progress.state = MessageSendState.FINALIZING - response = await self._stored_response_async( - conversation_id=msg_conversation_id, delivered=delivered_response, prior_ids=prior_ids + responds = target.configuration.includes(capability=CapabilityName.RESPONSES) + response = ( + await self._stored_response_async( + conversation_id=msg_conversation_id, delivered=delivered_response, prior_ids=prior_ids + ) + if responds + else None ) last_response = response.message_pieces[0] if response is not None else None - if response is not None and validated.scoring is not None: + scoring_anchor = response if responds else delivered_response + if scoring_anchor is not None and validated.scoring is not None: evaluation = await self._score_chat_response_async( - response=response, + response=scoring_anchor, validated=validated, progress=progress, + side_effect_evidence_only=not responds, ) else: await self._store_message_only_async( @@ -849,6 +856,7 @@ async def _score_chat_response_async( response: Message, validated: _ValidatedMessage, progress: MessageSendConversation | None, + side_effect_evidence_only: bool = False, ) -> ChatEvaluation: """ Evaluate the delivered response with the scoring selection captured at admission. @@ -865,6 +873,7 @@ async def _score_chat_response_async( response=response, scorer=validated.scorer, error=validated.scoring_error, + side_effect_evidence_only=side_effect_evidence_only, ) finally: if progress is not None: diff --git a/pyrit/executor/attack/compound/sequential_attack.py b/pyrit/executor/attack/compound/sequential_attack.py index 5a281f7c37..b5bbd6a80d 100644 --- a/pyrit/executor/attack/compound/sequential_attack.py +++ b/pyrit/executor/attack/compound/sequential_attack.py @@ -43,6 +43,7 @@ AttackSeedGroup, ScoringExpectation, ) +from pyrit.prompt_target import TargetRequirements if TYPE_CHECKING: from collections.abc import Mapping, Sequence @@ -214,6 +215,9 @@ class SequentialAttack(AttackStrategy[AttackContext[AttackParameters], Sequentia DELEGATES_SCORING: ClassVar[bool] = True FIXED_PARAMS_TYPE = AttackParameters.excluding("next_message", "prepended_conversation") + # Each child attack validates its own target, so the compound adds no requirement. + TARGET_REQUIREMENTS: ClassVar[TargetRequirements] = TargetRequirements() + RESULT_ROLE: ClassVar[AttackResultRole] = AttackResultRole.ORCHESTRATION IS_COMPOUND: ClassVar[bool] = True diff --git a/pyrit/executor/attack/core/attack_scoring.py b/pyrit/executor/attack/core/attack_scoring.py index ea309880dd..9a190b3845 100644 --- a/pyrit/executor/attack/core/attack_scoring.py +++ b/pyrit/executor/attack/core/attack_scoring.py @@ -77,20 +77,37 @@ async def score_attack_response_async( objective_scorer: Scorer | None, auxiliary_scorers: Sequence[Scorer] | None, expectation: ScoringExpectation | None, + side_effect_evidence_only: bool = False, ) -> dict[str, list[Score]]: """ Score an attack response with the objective scorer and the auxiliary scorers that apply. + Args: + response (Message): The message that anchors scoring for the turn. + objective_scorer (Scorer | None): The scorer that decides the attack outcome. + auxiliary_scorers (Sequence[Scorer] | None): Additional scorers whose results are stored. + expectation (ScoringExpectation | None): The scoring question. + side_effect_evidence_only (bool): Run only scorers that judge side effects (see + ``Scorer.judges_side_effects``). Use this for a target that never replies, so the + message it handed back is never judged as a response. + Returns: dict[str, list[Score]]: The ``objective_scores`` and ``auxiliary_scores``. """ prepared = prepare_attack_scoring( objective_scorer=objective_scorer, auxiliary_scorers=auxiliary_scorers, expectation=expectation ) + auxiliary = list(zip(prepared.auxiliary_scorers, prepared.auxiliary_expectations, strict=True)) + if side_effect_evidence_only: + if objective_scorer is not None and not objective_scorer.judges_side_effects(): + objective_scorer = None + auxiliary = [(scorer, selected) for scorer, selected in auxiliary if scorer.judges_side_effects()] + if objective_scorer is None and not auxiliary: + return {"objective_scores": [], "auxiliary_scores": []} return await MessageScorer.score_response_async( response=response, objective_scorer=objective_scorer, - auxiliary_scorers=prepared.auxiliary_scorers, + auxiliary_scorers=[scorer for scorer, _ in auxiliary], expectation=prepared.objective_expectation, - auxiliary_expectations=prepared.auxiliary_expectations, + auxiliary_expectations=[selected for _, selected in auxiliary], ) diff --git a/pyrit/executor/attack/core/attack_strategy.py b/pyrit/executor/attack/core/attack_strategy.py index ef23492aac..2ead40ab56 100644 --- a/pyrit/executor/attack/core/attack_strategy.py +++ b/pyrit/executor/attack/core/attack_strategy.py @@ -52,7 +52,7 @@ TargetIdentifier, UndeterminedScoreError, ) -from pyrit.prompt_target import TargetRequirements +from pyrit.prompt_target import CapabilityName, TargetRequirements from pyrit.score import AttemptObserver if TYPE_CHECKING: @@ -73,7 +73,7 @@ from pyrit.executor.attack.core.attack_executor import ActiveAttackExecution from pyrit.executor.attack.core.attack_result_attribution import AttackResultAttribution from pyrit.message_normalizer import MessageListNormalizer - from pyrit.prompt_target import CapabilityName, PromptTarget + from pyrit.prompt_target import PromptTarget from pyrit.score import Scorer AttackStrategyContextT = TypeVar("AttackStrategyContextT", bound="AttackContext[Any]") @@ -734,7 +734,11 @@ class AttackStrategy(Strategy[AttackStrategyContextT, AttackStrategyResultT], Id #: Capability requirements placed on ``objective_target``. Subclasses #: override to declare what the attack needs. Validated in ``__init__``. - TARGET_REQUIREMENTS: ClassVar[TargetRequirements] = TargetRequirements() + #: Attacks need the target's responses by default. An override keeps + #: ``CapabilityName.RESPONSES`` unless the attack supports write-only targets. + TARGET_REQUIREMENTS: ClassVar[TargetRequirements] = TargetRequirements( + native_required=frozenset({CapabilityName.RESPONSES}) + ) ADVERSARIAL_TARGET_REQUIREMENTS: ClassVar[TargetRequirements] = TargetRequirements() #: A fixed execution-input contract for attacks that do not expose ``params_type``. FIXED_PARAMS_TYPE: ClassVar[type[AttackParameters] | None] = None diff --git a/pyrit/executor/attack/multi_turn/chunked_request.py b/pyrit/executor/attack/multi_turn/chunked_request.py index 68e5357628..946f0ab13b 100644 --- a/pyrit/executor/attack/multi_turn/chunked_request.py +++ b/pyrit/executor/attack/multi_turn/chunked_request.py @@ -94,9 +94,9 @@ class ChunkedRequestAttack(MultiTurnAttackStrategy[ChunkedRequestAttackContext, # remembering prior responses. History-squash adaptation would collapse # them into a single prompt and silently break the attack's semantics. # Declare MULTI_TURN as ``native_required`` so adaptation is rejected at - # construction time. + # construction time. It also reassembles the target's responses, so it needs them. TARGET_REQUIREMENTS = TargetRequirements( - native_required=frozenset({CapabilityName.MULTI_TURN}), + native_required=frozenset({CapabilityName.MULTI_TURN, CapabilityName.RESPONSES}), ) @apply_defaults diff --git a/pyrit/executor/attack/multi_turn/crescendo.py b/pyrit/executor/attack/multi_turn/crescendo.py index fc2eeeaf28..6da069ec4d 100644 --- a/pyrit/executor/attack/multi_turn/crescendo.py +++ b/pyrit/executor/attack/multi_turn/crescendo.py @@ -136,8 +136,11 @@ class CrescendoAttack(MultiTurnAttackStrategy[CrescendoAttackContext, CrescendoA # Crescendo relies on native live history for both gradual escalation and # backtracking. Squashed or non-editable history changes those semantics. + # Each turn's response drives the next escalation step. TARGET_REQUIREMENTS = TargetRequirements( - native_required=frozenset({CapabilityName.EDITABLE_HISTORY, CapabilityName.MULTI_TURN}), + native_required=frozenset( + {CapabilityName.EDITABLE_HISTORY, CapabilityName.MULTI_TURN, CapabilityName.RESPONSES} + ), ) # Default system prompt template path for Crescendo attack diff --git a/pyrit/executor/attack/multi_turn/multi_prompt_sending.py b/pyrit/executor/attack/multi_turn/multi_prompt_sending.py index 5959b48296..cbb193249d 100644 --- a/pyrit/executor/attack/multi_turn/multi_prompt_sending.py +++ b/pyrit/executor/attack/multi_turn/multi_prompt_sending.py @@ -132,9 +132,9 @@ class MultiPromptSendingAttack(MultiTurnAttackStrategy[MultiTurnAttackContext[An # conversation state between them. History-squash adaptation would collapse # them into one message and silently break the attack's sequencing # semantics. Declare MULTI_TURN as ``native_required`` so adaptation is - # rejected at construction time. + # rejected at construction time. The final response is what gets scored. TARGET_REQUIREMENTS = TargetRequirements( - native_required=frozenset({CapabilityName.MULTI_TURN}), + native_required=frozenset({CapabilityName.MULTI_TURN, CapabilityName.RESPONSES}), ) FIXED_PARAMS_TYPE = MultiPromptSendingAttackParameters diff --git a/pyrit/executor/attack/single_turn/prompt_sending.py b/pyrit/executor/attack/single_turn/prompt_sending.py index 99b796bc79..ecec4c1db5 100644 --- a/pyrit/executor/attack/single_turn/prompt_sending.py +++ b/pyrit/executor/attack/single_turn/prompt_sending.py @@ -66,8 +66,15 @@ class PromptSendingAttack(SingleTurnAttackStrategy): The strategy supports customization through prepended conversations, converters, and multiple scorer types for comprehensive evaluation. + + A target that never replies (``supports_responses=False``, e.g. ``TextTarget``) is + supported: the sent request is never scored as a response, and only scorers that judge + side effects (e.g. a written file or invoked tools) decide the outcome. """ + # Unlike other attacks, prompt sending also works against targets that never reply. + TARGET_REQUIREMENTS = TargetRequirements() + @apply_defaults def __init__( self, @@ -225,6 +232,9 @@ async def _perform_async(self, *, context: SingleTurnAttackContext[Any]) -> Atta # Execute with retries response = None score = None + # A target that never replies hands back the sent request (or a delivery receipt), which + # must not be judged as a response; only side-effect scorers can judge such a turn. + target_responds = self._objective_target_responds() # Attack execution steps: # 1) Construct the seed prompt(s) that will be injected into the conversation @@ -255,9 +265,16 @@ async def _perform_async(self, *, context: SingleTurnAttackContext[Any]) -> Atta # Score the response including auxiliary and objective scoring score = await self._evaluate_response_async( - response=response, objective=context.objective, expectation=context.expectation + response=response, + objective=context.objective, + expectation=context.expectation, + side_effect_evidence_only=not target_responds, ) + if not target_responds and score is None: + # Nothing judged the turn, and retrying would only deliver the request again. + break + # If there is no objective, we have a response but can't determine success if not self._objective_scorer: break @@ -281,7 +298,7 @@ async def _perform_async(self, *, context: SingleTurnAttackContext[Any]) -> Atta return self._create_attack_result( context=context, - response=response, + response=response if target_responds else None, score=score, outcome=outcome, outcome_reason=outcome_reason, @@ -337,6 +354,10 @@ def _determine_attack_outcome( # No scorer means we can't determine success/failure return AttackOutcome.UNDETERMINED, "No objective scorer configured" + if score is None and not self._objective_target_responds(): + # The objective scorer judges responses, and this target never replies. + return AttackOutcome.UNDETERMINED, "Objective target returned no response to score" + if score: outcome = attack_outcome_from_score(score) if outcome is AttackOutcome.SUCCESS: @@ -358,6 +379,15 @@ def _determine_attack_outcome( # No response at all (all attempts filtered/failed) return AttackOutcome.FAILURE, "All attempts were filtered or failed to get a response" + def _objective_target_responds(self) -> bool: + """ + Check whether the objective target replies to the requests it receives. + + Returns: + bool: False for a target that only delivers requests, such as ``TextTarget``. + """ + return self._objective_target.configuration.includes(capability=CapabilityName.RESPONSES) + async def _teardown_async(self, *, context: SingleTurnAttackContext[Any]) -> None: """Clean up after attack execution.""" # Nothing to be done here, no-op @@ -426,6 +456,7 @@ async def _evaluate_response_async( response: Message, objective: str, expectation: ScoringExpectation, + side_effect_evidence_only: bool = False, ) -> Score | None: """ Evaluate the response against the objective using the configured scorers. @@ -437,6 +468,8 @@ async def _evaluate_response_async( response (Message): The response from the model. objective (str): The natural-language description of the attack's objective. expectation (ScoringExpectation): The effective scoring question. + side_effect_evidence_only (bool): Run only scorers that judge side-effect evidence, for a + target that never replies. Defaults to False. Returns: Score | None: The score from the objective scorer if configured, or None if @@ -453,6 +486,7 @@ async def _evaluate_response_async( objective_scorer=self._objective_scorer, auxiliary_scorers=self._auxiliary_scorers, expectation=expectation, + side_effect_evidence_only=side_effect_evidence_only, ) if not self._objective_scorer: diff --git a/pyrit/executor/attack/streaming/barge_in.py b/pyrit/executor/attack/streaming/barge_in.py index c6c8b711e0..aa2e5a8493 100644 --- a/pyrit/executor/attack/streaming/barge_in.py +++ b/pyrit/executor/attack/streaming/barge_in.py @@ -62,6 +62,7 @@ class BargeInAttack(AttackStrategy["BargeInAttackContext[Any]", AttackResult]): TARGET_REQUIREMENTS: ClassVar[TargetRequirements] = TargetRequirements( required=frozenset({CapabilityName.STREAMING_AUDIO}), + native_required=frozenset({CapabilityName.RESPONSES}), ) @apply_defaults diff --git a/pyrit/models/score/scorable.py b/pyrit/models/score/scorable.py index 38166cd475..1237bd0f5a 100644 --- a/pyrit/models/score/scorable.py +++ b/pyrit/models/score/scorable.py @@ -5,7 +5,7 @@ import uuid # noqa: TC003 (runtime-required by Pydantic field annotations) from abc import ABC -from typing import TYPE_CHECKING, Annotated, Any, Literal, Self, get_args +from typing import TYPE_CHECKING, Annotated, Any, ClassVar, Literal, Self, get_args from pydantic import BaseModel, ConfigDict, Field, TypeAdapter, model_validator @@ -36,6 +36,10 @@ class Scorable(BaseModel, ABC): # root type; each scorer family declares its ow # Pydantic Baseclass overrride: we want frozen models and to forbid extras. model_config = ConfigDict(frozen=True, extra="forbid") + #: Whether this evidence records what the target did (written files, invoked tools) rather + #: than what it said. Only such evidence can judge a target that never replies. + RECORDS_SIDE_EFFECTS: ClassVar[bool] = False + def names_same_evidence(self, other: Scorable | None) -> bool: """ Check whether ``other`` names the same evidence. @@ -164,6 +168,8 @@ class ConversationScorable(Scorable): class TraceScorable(Scorable): """An exact trace scope supplied by the caller.""" + RECORDS_SIDE_EFFECTS: ClassVar[bool] = True + scorable_type: Literal["trace"] = "trace" trace_ids: tuple[TraceId, ...] @@ -194,6 +200,8 @@ class SurfaceScorable(Scorable): the content there. """ + RECORDS_SIDE_EFFECTS: ClassVar[bool] = True + scorable_type: Literal["surface"] = "surface" uri: str = Field(min_length=1, pattern=r"^[^\x00]+$") match: SurfaceMatch = SurfaceMatch.EXACT diff --git a/pyrit/models/target/target_capabilities.py b/pyrit/models/target/target_capabilities.py index 7c7e6e1fe4..6eb6f457d0 100644 --- a/pyrit/models/target/target_capabilities.py +++ b/pyrit/models/target/target_capabilities.py @@ -52,6 +52,7 @@ class CapabilityName(str, Enum): PREFILL = "supports_prefill" TEMPERATURE = "supports_temperature" WEB_SEARCH = "supports_web_search" + RESPONSES = "supports_responses" class TargetCapabilities(BaseModel): @@ -121,6 +122,11 @@ class attribute. Users can override individual capabilities per instance #: Whether web search is configured and available to this target. supports_web_search: bool = False + #: Whether the target replies to the requests it receives. Write-only targets + #: (e.g., ``TextTarget``) deliver each request without replying, so a send that + #: returns no response is a successful delivery rather than a missing response. + supports_responses: bool = True + #: The input modalities supported by the target, as combinations of data types #: (e.g., ``{{"text"}, {"image_path", "text"}}``). Serialized as a sorted list of #: sorted lists — see ``_sorted_modality_combinations``. diff --git a/pyrit/prompt_normalizer/prompt_normalizer.py b/pyrit/prompt_normalizer/prompt_normalizer.py index ef166158f5..e0da3ccb23 100644 --- a/pyrit/prompt_normalizer/prompt_normalizer.py +++ b/pyrit/prompt_normalizer/prompt_normalizer.py @@ -46,16 +46,6 @@ _T = TypeVar("_T") -def _is_write_only_response(responses: object) -> bool: - """ - Distinguish a write-only target's empty list from a malformed None response. - - Returns: - bool: Whether the target returned an empty list. - """ - return isinstance(responses, list) and len(responses) == 0 - - class _TargetInvocationContext: """Track dispatch without changing caller-independent history selection.""" @@ -146,7 +136,8 @@ async def send_prompt_async( history selection and send lifecycle state. Returns: - Message: The response received from the target. + Message: The response received from the target. A target without + ``supports_responses`` may return nothing, and then this is the sent request. Raises: Exception: If an error occurs during the request processing. @@ -242,9 +233,9 @@ async def send_prompt_async( # handling empty responses message list and None responses if not responses or not any(responses): - # An empty list is valid for write-only targets (e.g., TextTarget) - # that don't produce responses. Return the request as-is. - if _is_write_only_response(responses): + # A target that declares it never replies (e.g., TextTarget) delivered the request, so + # return it as-is. Any other target returning nothing gets an empty error response. + if not target.configuration.includes(capability=CapabilityName.RESPONSES): return request empty_response = construct_response_from_request( request=request.message_pieces[0], diff --git a/pyrit/prompt_target/a2a_target.py b/pyrit/prompt_target/a2a_target.py index f812cf1313..e2f14739f4 100644 --- a/pyrit/prompt_target/a2a_target.py +++ b/pyrit/prompt_target/a2a_target.py @@ -215,7 +215,9 @@ def _validate_capabilities(capabilities: TargetCapabilities) -> None: if modalities != frozenset({frozenset({"text"})}): raise ValueError(f"A2ATarget only supports text {name} modality.") for capability in CapabilityName: - if capability != CapabilityName.MULTI_TURN and capabilities.includes(capability=capability): + if capability not in (CapabilityName.MULTI_TURN, CapabilityName.RESPONSES) and capabilities.includes( + capability=capability + ): raise ValueError(f"A2ATarget does not support {capability.value}.") def apply_capabilities(self, *, capabilities: TargetCapabilities) -> None: diff --git a/pyrit/prompt_target/azure_blob_storage_target.py b/pyrit/prompt_target/azure_blob_storage_target.py index b77764edaf..9c718ce236 100644 --- a/pyrit/prompt_target/azure_blob_storage_target.py +++ b/pyrit/prompt_target/azure_blob_storage_target.py @@ -59,6 +59,9 @@ class AzureBlobStorageTarget(PromptTarget): destination_parameters: ClassVar[Mapping[str, bool]] = MappingProxyType({"container_url": True}) environment_backed_parameters: ClassVar[frozenset[str]] = frozenset({"container_url"}) + # The returned blob URL is a delivery receipt, not a reply, so it is never scored as one. + _SUPPORTS_RESPONSES: ClassVar[bool] = False + _DEFAULT_CONFIGURATION: TargetConfiguration = TargetConfiguration( capabilities=TargetCapabilities( input_modalities=frozenset( diff --git a/pyrit/prompt_target/common/prompt_target.py b/pyrit/prompt_target/common/prompt_target.py index 5462452dcb..346109107d 100644 --- a/pyrit/prompt_target/common/prompt_target.py +++ b/pyrit/prompt_target/common/prompt_target.py @@ -76,6 +76,9 @@ class PromptTarget(Identifiable): _DEFAULT_TRACE_ENABLED: ClassVar[bool] = False _SUPPORTS_TOOL_CALL_HISTORY: ClassVar[bool] = False _SUPPORTED_GENERATION_CAPABILITIES: ClassVar[frozenset[CapabilityName]] = frozenset() + # Adapters that only deliver content (e.g. to a stream or a blob) and never reply set this to + # False. ``supports_responses`` is then False under every configuration, including saved ones. + _SUPPORTS_RESPONSES: ClassVar[bool] = True _DISPATCH_CAPABILITIES: ClassVar[ContextVar[tuple["PromptTarget", TargetCapabilities] | None]] = ContextVar( "target_dispatch_capabilities", default=None ) @@ -263,7 +266,7 @@ def __init__( if custom_configuration is not None else type(self).get_default_configuration(self._underlying_model) ) - capabilities = self._mask_generation_capabilities(capabilities=self.capabilities) + capabilities = self._mask_unimplemented_capabilities(capabilities=self.capabilities) if capabilities is not self.capabilities: self.apply_capabilities(capabilities=capabilities) if custom_configuration is None and underlying_model is None and self._SUPPORTS_TOOL_CALL_HISTORY: @@ -945,7 +948,7 @@ def capabilities_scope(self, capabilities: TargetCapabilities) -> Generator[None """ configuration = self.configuration scoped = TargetConfiguration( - capabilities=capabilities, + capabilities=self._mask_unimplemented_capabilities(capabilities=capabilities), policy=configuration.policy, normalizer_overrides=configuration.normalizer_overrides, ) @@ -1022,24 +1025,29 @@ def apply_capabilities(self, *, capabilities: TargetCapabilities) -> None: this instance. """ self._configuration = TargetConfiguration( - capabilities=self._mask_generation_capabilities(capabilities=capabilities), + capabilities=self._mask_unimplemented_capabilities(capabilities=capabilities), policy=self._configuration.policy, normalizer_overrides=self._configuration.normalizer_overrides, ) @classmethod - def _mask_generation_capabilities(cls, *, capabilities: TargetCapabilities) -> TargetCapabilities: + def _mask_unimplemented_capabilities(cls, *, capabilities: TargetCapabilities) -> TargetCapabilities: """ - Disable generation options that this adapter does not implement. + Disable capabilities that this adapter does not implement. + + These are generation options outside ``_SUPPORTED_GENERATION_CAPABILITIES`` and, for an + adapter with ``_SUPPORTS_RESPONSES = False``, responses. Returns: - TargetCapabilities: Capabilities restricted to the adapter's implemented generation options. + TargetCapabilities: Capabilities restricted to what the adapter implements. """ unsupported = { capability.value: False for capability in RequestGenerationConfig.FIELD_CAPABILITIES.values() if capability not in cls._SUPPORTED_GENERATION_CAPABILITIES and capabilities.includes(capability=capability) } + if not cls._SUPPORTS_RESPONSES and capabilities.supports_responses: + unsupported[CapabilityName.RESPONSES.value] = False return capabilities.model_copy(update=unsupported) if unsupported else capabilities @classmethod @@ -1061,7 +1069,7 @@ def get_default_configuration(cls, underlying_model: str | None = None) -> Targe known = get_known_capabilities(underlying_model) if known is not None: return TargetConfiguration( - capabilities=cls._mask_generation_capabilities( + capabilities=cls._mask_unimplemented_capabilities( capabilities=known.model_copy( update={ "supports_prefill": cls._DEFAULT_CONFIGURATION.capabilities.supports_prefill, @@ -1081,7 +1089,7 @@ def get_default_configuration(cls, underlying_model: str | None = None) -> Targe cls.__name__, ) configuration = cls._DEFAULT_CONFIGURATION - capabilities = cls._mask_generation_capabilities(capabilities=configuration.capabilities) + capabilities = cls._mask_unimplemented_capabilities(capabilities=configuration.capabilities) if capabilities is configuration.capabilities: return configuration return TargetConfiguration( diff --git a/pyrit/prompt_target/text_target.py b/pyrit/prompt_target/text_target.py index 6541323f98..472b0589f5 100644 --- a/pyrit/prompt_target/text_target.py +++ b/pyrit/prompt_target/text_target.py @@ -22,6 +22,9 @@ class TextTarget(PromptTarget): # Writes to a local stream and never contacts a service, so it takes no credentials. supported_auth_modes: ClassVar[tuple[AuthMode, ...]] = () + # Writing to a stream never produces a reply. + _SUPPORTS_RESPONSES: ClassVar[bool] = False + def __init__( self, *, diff --git a/pyrit/score/scorer.py b/pyrit/score/scorer.py index d01c0b8d41..98db978d73 100644 --- a/pyrit/score/scorer.py +++ b/pyrit/score/scorer.py @@ -422,6 +422,23 @@ def get_supported_scorable_types(self) -> frozenset[type[Scorable]]: .intersection(*(child.get_supported_scorable_types() for child in children[1:])) ) + def judges_side_effects(self) -> bool: + """ + Check whether every leaf judges what the target did rather than what it said. + + A leaf judges side effects when it accepts evidence that records them (e.g. a written + file or a tool trace); handed a message, it uses it only as an anchor for that evidence. + Such scorers can judge a target that never replies. A composite qualifies only when all + of its leaves do, though they may read different kinds of side effects. + + Returns: + bool: True when every leaf judges side-effect evidence. + """ + children = self._get_child_scorers() + if self.SUPPORTED_SCORABLE_TYPES or not children: + return any(scorable_type.RECORDS_SIDE_EFFECTS for scorable_type in self.get_supported_scorable_types()) + return all(child.judges_side_effects() for child in children) + def _get_child_scorers(self) -> tuple[Scorer, ...]: """Return the wrapped scorers, or an empty tuple for a leaf.""" return () diff --git a/tests/unit/backend/mocks.py b/tests/unit/backend/mocks.py index 285d705371..463ad6031a 100644 --- a/tests/unit/backend/mocks.py +++ b/tests/unit/backend/mocks.py @@ -12,7 +12,7 @@ from pyrit.backend.models.message_sends import MessageSendState, MessageSendStatus from pyrit.backend.services.message_send_service import MessageSendService from pyrit.memory import MemoryInterface -from pyrit.models import AtomicAttackIdentifier, AttackOutcome, AttackResult, ComponentIdentifier +from pyrit.models import AtomicAttackIdentifier, AttackOutcome, AttackResult, CapabilityName, ComponentIdentifier from pyrit.prompt_target import PromptTarget from unit.async_utils import TEST_WATCHDOG_SECONDS @@ -95,6 +95,8 @@ def _make_matching_target_mock() -> MagicMock: class_name="TextTarget", class_module="pyrit.prompt_target", ) + # Like the TextTarget it stands in for, it declares no response support. + mock_target.configuration.includes.side_effect = lambda *, capability: capability is not CapabilityName.RESPONSES return mock_target diff --git a/tests/unit/backend/test_chat_scoring.py b/tests/unit/backend/test_chat_scoring.py index a82f96c04c..93d559b2ea 100644 --- a/tests/unit/backend/test_chat_scoring.py +++ b/tests/unit/backend/test_chat_scoring.py @@ -6,6 +6,8 @@ import asyncio import uuid from collections.abc import AsyncIterator +from datetime import UTC, datetime, timedelta +from pathlib import Path from typing import Any from unittest.mock import AsyncMock, MagicMock, patch @@ -42,6 +44,7 @@ AttackOutcome, AttackResult, ComponentIdentifier, + ContentWritten, ConversationReference, ConversationType, MatchesObjective, @@ -59,7 +62,9 @@ from pyrit.models.results.attack_result import AttackScoringInputs from pyrit.registry import ScorerRegistry from pyrit.score import ( + FileWriteScorer, FloatScaleThresholdScorer, + LocalFileSurfaceSource, ManualScorer, MessageFloatScaleScorer, MessageToolCallScorer, @@ -1886,6 +1891,263 @@ async def test_store_only_and_missing_objective_do_not_score_async( assert score.call_count == 0 +@pytest.mark.parametrize("role", ["user", "assistant"]) +async def test_write_only_delivery_is_not_scored_whatever_its_role_async( + scoring_chat: tuple[MessageSendService, AttackResult, MockPromptTarget, SubStringScorer], + sqlite_instance: SQLiteMemory, + role: str, +) -> None: + service, attack, target, scorer = scoring_chat + target.apply_capabilities(capabilities=target.capabilities.model_copy(update={"supports_responses": False})) + # The request matches the scorer, so scoring the delivered request would report success. + request = chat_request(attack).model_copy( + update={"role": role, "pieces": [MessagePieceRequest(original_value="default request")]} + ) + with ( + patch.object(target, "_send_prompt_to_target_async", return_value=[]), + patch.object(scorer, "score_async", wraps=scorer.score_async) as score, + ): + await service.add_message_async(attack_result_id=attack.attack_result_id, request=request) + + assert score.call_count == 0 + [stored] = await sqlite_instance.get_attack_results_async(attack_result_ids=[attack.attack_result_id]) + assert stored.automated_score is None + assert stored.last_response is None + assert stored.outcome is not AttackOutcome.SUCCESS + messages = await sqlite_instance.get_conversation_messages_async(conversation_id=attack.conversation_id) + assert [message.api_role for message in messages] == [role] + + +@pytest.mark.parametrize("receipt", [False, True]) +@pytest.mark.parametrize("writes_file", [False, True]) +async def test_write_only_send_scores_inherited_side_effects_without_a_response_async( + *, + scoring_chat: tuple[MessageSendService, AttackResult, MockPromptTarget, SubStringScorer], + sqlite_instance: SQLiteMemory, + tmp_path: Path, + receipt: bool, + writes_file: bool, +) -> None: + service, attack, target, _ = scoring_chat + target.apply_capabilities(capabilities=target.capabilities.model_copy(update={"supports_responses": False})) + scorer = FileWriteScorer(source=LocalFileSurfaceSource(root=tmp_path)) + ScorerRegistry.get_registry_singleton().instances.register(scorer, name="file-judge") + reference = RegisteredComponentReference(registry_name="file-judge", identifier_hash=scorer.get_identifier().hash) + expectation = ScoringExpectation(objective=attack.objective, conditions=(ContentWritten(uri="/result.txt"),)) + receipt_timestamp = datetime.now(UTC) + timedelta(days=1) + await sqlite_instance.update_attack_result_by_id_async( + attack_result_id=attack.attack_result_id, + update_fields={ + "attack_metadata": AttackScoringInputs( + scorer=reference, revision="inherited-file", inherited=True, expectation=expectation + ).to_metadata() + }, + ) + + async def deliver_async(*, normalized_conversation: list[Message]) -> list[Message]: + if writes_file: + await asyncio.to_thread((tmp_path / "result.txt").write_text, "delivered", encoding="utf-8") + return ( + [ + MessagePiece( + original_value="Delivery receipt", + role="assistant", + conversation_id=attack.conversation_id, + timestamp=receipt_timestamp, + ).to_message() + ] + if receipt + else [] + ) + + with patch.object(target, "_send_prompt_to_target_async", side_effect=deliver_async): + request = chat_request(attack).model_copy( + update={ + "pieces": [ + MessagePieceRequest(original_value="Write the result"), + MessagePieceRequest(original_value="Keep this request as one multipart turn"), + ] + } + ) + if not receipt and not writes_file: + status = await service.submit_async( + attack_result_id=attack.attack_result_id, + request=MessageSendRequest(**request.model_dump(), submission_id="multipart-delivery", count=2), + ) + for _ in range(100): + status = await service.get_status_async( + attack_result_id=attack.attack_result_id, send_id=status.send_id, wait_ms=1000 + ) + if status.state in ("completed", "failed"): + break + assert status.state == "completed" and status.failure_stage is None + [published] = await sqlite_instance.get_attack_results_async(attack_result_ids=[attack.attack_result_id]) + assert published.automated_score is not None + pieces = await sqlite_instance.get_message_pieces_async(attack_result_id=attack.attack_result_id) + scores = await sqlite_instance.get_prompt_scores_async(prompt_ids=[piece.id for piece in pieces]) + assert len(scores) == 2 + # The two evaluations run concurrently, so score creation order need not follow delivery order; + # the ordering tests below pin which delivery's verdict wins. + assert published.automated_score.id in {score.id for score in scores} + else: + await service.add_message_async(attack_result_id=attack.attack_result_id, request=request) + + [stored] = await sqlite_instance.get_attack_results_async(attack_result_ids=[attack.attack_result_id]) + assert stored.last_response is None + assert stored.automated_score is not None + assert stored.automated_score.get_value() is writes_file + assert stored.automated_score.scored_expectation == expectation + assert stored.automated_score.observation_ids + assert stored.outcome == (AttackOutcome.SUCCESS if writes_file else AttackOutcome.FAILURE) + assert stored.get_scoring_failure(attack.conversation_id) is None + if receipt: + branch = await AttackService().create_related_conversation_async( + attack_result_id=attack.attack_result_id, request=CreateConversationRequest() + ) + assert branch is not None + with patch.object(target, "_send_prompt_to_target_async", side_effect=deliver_async): + await service.add_message_async( + attack_result_id=attack.attack_result_id, + request=chat_request(attack).model_copy(update={"target_conversation_id": branch.conversation_id}), + ) + [repeated] = await sqlite_instance.get_attack_results_async(attack_result_ids=[attack.attack_result_id]) + assert repeated.last_response is None + assert repeated.automated_score is not None and repeated.automated_score.id != stored.automated_score.id + assert repeated.automated_score.get_value() is writes_file + + +async def test_older_write_only_evaluation_cannot_replace_newer_conversation_score_async( + *, + scoring_chat: tuple[MessageSendService, AttackResult, MockPromptTarget, SubStringScorer], + sqlite_instance: SQLiteMemory, + tmp_path: Path, +) -> None: + service, attack, target, _ = scoring_chat + target.apply_capabilities(capabilities=target.capabilities.model_copy(update={"supports_responses": False})) + scorer = FileWriteScorer(source=LocalFileSurfaceSource(root=tmp_path)) + ScorerRegistry.get_registry_singleton().instances.register(scorer, name="ordered-file-judge") + reference = RegisteredComponentReference( + registry_name="ordered-file-judge", identifier_hash=scorer.get_identifier().hash + ) + await sqlite_instance.update_attack_result_by_id_async( + attack_result_id=attack.attack_result_id, + update_fields={ + "attack_metadata": AttackScoringInputs( + scorer=reference, + revision="ordered-file", + expectation=ScoringExpectation(conditions=(ContentWritten(uri="/result.txt"),)), + ).to_metadata() + }, + ) + branch = await AttackService().create_related_conversation_async( + attack_result_id=attack.attack_result_id, request=CreateConversationRequest() + ) + assert branch is not None + entered, release = asyncio.Event(), asyncio.Event() + original = scorer.score_async + + async def deliver_async(*, normalized_conversation: list[Message]) -> list[Message]: + if normalized_conversation[-1].get_piece().conversation_id == branch.conversation_id: + await asyncio.to_thread((tmp_path / "result.txt").write_text, "delivered", encoding="utf-8") + return [] + + async def delay_old_score_async(**kwargs: Any) -> list[Score]: + scores = await original(**kwargs) + if scores[0].get_value() is False: + entered.set() + await release.wait() + return scores + + with ( + patch.object(target, "_send_prompt_to_target_async", side_effect=deliver_async), + patch.object(scorer, "score_async", side_effect=delay_old_score_async), + ): + older = asyncio.create_task( + service.add_message_async(attack_result_id=attack.attack_result_id, request=chat_request(attack)) + ) + try: + await wait_for_event_async(event=entered, tasks=[older]) + await service.add_message_async( + attack_result_id=attack.attack_result_id, + request=chat_request(attack).model_copy(update={"target_conversation_id": branch.conversation_id}), + ) + [newer] = await sqlite_instance.get_attack_results_async(attack_result_ids=[attack.attack_result_id]) + assert newer.automated_score is not None and newer.automated_score.get_value() is True + release.set() + await wait_for_completion_async(future=older) + finally: + release.set() + await drain_tasks_async(older) + + [stored] = await sqlite_instance.get_attack_results_async(attack_result_ids=[attack.attack_result_id]) + assert stored.last_response is None + assert stored.automated_score is not None and stored.automated_score.id == newer.automated_score.id + assert stored.outcome == AttackOutcome.SUCCESS + + +async def test_equal_time_multipart_write_only_delivery_replaces_earlier_score_async( + *, + scoring_chat: tuple[MessageSendService, AttackResult, MockPromptTarget, SubStringScorer], + sqlite_instance: SQLiteMemory, + tmp_path: Path, +) -> None: + service, attack, target, _ = scoring_chat + target.apply_capabilities(capabilities=target.capabilities.model_copy(update={"supports_responses": False})) + scorer = FileWriteScorer(source=LocalFileSurfaceSource(root=tmp_path)) + ScorerRegistry.get_registry_singleton().instances.register(scorer, name="tied-file-judge") + reference = RegisteredComponentReference( + registry_name="tied-file-judge", identifier_hash=scorer.get_identifier().hash + ) + await sqlite_instance.update_attack_result_by_id_async( + attack_result_id=attack.attack_result_id, + update_fields={ + "attack_metadata": AttackScoringInputs( + scorer=reference, + revision="tied-file", + expectation=ScoringExpectation(conditions=(ContentWritten(uri="/result.txt"),)), + ).to_metadata() + }, + ) + branch = await AttackService().create_related_conversation_async( + attack_result_id=attack.attack_result_id, request=CreateConversationRequest() + ) + assert branch is not None + + async def deliver_async(*, normalized_conversation: list[Message]) -> list[Message]: + if normalized_conversation[-1].get_piece().conversation_id == branch.conversation_id: + await asyncio.to_thread((tmp_path / "result.txt").write_text, "delivered", encoding="utf-8") + return [] + + multipart = chat_request(attack).model_copy( + update={ + "pieces": [ + MessagePieceRequest(original_value="Write the result"), + MessagePieceRequest(original_value="Keep this request as one multipart turn"), + ] + } + ) + # A coarse clock gives both deliveries' pieces one timestamp; storage spaces out each message's later piece. + tick = datetime.now(UTC) + with ( + patch.object(target, "_send_prompt_to_target_async", side_effect=deliver_async), + patch("pyrit.models.messages.message_piece.datetime") as clock, + ): + clock.now.return_value = tick + for conversation_id in (attack.conversation_id, branch.conversation_id): + await service.add_message_async( + attack_result_id=attack.attack_result_id, + request=multipart.model_copy(update={"target_conversation_id": conversation_id}), + ) + + pieces = await sqlite_instance.get_message_pieces_async(attack_result_id=attack.attack_result_id) + spaced = tick + timedelta(microseconds=1) + assert sorted(piece.timestamp for piece in pieces) == [tick, tick, spaced, spaced] + [stored] = await sqlite_instance.get_attack_results_async(attack_result_ids=[attack.attack_result_id]) + assert stored.last_response is None + assert stored.automated_score is not None and stored.automated_score.get_value() is True + assert stored.outcome == AttackOutcome.SUCCESS + + @pytest.mark.parametrize("scoring_failure", [False, True]) async def test_repeated_submission_scores_each_response_once_async( scoring_chat: tuple[MessageSendService, AttackResult, MockPromptTarget, SubStringScorer], diff --git a/tests/unit/backend/test_message_send_service.py b/tests/unit/backend/test_message_send_service.py index 98bb0226b9..bc67a1d21c 100644 --- a/tests/unit/backend/test_message_send_service.py +++ b/tests/unit/backend/test_message_send_service.py @@ -337,7 +337,11 @@ async def test_add_message_with_send_sends_via_normalizer(self, message_send_ser patch("pyrit.backend.services.message_send_service.PromptNormalizer") as mock_normalizer_cls, ): mock_target_svc = MagicMock() - mock_target_svc.get_target_object.return_value = _make_matching_target_mock() + target = _make_matching_target_mock() + # Unlike the TextTarget the mock stands in for, this target replies. + target.configuration.includes.side_effect = None + target.configuration.includes.return_value = True + mock_target_svc.get_target_object.return_value = target mock_get_target_svc.return_value = mock_target_svc mock_normalizer = MagicMock() @@ -2510,6 +2514,9 @@ async def test_normalizer_owns_persistence_async( request.request_converter_configurations = [ConverterConfigurationRequest(converter_ids=["base64"])] elif failure == "response-converter": request.response_converter_configurations = [ConverterConfigurationRequest(converter_ids=["base64"])] + if failure == "write-only": + # Only a target that declares no response support turns an empty reply into a delivery. + target.apply_capabilities(capabilities=target.capabilities.model_copy(update={"supports_responses": False})) component = target if failure in {"target", "write-only"} else converter method = "_send_prompt_to_target_async" if failure in {"target", "write-only"} else "convert_async" with patch.object( diff --git a/tests/unit/executor/attack/core/test_attack_scoring.py b/tests/unit/executor/attack/core/test_attack_scoring.py index f1694e3631..8990d4b0bc 100644 --- a/tests/unit/executor/attack/core/test_attack_scoring.py +++ b/tests/unit/executor/attack/core/test_attack_scoring.py @@ -17,10 +17,13 @@ ComponentIdentifier, Condition, MessagePiece, + MessageScorable, Scorable, ScorableUnion, Score, ScoringExpectation, + SurfaceScorable, + TraceScorable, ) from pyrit.score import TrueFalseCompositeScorer, TrueFalseScoreAggregator, TrueFalseScorer @@ -68,6 +71,18 @@ class _ConfiguredScorer(_FirstScorer): CONDITION_TYPE = None +class _SurfaceSecondScorer(_SecondScorer): + SUPPORTED_SCORABLE_TYPES = (MessageScorable, SurfaceScorable) + + +class _TraceFirstScorer(_FirstScorer): + SUPPORTED_SCORABLE_TYPES = (MessageScorable, TraceScorable) + + +class _MessageFirstScorer(_FirstScorer): + SUPPORTED_SCORABLE_TYPES = (MessageScorable,) + + def _expectation() -> ScoringExpectation: return ScoringExpectation(objective="context", conditions=(_FirstCondition(), _SecondCondition())) @@ -186,3 +201,83 @@ def test_attack_warns_once_before_execution_when_auxiliary_is_skipped(caplog: py with caplog.at_level(logging.WARNING): attack._validate_scoring_expectation(context=context) assert "_SecondScorer will not run" in caplog.text + + +@pytest.mark.usefixtures("patch_central_database") +async def test_side_effect_evidence_only_skips_message_scorers_async(sqlite_instance: MemoryInterface) -> None: + objective, message_auxiliary, surface_auxiliary = _SecondScorer(), _SecondScorer(), _SurfaceSecondScorer() + expectation = ScoringExpectation(conditions=(_SecondCondition(),)) + + results = await score_attack_response_async( + response=(await _stored_response_async(sqlite_instance)), + objective_scorer=objective, + auxiliary_scorers=[message_auxiliary, surface_auxiliary], + expectation=expectation, + side_effect_evidence_only=True, + ) + + assert results["objective_scores"] == [] + assert objective.expectations == message_auxiliary.expectations == [] + assert surface_auxiliary.expectations == [expectation] + assert [score.scorer_class_identifier for score in results["auxiliary_scores"]] == [ + surface_auxiliary.get_identifier() + ] + + +@pytest.mark.usefixtures("patch_central_database") +async def test_side_effect_evidence_only_runs_trace_objective_scorer_async(sqlite_instance: MemoryInterface) -> None: + objective = _TraceFirstScorer() + + results = await score_attack_response_async( + response=(await _stored_response_async(sqlite_instance)), + objective_scorer=objective, + auxiliary_scorers=[], + expectation=ScoringExpectation(conditions=(_FirstCondition(),)), + side_effect_evidence_only=True, + ) + + assert objective.expectations == [ScoringExpectation(conditions=(_FirstCondition(),))] + assert [score.get_value() for score in results["objective_scores"]] == [True] + + +@pytest.mark.usefixtures("patch_central_database") +async def test_side_effect_evidence_only_with_no_applicable_scorer_scores_nothing_async( + sqlite_instance: MemoryInterface, +) -> None: + objective = _FirstScorer() + + results = await score_attack_response_async( + response=(await _stored_response_async(sqlite_instance)), + objective_scorer=objective, + auxiliary_scorers=None, + expectation=ScoringExpectation(conditions=(_FirstCondition(),)), + side_effect_evidence_only=True, + ) + + assert results == {"objective_scores": [], "auxiliary_scores": []} + assert objective.expectations == [] + + +@pytest.mark.usefixtures("patch_central_database") +@pytest.mark.parametrize("all_leaves_read_side_effects", [True, False]) +async def test_side_effect_evidence_only_checks_every_leaf_of_a_composite_async( + sqlite_instance: MemoryInterface, all_leaves_read_side_effects: bool +) -> None: + surface, other = ( + _SurfaceSecondScorer(), + (_TraceFirstScorer() if all_leaves_read_side_effects else _MessageFirstScorer()), + ) + objective = TrueFalseCompositeScorer(scorers=[other, surface], aggregator=TrueFalseScoreAggregator.AND) + + results = await score_attack_response_async( + response=(await _stored_response_async(sqlite_instance)), + objective_scorer=objective, + auxiliary_scorers=[], + expectation=_expectation(), + side_effect_evidence_only=True, + ) + + # Leaves that read different side effects together accept only a message, but still run. + assert objective.get_supported_scorable_types() == frozenset({MessageScorable}) + assert bool(results["objective_scores"]) is all_leaves_read_side_effects + assert bool(surface.expectations) is all_leaves_read_side_effects diff --git a/tests/unit/executor/attack/multi_turn/test_pair.py b/tests/unit/executor/attack/multi_turn/test_pair.py index d9f998ebb1..51f5d1191e 100644 --- a/tests/unit/executor/attack/multi_turn/test_pair.py +++ b/tests/unit/executor/attack/multi_turn/test_pair.py @@ -41,7 +41,13 @@ def _make_mock_objective_target() -> PromptTarget: ) target.capabilities.supports_multi_turn = True target.capabilities.output_modalities = frozenset({frozenset(["text"])}) - target.configuration.includes.side_effect = lambda capability: capability == CapabilityName.MULTI_TURN + target.configuration.includes.side_effect = lambda capability: ( + capability + in { + CapabilityName.MULTI_TURN, + CapabilityName.RESPONSES, + } + ) target.configuration.capabilities.output_modalities = frozenset({frozenset(["text"])}) return cast("PromptTarget", target) diff --git a/tests/unit/executor/attack/multi_turn/test_supports_multi_turn_attacks.py b/tests/unit/executor/attack/multi_turn/test_supports_multi_turn_attacks.py index 447a2b05a3..6381c2eda9 100644 --- a/tests/unit/executor/attack/multi_turn/test_supports_multi_turn_attacks.py +++ b/tests/unit/executor/attack/multi_turn/test_supports_multi_turn_attacks.py @@ -17,7 +17,7 @@ ) from pyrit.memory import CentralMemory from pyrit.models import ConversationType, Message, MessagePiece, ScoringExpectation -from pyrit.prompt_target import PromptTarget, TargetCapabilities, TargetConfiguration +from pyrit.prompt_target import CapabilityName, PromptTarget, TargetCapabilities, TargetConfiguration class _SingleTurnPromptTarget(PromptTarget): @@ -52,7 +52,9 @@ def _make_strategy(*, supports_multi_turn: bool): target = MagicMock() target.capabilities.supports_multi_turn = supports_multi_turn - target.configuration.includes.return_value = supports_multi_turn + target.configuration.includes.side_effect = lambda *, capability: ( + capability is CapabilityName.RESPONSES or supports_multi_turn + ) target.get_identifier.return_value = {"__type__": "MockTarget", "__module__": "test", "id": "mock-id"} with patch.multiple( @@ -463,7 +465,9 @@ def _make_tap_node(self, *, supports_multi_turn: bool): target = MagicMock() target.capabilities.supports_multi_turn = supports_multi_turn - target.configuration.includes.return_value = supports_multi_turn + target.configuration.includes.side_effect = lambda *, capability: ( + capability is CapabilityName.RESPONSES or supports_multi_turn + ) target.configuration.capabilities.input_modalities = frozenset({frozenset({"text"})}) target.configuration.capabilities.output_modalities = frozenset({frozenset({"text"})}) target.get_identifier.return_value = {"__type__": "MockTarget", "__module__": "test", "id": "mock-id"} @@ -868,7 +872,9 @@ def _make_tap_node(self, *, supports_multi_turn: bool): target = MagicMock() target.capabilities.supports_multi_turn = supports_multi_turn - target.configuration.includes.return_value = supports_multi_turn + target.configuration.includes.side_effect = lambda *, capability: ( + capability is CapabilityName.RESPONSES or supports_multi_turn + ) target.configuration.capabilities.input_modalities = frozenset({frozenset({"text"})}) target.configuration.capabilities.output_modalities = frozenset({frozenset({"text"})}) target.get_identifier.return_value = {"__type__": "MockTarget", "__module__": "test", "id": "mock-id"} diff --git a/tests/unit/executor/attack/multi_turn/test_tree_of_attacks.py b/tests/unit/executor/attack/multi_turn/test_tree_of_attacks.py index b855c49926..eea801a33e 100644 --- a/tests/unit/executor/attack/multi_turn/test_tree_of_attacks.py +++ b/tests/unit/executor/attack/multi_turn/test_tree_of_attacks.py @@ -307,7 +307,7 @@ def _create_mock_target(supports_multi_turn: bool = True) -> PromptTarget: target.capabilities.supports_multi_turn = supports_multi_turn target.capabilities.output_modalities = frozenset({frozenset(["text"])}) target.configuration.includes.side_effect = lambda capability: ( - capability == CapabilityName.MULTI_TURN and supports_multi_turn + capability == CapabilityName.RESPONSES or (capability == CapabilityName.MULTI_TURN and supports_multi_turn) ) # Sensible defaults so the _ModalityFeedbackRouter sees a text-only target, # matching the historical behavior of these tests. diff --git a/tests/unit/executor/attack/single_turn/test_prompt_sending.py b/tests/unit/executor/attack/single_turn/test_prompt_sending.py index ac3c7cfa90..a4e2aa2e92 100644 --- a/tests/unit/executor/attack/single_turn/test_prompt_sending.py +++ b/tests/unit/executor/attack/single_turn/test_prompt_sending.py @@ -983,7 +983,10 @@ async def test_perform_attack_without_scorer_completes_after_first_response( # Verify that _evaluate_response_async was called even without objective scorer # This ensures auxiliary scores are still collected attack._evaluate_response_async.assert_called_once_with( - response=sample_response, objective=basic_context.objective, expectation=basic_context.expectation + response=sample_response, + objective=basic_context.objective, + expectation=basic_context.expectation, + side_effect_evidence_only=False, ) async def test_perform_attack_without_scorer_retries_on_filtered_response( diff --git a/tests/unit/executor/attack/test_write_only_objective_target.py b/tests/unit/executor/attack/test_write_only_objective_target.py new file mode 100644 index 0000000000..fccd6d93d0 --- /dev/null +++ b/tests/unit/executor/attack/test_write_only_objective_target.py @@ -0,0 +1,366 @@ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT license. + +""" +Regression tests for attacks against write-only objective targets. + +A write-only target (e.g., TextTarget) delivers the request without producing a response. Prompt sending +attacks run against it without scoring the request as response evidence, using real targets, scorers, and +memory; every other attack requires responses and rejects such a target at construction. +""" + +import base64 +import importlib +import inspect +import io +import json +import pkgutil +from collections.abc import Callable +from contextlib import AbstractContextManager +from datetime import UTC, datetime +from typing import Any +from unittest.mock import AsyncMock, patch + +import pytest +from unit.mocks import MockPromptTarget + +import pyrit.executor.attack +from pyrit.converter import Base64Converter +from pyrit.executor.attack import ( + AttackAdversarialConfig, + AttackConverterConfig, + AttackScoringConfig, + AttackStrategy, + ChunkedRequestAttack, + CrescendoAttack, + ManyShotJailbreakAttack, + MultiPromptSendingAttack, + PromptSendingAttack, + RedTeamingAttack, + SequentialAttack, + SkeletonKeyAttack, + TreeOfAttacksWithPruningAttack, +) +from pyrit.memory import SQLiteMemory +from pyrit.models import AttackOutcome, Message, MessagePiece, Score +from pyrit.prompt_normalizer import ConverterConfiguration +from pyrit.prompt_target import CapabilityName, PromptTarget, TargetCapabilities, TargetConfiguration, TextTarget +from pyrit.score import MessageScorer, RegexScorer + +_NO_RESPONSE_REASON = "Objective target returned no response to score" + + +class _EchoTarget(MockPromptTarget): + """Replies with the request text, so a scorer matching the request also matches the response.""" + + async def _send_prompt_to_target_async(self, *, normalized_conversation: list[Message]) -> list[Message]: + message = normalized_conversation[-1] + self.prompt_sent.append(message.get_value()) + return [ + MessagePiece( + role="assistant", + original_value=message.get_value(), + conversation_id=message.message_pieces[0].conversation_id, + ).to_message() + ] + + +class _JsonAdversarialChat(MockPromptTarget): + """Adversarial chat that always proposes the same next message in the adversarial_chat JSON shape.""" + + async def _send_prompt_to_target_async(self, *, normalized_conversation: list[Message]) -> list[Message]: + message = normalized_conversation[-1] + self.prompt_sent.append(message.get_value()) + payload = json.dumps( + {"next_message": "Hello from adversary", "rationale": "test", "last_response_summary": "test"} + ) + return [ + MessagePiece( + role="assistant", + original_value=payload, + conversation_id=message.message_pieces[0].conversation_id, + ).to_message() + ] + + +class _ScriptedTarget(MockPromptTarget): + """ + Returns each scripted reply in turn; ``None`` returns no response and an exception is raised. + + By default it declares no response support, so an unanswered send is a delivery, while a send + that does return a reply (like a storage receipt) is still processed as a response. + """ + + def __init__(self, *, replies: list[str | Exception | None], supports_responses: bool = False) -> None: + capabilities = MockPromptTarget._DEFAULT_CONFIGURATION.capabilities + super().__init__( + custom_configuration=TargetConfiguration( + capabilities=capabilities.model_copy(update={"supports_responses": supports_responses}) + ) + ) + self._replies = list(replies) + + async def _send_prompt_to_target_async(self, *, normalized_conversation: list[Message]) -> list[Message]: + message = normalized_conversation[-1] + self.prompt_sent.append(message.get_value()) + reply = self._replies.pop(0) + if isinstance(reply, Exception): + raise reply + if reply is None: + return [] + return [ + MessagePiece( + role="assistant", + original_value=reply, + conversation_id=message.message_pieces[0].conversation_id, + ).to_message() + ] + + +def _matching_scorer() -> RegexScorer: + # Matches the objective text, so scoring the sent request would report SUCCESS. + return RegexScorer(patterns={"objective": "Hello"}) + + +async def _all_scores_async(memory: SQLiteMemory) -> list[Score]: + # An unfiltered query returns nothing, so filter on a time that every stored score is after. + return list(await memory.get_scores_async(sent_after=datetime(2000, 1, 1, tzinfo=UTC), include_intermediate=True)) + + +def _no_message_scoring() -> AbstractContextManager[AsyncMock]: + # Every message-text scorer runs through this call, so it must never run for a delivered request. + return patch.object(MessageScorer, "score_response_async", new_callable=AsyncMock) + + +async def _assert_only_requests_persisted(*, memory: SQLiteMemory, conversation_id: str, expected_count: int) -> None: + pieces = await memory.get_message_pieces_async(conversation_id=conversation_id) + assert [piece.role for piece in pieces] == ["user"] * expected_count + assert await _all_scores_async(memory) == [] + + +@pytest.mark.usefixtures("patch_central_database") +class TestPromptSendingAttackWriteOnlyTarget: + async def test_write_only_target_is_undetermined_and_never_scored(self, sqlite_instance: SQLiteMemory) -> None: + text_stream = io.StringIO() + attack = PromptSendingAttack( + objective_target=TextTarget(text_stream=text_stream), + attack_scoring_config=AttackScoringConfig( + objective_scorer=_matching_scorer(), + auxiliary_scorers=[_matching_scorer()], + ), + max_attempts_on_failure=2, + ) + + with _no_message_scoring() as mock_score: + result = await attack.execute_async(objective="Hello QA") + + mock_score.assert_not_awaited() + assert result.outcome is AttackOutcome.UNDETERMINED + assert result.outcome_reason == _NO_RESPONSE_REASON + assert result.last_response is None + assert result.automated_score is None + assert result.executed_turns == 1 + # Delivered exactly once despite retries being available. + assert text_stream.getvalue().count("Hello QA") == 1 + await _assert_only_requests_persisted( + memory=sqlite_instance, conversation_id=result.conversation_id, expected_count=1 + ) + stored_results = await sqlite_instance.get_attack_results_async(conversation_id=result.conversation_id) + assert [stored.outcome for stored in stored_results] == [AttackOutcome.UNDETERMINED] + + async def test_assistant_role_request_to_write_only_target_is_not_a_response( + self, sqlite_instance: SQLiteMemory + ) -> None: + text_stream = io.StringIO() + attack = PromptSendingAttack( + objective_target=TextTarget(text_stream=text_stream), + attack_scoring_config=AttackScoringConfig(objective_scorer=_matching_scorer()), + ) + + with _no_message_scoring() as mock_score: + result = await attack.execute_async( + objective="Hello QA", + next_message=Message.from_prompt(prompt="Hello supplied request", role="assistant"), + ) + + mock_score.assert_not_awaited() + assert result.outcome is AttackOutcome.UNDETERMINED + assert result.outcome_reason == _NO_RESPONSE_REASON + assert result.last_response is None + assert result.automated_score is None + assert text_stream.getvalue() == "assistant: Hello supplied request\n" + assert await _all_scores_async(sqlite_instance) == [] + + async def test_write_only_target_without_scorer_has_no_last_response(self, sqlite_instance: SQLiteMemory) -> None: + attack = PromptSendingAttack(objective_target=TextTarget(text_stream=io.StringIO())) + + result = await attack.execute_async(objective="Hello QA") + + assert result.outcome is AttackOutcome.UNDETERMINED + assert result.outcome_reason == "No objective scorer configured" + assert result.last_response is None + assert result.automated_score is None + await _assert_only_requests_persisted( + memory=sqlite_instance, conversation_id=result.conversation_id, expected_count=1 + ) + + async def test_write_only_target_keeps_converted_request_export(self, sqlite_instance: SQLiteMemory) -> None: + text_stream = io.StringIO() + attack = PromptSendingAttack( + objective_target=TextTarget(text_stream=text_stream), + attack_converter_config=AttackConverterConfig( + request_converters=ConverterConfiguration.from_converters(converters=[Base64Converter()]) + ), + attack_scoring_config=AttackScoringConfig(objective_scorer=_matching_scorer()), + ) + + result = await attack.execute_async(objective="Hello QA") + + encoded = base64.b64encode(b"Hello QA").decode() + assert result.outcome is AttackOutcome.UNDETERMINED + assert text_stream.getvalue() == f"user: {encoded}\n" + pieces = await sqlite_instance.get_message_pieces_async(conversation_id=result.conversation_id) + assert [(piece.role, piece.original_value, piece.converted_value) for piece in pieces] == [ + ("user", "Hello QA", encoded) + ] + + async def test_missing_reply_from_responding_target_is_an_empty_response( + self, sqlite_instance: SQLiteMemory + ) -> None: + target = _ScriptedTarget(replies=[None, None, None], supports_responses=True) + attack = PromptSendingAttack( + objective_target=target, + attack_scoring_config=AttackScoringConfig(objective_scorer=_matching_scorer()), + max_attempts_on_failure=2, + ) + + result = await attack.execute_async(objective="Hello QA") + + # The target should have replied, so the missing reply is an empty error response and is resent. + assert len(target.prompt_sent) == 3 + assert result.outcome is AttackOutcome.UNDETERMINED + assert result.outcome_reason is not None + assert "Response had an error: empty" in result.outcome_reason + assert result.last_response is not None + assert (result.last_response.role, result.last_response.response_error) == ("assistant", "empty") + + async def test_responding_target_with_same_scorer_succeeds(self, sqlite_instance: SQLiteMemory) -> None: + attack = PromptSendingAttack( + objective_target=_EchoTarget(), + attack_scoring_config=AttackScoringConfig(objective_scorer=_matching_scorer()), + ) + + result = await attack.execute_async(objective="Hello QA") + + assert result.outcome is AttackOutcome.SUCCESS + assert result.last_response is not None + assert result.last_response.role == "assistant" + assert result.automated_score is not None + assert result.automated_score.get_value() is True + + async def test_delivery_receipt_from_write_only_target_is_not_scored(self, sqlite_instance: SQLiteMemory) -> None: + # Like AzureBlobStorageTarget, the target returns a receipt that matches the scorer but is not a reply. + target = _ScriptedTarget(replies=["Hello receipt"]) + attack = PromptSendingAttack( + objective_target=target, + attack_scoring_config=AttackScoringConfig(objective_scorer=_matching_scorer()), + max_attempts_on_failure=2, + ) + + with _no_message_scoring() as mock_score: + result = await attack.execute_async(objective="Hello QA") + + mock_score.assert_not_awaited() + assert result.outcome is AttackOutcome.UNDETERMINED + assert result.outcome_reason == _NO_RESPONSE_REASON + assert result.last_response is None + assert result.automated_score is None + assert target.prompt_sent == ["Hello QA"] + assert await _all_scores_async(sqlite_instance) == [] + + +def _text_target(text_stream: io.StringIO, **capabilities: bool) -> TextTarget: + # Declares the other capabilities an attack needs, so only the missing response support fails. + return TextTarget( + text_stream=text_stream, + custom_configuration=TargetConfiguration(capabilities=TargetCapabilities(**capabilities)), + ) + + +def _adversarial_config() -> AttackAdversarialConfig: + return AttackAdversarialConfig(target=_JsonAdversarialChat()) + + +_MULTI_TURN = {"supports_multi_turn": True} +_CHAT_HISTORY = {"supports_multi_turn": True, "supports_editable_history": True} + + +@pytest.mark.usefixtures("patch_central_database") +@pytest.mark.parametrize( + ("build", "capabilities"), + [ + pytest.param( + lambda target: RedTeamingAttack(objective_target=target, attack_adversarial_config=_adversarial_config()), + {}, + id="red-teaming", + ), + pytest.param( + lambda target: TreeOfAttacksWithPruningAttack( + objective_target=target, attack_adversarial_config=_adversarial_config() + ), + {}, + id="tree-of-attacks", + ), + pytest.param( + lambda target: CrescendoAttack(objective_target=target, attack_adversarial_config=_adversarial_config()), + _CHAT_HISTORY, + id="crescendo", + ), + pytest.param(lambda target: MultiPromptSendingAttack(objective_target=target), _MULTI_TURN, id="multi-prompt"), + pytest.param( + lambda target: ChunkedRequestAttack(objective_target=target, chunk_size=10, total_length=30), + _MULTI_TURN, + id="chunked-request", + ), + ], +) +def test_attack_that_needs_responses_rejects_write_only_target_at_construction( + build: Callable[[PromptTarget], AttackStrategy[Any, Any]], capabilities: dict[str, bool] +) -> None: + text_stream = io.StringIO() + + with pytest.raises(ValueError, match="supports_responses") as exc_info: + build(_text_target(text_stream, **capabilities)) + + assert "1 required capability" in str(exc_info.value) + assert text_stream.getvalue() == "" + + +# Attacks that support targets that never reply. Every other attack must require responses. +_WRITE_ONLY_CAPABLE_ATTACKS = {PromptSendingAttack, ManyShotJailbreakAttack, SkeletonKeyAttack, SequentialAttack} + + +def _concrete_attack_classes() -> list[type[AttackStrategy[Any, Any]]]: + for module in pkgutil.walk_packages(pyrit.executor.attack.__path__, "pyrit.executor.attack."): + importlib.import_module(module.name) + pending: list[type[AttackStrategy[Any, Any]]] = [AttackStrategy] + found: set[type[AttackStrategy[Any, Any]]] = set() + while pending: + for subclass in pending.pop().__subclasses__(): + pending.append(subclass) + if subclass.__module__.startswith("pyrit.") and not inspect.isabstract(subclass): + found.add(subclass) + return sorted(found, key=lambda attack_class: attack_class.__qualname__) + + +def test_attack_discovery_finds_known_attacks() -> None: + assert {RedTeamingAttack, TreeOfAttacksWithPruningAttack, *_WRITE_ONLY_CAPABLE_ATTACKS} <= set( + _concrete_attack_classes() + ) + + +@pytest.mark.parametrize("attack_class", _concrete_attack_classes(), ids=lambda attack_class: attack_class.__name__) +def test_only_prompt_sending_attacks_accept_write_only_targets(attack_class: type[AttackStrategy[Any, Any]]) -> None: + requires_responses = CapabilityName.RESPONSES in attack_class.TARGET_REQUIREMENTS.native_required + + assert requires_responses is (attack_class not in _WRITE_ONLY_CAPABLE_ATTACKS) diff --git a/tests/unit/prompt_normalizer/test_prompt_normalizer.py b/tests/unit/prompt_normalizer/test_prompt_normalizer.py index 4390f8b3da..ac378ff836 100644 --- a/tests/unit/prompt_normalizer/test_prompt_normalizer.py +++ b/tests/unit/prompt_normalizer/test_prompt_normalizer.py @@ -729,6 +729,59 @@ async def test_send_prompt_async_none_in_list_response_returns_empty(mock_memory assert response.message_pieces[0].original_value == "" +def _write_only_mock_target(*, return_value: object) -> MagicMock: + prompt_target = MagicMock() + prompt_target.configuration = TargetConfiguration(capabilities=TargetCapabilities(supports_responses=False)) + prompt_target.send_prompt_async = AsyncMock(return_value=return_value) + prompt_target.get_identifier.return_value = get_mock_target_identifier("MockTarget") + return prompt_target + + +@pytest.mark.parametrize("target_return", [[], None], ids=["empty-list", "none"]) +@pytest.mark.parametrize("role", ["user", "assistant", "system"]) +async def test_send_prompt_async_write_only_target_returns_request(mock_memory_instance, role, target_return): + prompt_target = _write_only_mock_target(return_value=target_return) + message = Message.from_prompt(prompt="write-only request", role=role) + + response = await PromptNormalizer().send_prompt_async(message=message, target=prompt_target) + + assert response.api_role == role + assert response.get_value() == "write-only request" + # Only the request is persisted; no response is fabricated for the write-only target. + assert mock_memory_instance.add_message_to_memory_async.call_count == 1 + persisted = mock_memory_instance.add_message_to_memory_async.call_args.kwargs["request"] + assert [piece.id for piece in persisted.message_pieces] == [piece.id for piece in response.message_pieces] + + +async def test_send_prompt_async_empty_list_from_responding_target_is_empty_response(mock_memory_instance): + prompt_target = MagicMock() + prompt_target.configuration = TargetConfiguration(capabilities=TargetCapabilities()) + prompt_target.send_prompt_async = AsyncMock(return_value=[]) + prompt_target.get_identifier.return_value = get_mock_target_identifier("MockTarget") + + response = await PromptNormalizer().send_prompt_async( + message=Message.from_prompt(prompt="request", role="user"), target=prompt_target + ) + + # The target should have replied, so the missing reply is an empty response, not a delivery. + assert response.api_role == "assistant" + assert response.get_piece().response_error == "empty" + persisted = [call.kwargs["request"] for call in mock_memory_instance.add_message_to_memory_async.call_args_list] + assert [message.api_role for message in persisted] == ["user", "assistant"] + + +async def test_send_prompt_async_receipt_from_write_only_target_is_returned(mock_memory_instance): + receipt = Message.from_prompt(prompt="https://storage.example/receipt", role="assistant") + prompt_target = _write_only_mock_target(return_value=[receipt]) + + response = await PromptNormalizer().send_prompt_async( + message=Message.from_prompt(prompt="request", role="user"), target=prompt_target + ) + + # What the target returns is kept; callers ask the target whether it is a reply. + assert response.get_value() == "https://storage.example/receipt" + + async def test_build_message(mock_memory_instance, seed_group): # This test is obsolete since _build_message was removed and message preparation # is now done inline in send_prompt_async. The functionality is tested by diff --git a/tests/unit/prompt_target/target/test_prompt_target_azure_blob_storage.py b/tests/unit/prompt_target/target/test_prompt_target_azure_blob_storage.py index 8ca8e98889..0d89813ad4 100644 --- a/tests/unit/prompt_target/target/test_prompt_target_azure_blob_storage.py +++ b/tests/unit/prompt_target/target/test_prompt_target_azure_blob_storage.py @@ -35,6 +35,11 @@ def test_initialization_with_required_parameters(azure_blob_storage_target: Azur assert azure_blob_storage_target._sas_token == "valid_sas_token" +def test_declares_no_response_support(azure_blob_storage_target: AzureBlobStorageTarget): + # The returned blob URL is a delivery receipt, not a reply. + assert not azure_blob_storage_target.capabilities.supports_responses + + def test_supported_auth_modes_includes_identity(): """Blob advertises identity-based auth (DefaultAzureCredential) alongside api_key.""" assert AzureBlobStorageTarget.supported_auth_modes == ("api_key", "identity") diff --git a/tests/unit/prompt_target/target/test_target_capabilities.py b/tests/unit/prompt_target/target/test_target_capabilities.py index 40c0ad3708..62297c8596 100644 --- a/tests/unit/prompt_target/target/test_target_capabilities.py +++ b/tests/unit/prompt_target/target/test_target_capabilities.py @@ -249,6 +249,9 @@ def test_default_capabilities_are_text_only(self): assert caps.input_modalities == frozenset({frozenset(["text"])}) assert caps.output_modalities == frozenset({frozenset(["text"])}) + def test_default_capabilities_support_responses(self): + assert TargetCapabilities().includes(capability=CapabilityName.RESPONSES) + @patch.dict("os.environ", _CLEAN_UNDERLYING_MODEL_ENV) def test_openai_chat_target_modalities(self): from pyrit.prompt_target import OpenAIChatTarget diff --git a/tests/unit/prompt_target/test_text_target.py b/tests/unit/prompt_target/test_text_target.py index 03c1b41714..14a0b8cb32 100644 --- a/tests/unit/prompt_target/test_text_target.py +++ b/tests/unit/prompt_target/test_text_target.py @@ -9,8 +9,9 @@ import pytest from unit.mocks import get_sample_conversations -from pyrit.models import Message, MessagePiece, flatten_to_message_pieces -from pyrit.prompt_target import TextTarget +from pyrit.models import CapabilityName, Message, MessagePiece, flatten_to_message_pieces +from pyrit.prompt_normalizer import PromptNormalizer +from pyrit.prompt_target import TargetCapabilities, TargetConfiguration, TextTarget @pytest.fixture @@ -34,6 +35,51 @@ def test_init_with_custom_stream(): assert target._text_stream is stream +@pytest.mark.usefixtures("patch_central_database") +def test_declares_no_response_support(): + target = TextTarget(text_stream=io.StringIO()) + + assert not target.configuration.includes(capability=CapabilityName.RESPONSES) + + +@pytest.mark.usefixtures("patch_central_database") +def test_custom_configuration_cannot_declare_response_support(): + # A custom configuration that only sets multi-turn leaves supports_responses at its default of True. + target = TextTarget( + text_stream=io.StringIO(), + custom_configuration=TargetConfiguration(capabilities=TargetCapabilities(supports_multi_turn=True)), + ) + + assert target.capabilities.supports_multi_turn + assert not target.capabilities.supports_responses + + +@pytest.mark.usefixtures("patch_central_database") +def test_apply_capabilities_cannot_declare_response_support(): + target = TextTarget(text_stream=io.StringIO()) + + target.apply_capabilities(capabilities=TargetCapabilities(supports_multi_turn=True, supports_responses=True)) + + assert target.capabilities.supports_multi_turn + assert not target.capabilities.supports_responses + + +@pytest.mark.usefixtures("patch_central_database") +async def test_saved_capabilities_scope_cannot_declare_response_support(): + target = TextTarget(text_stream=io.StringIO()) + + # A capability snapshot saved before supports_responses existed loads with its default of True. + with target.capabilities_scope(TargetCapabilities()): + assert not target.capabilities.supports_responses + response = await PromptNormalizer().send_prompt_async( + message=Message.from_prompt(prompt="hello", role="user"), target=target + ) + + # The normalizer hands back the request instead of fabricating an empty error response. + assert response.api_role == "user" + assert response.get_value() == "hello" + + @pytest.mark.usefixtures("patch_central_database") async def test_send_prompt_async_writes_to_stream(sample_entries: MutableSequence[MessagePiece]): output_stream = io.StringIO() diff --git a/tests/unit/score/test_file_write_scorer.py b/tests/unit/score/test_file_write_scorer.py index 2276173ef0..e62f7b54b1 100644 --- a/tests/unit/score/test_file_write_scorer.py +++ b/tests/unit/score/test_file_write_scorer.py @@ -13,6 +13,7 @@ import httpx import pytest +from unit.mocks import MockPromptTarget from pyrit.executor.attack import AttackScoringConfig, PromptSendingAttack from pyrit.models import ( @@ -39,10 +40,12 @@ ToolCallRequirement, ToolsCalled, ) +from pyrit.prompt_target import TargetConfiguration from pyrit.score import ( FileWriteScorer, LocalFileSurfaceSource, NonReplayableObservationError, + RegexScorer, TrueFalseCompositeScorer, TrueFalseFallbackScorer, TrueFalseInverterScorer, @@ -55,7 +58,7 @@ from pathlib import Path from pyrit.memory import SQLiteMemory - from pyrit.models import TextMatcher + from pyrit.models import Message, TextMatcher from pyrit.prompt_target import HTTPTarget pytestmark = pytest.mark.usefixtures("patch_central_database") @@ -445,6 +448,72 @@ async def test_attack_scores_file_write_async( assert observation.scorable == SurfaceScorable(uri="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/data/out.txt") +class _WriteOnlyAgentTarget(MockPromptTarget): + """An agent stand-in that writes the prompt it receives to /data/out.txt and returns no response.""" + + _DEFAULT_CONFIGURATION = TargetConfiguration( + capabilities=MockPromptTarget._DEFAULT_CONFIGURATION.capabilities.model_copy( + update={"supports_responses": False} + ) + ) + + def __init__(self, *, root: Path, write: bool) -> None: + super().__init__() + self._root = root + self._write = write + + async def _send_prompt_to_target_async(self, *, normalized_conversation: list[Message]) -> list[Message]: + if self._write: + _write(root=self._root, data=normalized_conversation[-1].get_value()) + return [] + + +@pytest.mark.parametrize("require_content_change", [False, True]) +@pytest.mark.parametrize(("write", "outcome"), [(True, AttackOutcome.SUCCESS), (False, AttackOutcome.FAILURE)]) +async def test_attack_scores_file_write_of_write_only_target_async( + *, + sqlite_instance: SQLiteMemory, + tmp_path: Path, + write: bool, + outcome: AttackOutcome, + require_content_change: bool, +) -> None: + attack = PromptSendingAttack( + objective_target=_WriteOnlyAgentTarget(root=tmp_path, write=write), + attack_scoring_config=AttackScoringConfig( + objective_scorer=FileWriteScorer(source=LocalFileSurfaceSource(root=tmp_path)), + # Matches the request text, so it must not judge the delivered request. + auxiliary_scorers=[RegexScorer(patterns={"objective": "exfiltrated"})], + ), + max_attempts_on_failure=0, + ) + expectation = _expectation(matcher=Contains(value="exfiltrated"), require_content_change=require_content_change) + + result = await attack.execute_async(objective="exfiltrated", expectation=expectation) + + assert result.outcome is outcome + assert result.last_response is None + score = result.automated_score + assert score is not None + (request,) = await sqlite_instance.get_message_pieces_async(conversation_id=result.conversation_id) + assert request.role == "user" + assert score.scorable == MessageScorable(message_piece_ids=(request.id,)) + observation = (await sqlite_instance.get_observations_async(observation_ids=score.observation_ids))[0] + assert observation.scorable == SurfaceScorable(uri="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/data/out.txt") + stored = await sqlite_instance.get_scores_async( + sent_after=datetime(2000, 1, 1, tzinfo=UTC), include_intermediate=True + ) + assert [stored_score.scorer_class_identifier.class_name for stored_score in stored] == ["FileWriteScorer"] + assert [ + stored_score.id for stored_score in await sqlite_instance.get_prompt_scores_async(prompt_ids=[request.id]) + ] == [score.id] + (stored_result,) = await sqlite_instance.get_attack_results_async(attack_result_ids=[result.attack_result_id]) + assert stored_result.outcome is outcome + assert stored_result.last_response is None + assert stored_result.automated_score is not None + assert stored_result.automated_score.id == score.id + + # --- observation lifecycle ------------------------------------------------------------------ diff --git a/tests/unit/score/test_message_trace_scoring.py b/tests/unit/score/test_message_trace_scoring.py index f817aa8641..fdc8cf6aab 100644 --- a/tests/unit/score/test_message_trace_scoring.py +++ b/tests/unit/score/test_message_trace_scoring.py @@ -5,6 +5,7 @@ from collections.abc import Iterator from contextlib import nullcontext from datetime import UTC, datetime +from pathlib import Path from unittest.mock import AsyncMock, patch import httpx @@ -25,11 +26,14 @@ Acquisition, AttackOutcome, ChatMessageRole, + Contains, + ContentWritten, Message, MessagePiece, MessageScorable, RequestTraceContext, ScoringExpectation, + SurfaceScorable, ToolCallRequirement, ToolsCalled, TraceScorable, @@ -38,8 +42,10 @@ from pyrit.prompt_normalizer import PromptNormalizer from pyrit.prompt_target import HTTPTarget, TargetCapabilities, TargetConfiguration, TargetTraceConfig from pyrit.score import ( + FileWriteScorer, InMemoryTraceClient, InMemoryTraceExporter, + LocalFileSurfaceSource, OtelToolCallScorer, OtelTraceSource, SubStringScorer, @@ -143,6 +149,87 @@ async def test_attack_scores_tool_evidence_and_replays_async( assert replay.get_value() == score.get_value() +class _WriteOnlyTracedAgent(HTTPTarget): + """A traced agent that acts on the request and returns no response, like a write-only target.""" + + async def _send_prompt_to_target_async(self, *, normalized_conversation: list[Message]) -> list[Message]: + await super()._send_prompt_to_target_async(normalized_conversation=normalized_conversation) + return [] + + +@pytest.mark.parametrize( + ("acts", "outcome"), + [(True, AttackOutcome.SUCCESS), (False, AttackOutcome.FAILURE)], +) +async def test_composite_of_file_and_trace_scorers_judges_write_only_target_async( + sqlite_instance: SQLiteMemory, + capture: tuple[InMemoryTraceClient, TracerProvider], + tmp_path: Path, + acts: bool, + outcome: AttackOutcome, +) -> None: + client, provider = capture + tracer = provider.get_tracer("test-agent") + + def respond(request: httpx.Request) -> httpx.Response: + context = TraceContextTextMapPropagator().extract(dict(request.headers)) + with tracer.start_as_current_span("agent", context=context) as root: + if acts: + with tracer.start_as_current_span( + "lookup", attributes={"gen_ai.operation.name": "execute_tool", "gen_ai.tool.name": "lookup"} + ): + path = tmp_path / "data" / "out.txt" + path.parent.mkdir(parents=True, exist_ok=True) + path.write_text("exfiltrated") + client.mark_complete(trace_ids=(f"{root.get_span_context().trace_id:032x}",)) + return httpx.Response(200, text="ignored") + + target = _WriteOnlyTracedAgent( + http_request="POST / HTTP/1.1\nHost: agent.test\n\n{PROMPT}", + transport=httpx.MockTransport(respond), + trace_config=TargetTraceConfig(enabled=True), + custom_configuration=TargetConfiguration(capabilities=TargetCapabilities(supports_responses=False)), + ) + # Neither leaf reads the request text, but together they accept only a MessageScorable. + objective_scorer = TrueFalseCompositeScorer( + scorers=[ + FileWriteScorer(source=LocalFileSurfaceSource(root=tmp_path)), + OtelToolCallScorer(source=OtelTraceSource(trace_client=client)), + ], + aggregator=TrueFalseScoreAggregator.AND, + ) + scoring_config = AttackScoringConfig(objective_scorer=objective_scorer) + expectation = ScoringExpectation( + conditions=( + ContentWritten(uri="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/data/out.txt", matcher=Contains(value="exfiltrated")), + ToolsCalled(tools=(ToolCallRequirement(name="lookup"),)), + ) + ) + + result = await PromptSendingAttack( + objective_target=target, attack_scoring_config=scoring_config, max_attempts_on_failure=0 + ).execute_async(objective="exfiltrated", expectation=expectation) + + assert result.outcome is outcome + assert result.last_response is None + score = result.automated_score + assert score is not None + (request,) = await sqlite_instance.get_message_pieces_async(conversation_id=result.conversation_id) + assert request.role == "user" + # Scores attach to a piece's original prompt, so the stored request finds its score. + assert score.scorable == MessageScorable(message_piece_ids=(request.original_prompt_id,)) + assert [stored.id for stored in await sqlite_instance.get_prompt_scores_async(prompt_ids=[request.id])] == [ + score.id + ] + observations = await sqlite_instance.get_observations_async(observation_ids=score.observation_ids) + assert {type(observation.scorable) for observation in observations} == {SurfaceScorable, TraceScorable} + (stored,) = await sqlite_instance.get_attack_results_async(attack_result_ids=[result.attack_result_id]) + assert stored.outcome is outcome + assert stored.last_response is None + assert stored.automated_score is not None + assert stored.automated_score.id == score.id + + @pytest.mark.parametrize("role", ["user", "tool", "assistant", "developer"]) async def test_multiturn_attack_combines_only_its_requests_async( capture: tuple[InMemoryTraceClient, TracerProvider], diff --git a/tests/unit/score/test_scorer_condition_contracts.py b/tests/unit/score/test_scorer_condition_contracts.py index d68c431d61..b6dedc2247 100644 --- a/tests/unit/score/test_scorer_condition_contracts.py +++ b/tests/unit/score/test_scorer_condition_contracts.py @@ -30,15 +30,20 @@ ) from pyrit.score import ( DecisionScorer, + FileWriteScorer, LegacyScorerHookError, MessageTrueFalseScorer, ObservationSource, + OtelToolCallScorer, ProgramExecutionScorer, Scorer, ScorerPromptValidator, SelfAskGeneralFloatScaleScorer, SelfAskScaleScorer, SubStringScorer, + TrueFalseCompositeScorer, + TrueFalseInverterScorer, + TrueFalseScoreAggregator, TrueFalseScorer, ) from pyrit.score.observation import execution @@ -217,6 +222,24 @@ def test_program_scorer_declares_code_and_execution_evidence(self) -> None: ) assert scorer.get_condition_types() == frozenset({ProgramBehaves}) + def test_judges_side_effects_requires_every_leaf_to_read_side_effects(self) -> None: + file_scorer = FileWriteScorer(source=MagicMock(spec=ObservationSource)) + trace_scorer = OtelToolCallScorer(source=MagicMock(spec=ObservationSource)) + text_scorer = SubStringScorer(substring="x") + side_effects = TrueFalseCompositeScorer( + scorers=[file_scorer, TrueFalseInverterScorer(scorer=trace_scorer)], + aggregator=TrueFalseScoreAggregator.AND, + ) + mixed = TrueFalseCompositeScorer(scorers=[file_scorer, text_scorer], aggregator=TrueFalseScoreAggregator.AND) + + # Leaves reading different side effects share only MessageScorable, yet still qualify. + assert side_effects.get_supported_scorable_types() == frozenset({MessageScorable}) + assert file_scorer.judges_side_effects() + assert trace_scorer.judges_side_effects() + assert side_effects.judges_side_effects() + assert not text_scorer.judges_side_effects() + assert not mixed.judges_side_effects() + class TestNoAmbientExpectation: def test_ambient_expectation_context_is_removed(self) -> None: