From 3df5e0441adc617d030f63bf363c511967290335 Mon Sep 17 00:00:00 2001 From: Richard Lundeen Date: Fri, 20 Nov 2026 21:30:53 -0800 Subject: [PATCH 1/2] FIX: Rebuild decision and Prompt Shield targets for capability detection LiteLLMDecisionTarget and PromptShieldTarget now supply reconstruction parameters, reusing the source's resolved key or token provider, with connection settings copy-locked. Discovery sends a target-provided probe text so the decision target's control request is a valid decision request, and the decision target no longer runs chat probes. Detection rejects targets that can't be rebuilt with a clear message before probing. Co-Authored-By: Claude Opus 5.5 --- pyrit/backend/services/target_service.py | 7 ++ .../common/discover_target_capabilities.py | 23 +++++- pyrit/prompt_target/common/prompt_target.py | 7 +- .../prompt_target/litellm_decision_target.py | 34 ++++++++- pyrit/prompt_target/openai/openai_target.py | 10 --- pyrit/prompt_target/prompt_shield_target.py | 19 +++++ tests/unit/backend/test_target_detection.py | 74 ++++++++++++++++++- .../target/test_litellm_decision_target.py | 30 ++++++++ .../target/test_prompt_shield_target.py | 39 ++++++++++ 9 files changed, 224 insertions(+), 19 deletions(-) diff --git a/pyrit/backend/services/target_service.py b/pyrit/backend/services/target_service.py index 2d53e879c2..7016b36af4 100644 --- a/pyrit/backend/services/target_service.py +++ b/pyrit/backend/services/target_service.py @@ -82,6 +82,7 @@ RegistryNameTakenError, registry_entry_origin, ) +from pyrit.registry.registry import Reconstructable logger = logging.getLogger(__name__) @@ -163,6 +164,12 @@ async def detect_capabilities_async(self, *, target_registry_name: str, expected if getattr(target, "inner_targets", None) and not isinstance(target, RoundRobinTarget): raise ValueError("Capability detection is not supported for this composite target type.") sources = target.inner_targets if isinstance(target, RoundRobinTarget) else [target] + # Detection probes a private copy, so a target that can't be rebuilt can't be checked. + for source in sources: + if not isinstance(source, Reconstructable): + raise ValueError( + f"Capability detection is not supported for {type(source).__name__} because it can't be rebuilt." + ) snapshots = [(source, source.configuration) for source in [target, *sources]] source_ids = {id(source) for source, _ in snapshots} if target_registry_name in self._detecting or source_ids & self._detecting_sources: diff --git a/pyrit/prompt_target/common/discover_target_capabilities.py b/pyrit/prompt_target/common/discover_target_capabilities.py index 491543c063..e7e227290a 100644 --- a/pyrit/prompt_target/common/discover_target_capabilities.py +++ b/pyrit/prompt_target/common/discover_target_capabilities.py @@ -682,10 +682,13 @@ def _supports_chat_probes(target: PromptTarget) -> bool: bool: Whether chat features can be sent by this adapter. """ from pyrit.prompt_target.litellm_chat_target import LiteLLMChatTarget + from pyrit.prompt_target.litellm_decision_target import LiteLLMDecisionTarget from pyrit.prompt_target.openai.openai_chat_target import OpenAIChatTarget from pyrit.prompt_target.openai.openai_response_target import OpenAIResponseTarget - return isinstance(target, (OpenAIChatTarget, OpenAIResponseTarget, LiteLLMChatTarget)) + return isinstance(target, (OpenAIChatTarget, OpenAIResponseTarget, LiteLLMChatTarget)) and not isinstance( + target, LiteLLMDecisionTarget + ) async def _discover_capability_flags_async( @@ -849,7 +852,12 @@ async def _discover_input_modalities_async( queried.add(combination) continue try: - message = await asyncio.to_thread(_create_test_message, modalities=combination, test_assets=assets) + message = await asyncio.to_thread( + _create_test_message, + modalities=combination, + test_assets=assets, + text=target.capability_probe_text, + ) except FileNotFoundError as exc: # Skip combinations we cannot construct a valid probe payload for. logger.info("Skipping modality %s: %s", combination, exc) @@ -897,7 +905,12 @@ async def _check_control_request_async( with _permissive_configuration(target=target): for combination in combinations: try: - message = await asyncio.to_thread(_create_test_message, modalities=combination, test_assets=assets) + message = await asyncio.to_thread( + _create_test_message, + modalities=combination, + test_assets=assets, + text=target.capability_probe_text, + ) except (FileNotFoundError, ValueError) as exc: logger.info("Cannot prepare control input %s: %s", sorted(combination), exc) continue @@ -1077,6 +1090,7 @@ def _create_test_message( *, modalities: frozenset[PromptDataType], test_assets: dict[PromptDataType, str], + text: str = "test", ) -> Message: """ Build a minimal ``Message`` that exercises ``modalities``. @@ -1085,6 +1099,7 @@ def _create_test_message( modalities (frozenset[PromptDataType]): The modalities to include. test_assets (dict[PromptDataType, str]): Mapping from non-text modality to a file path used for the probe. + text (str): The text piece's value. Defaults to ``"test"``. Returns: Message: A message containing one piece per modality. @@ -1101,7 +1116,7 @@ def _create_test_message( pieces.append( MessagePiece( role="user", - original_value="test", + original_value=text, original_value_data_type="text", conversation_id=conversation_id, prompt_metadata=_probe_metadata(), diff --git a/pyrit/prompt_target/common/prompt_target.py b/pyrit/prompt_target/common/prompt_target.py index 14b38a75d7..e0e97ae8df 100644 --- a/pyrit/prompt_target/common/prompt_target.py +++ b/pyrit/prompt_target/common/prompt_target.py @@ -196,6 +196,10 @@ class PromptTarget(Identifiable): # with the endpoint it was configured for. COPY_LOCKED_PARAMETER_NAMES: ClassVar[frozenset[str]] = frozenset() + # Text capability discovery sends to check a text input. A target that accepts only structured text + # overrides it with a valid request. + capability_probe_text: ClassVar[str] = "test" + def __init_subclass__(cls, **kwargs: object) -> None: """ Validate that subclasses follow the keyword-only ``__init__`` contract. @@ -679,7 +683,7 @@ def _reset_credential_status(self) -> None: def attach_reconstruction_source(self, source: object) -> None: """ - Report credential rejections into the target this copy was built from. + Share request pacing and credential status, not clients or behavioral configuration. Args: source (object): The registered target this copy was built from. @@ -687,6 +691,7 @@ def attach_reconstruction_source(self, source: object) -> None: if isinstance(source, PromptTarget): self._credential_status_source = source._credential_status_owner() self._credential_generation = source._credential_generation + self._rate_limit_source = getattr(source, "_rate_limit_source", source) def _validate_request(self, *, normalized_conversation: list[Message]) -> None: """ diff --git a/pyrit/prompt_target/litellm_decision_target.py b/pyrit/prompt_target/litellm_decision_target.py index 3f3d926cc7..4525ebb6d1 100644 --- a/pyrit/prompt_target/litellm_decision_target.py +++ b/pyrit/prompt_target/litellm_decision_target.py @@ -4,7 +4,7 @@ import json import math from collections.abc import Awaitable, Callable -from typing import TYPE_CHECKING, Any, TypedDict, cast +from typing import TYPE_CHECKING, Any, ClassVar, TypedDict, cast from pyrit.exceptions import pyrit_target_retry from pyrit.models import ( @@ -44,6 +44,21 @@ class LiteLLMDecisionTarget(LiteLLMChatTarget): _SUPPORTS_TOOL_CALL_HISTORY = False _DEFAULT_CONFIGURATION = TargetConfiguration(capabilities=TargetCapabilities()) + # The model name's provider prefix chooses where LiteLLM sends the key when no endpoint is set. + COPY_LOCKED_PARAMETER_NAMES: ClassVar[frozenset[str]] = frozenset({"model_name", "endpoint", "api_key", "headers"}) + capability_probe_text: ClassVar[str] = json.dumps( + { + "state": "test", + "questions": { + "probe": { + "type": "noul", + "instructions": "Is the state the word test?", + "criteria": {"true": "It is.", "false": "It is not."}, + } + }, + } + ) + def __init__( self, *, @@ -93,6 +108,23 @@ def _build_identifier(self) -> ComponentIdentifier: """ return self._create_identifier(params={"endpoint": self._endpoint, "headers": self._identifier_headers()}) + def get_reconstruction_parameters(self) -> dict[str, object]: + """ + Return server-only inputs, including the resolved key or token provider. + + Returns: + dict[str, object]: Constructor inputs that rebuild this target. + """ + return { + "model_name": self._model_name, + "endpoint": self._endpoint, + "api_key": self._api_key, + "headers": self._headers, + "max_requests_per_minute": self._max_requests_per_minute, + "custom_configuration": self.configuration, + "trace_config": self._trace_config, + } + @pyrit_target_retry @limit_requests_per_minute async def _send_prompt_to_target_async(self, *, normalized_conversation: list[Message]) -> list[Message]: diff --git a/pyrit/prompt_target/openai/openai_target.py b/pyrit/prompt_target/openai/openai_target.py index 9e6d58b62e..e0c5ea3bab 100644 --- a/pyrit/prompt_target/openai/openai_target.py +++ b/pyrit/prompt_target/openai/openai_target.py @@ -504,16 +504,6 @@ async def cleanup_target_async(self) -> None: if self._async_client is not None: await self._async_client.close() - def attach_reconstruction_source(self, source: object) -> None: - """ - Share request pacing and credential status, not clients or behavioral configuration. - - Args: - source (object): The registered target this copy was built from. - """ - super().attach_reconstruction_source(source) - self._rate_limit_source = getattr(source, "_rate_limit_source", source) - @property def supports_credential_updates(self) -> bool: """Whether this target can replace its API key or request headers in place; not with its own HTTP client.""" diff --git a/pyrit/prompt_target/prompt_shield_target.py b/pyrit/prompt_target/prompt_shield_target.py index 0c9cf411c3..a89a55f593 100644 --- a/pyrit/prompt_target/prompt_shield_target.py +++ b/pyrit/prompt_target/prompt_shield_target.py @@ -70,6 +70,7 @@ class PromptShieldTarget(PromptTarget): server_fallback_parameters: ClassVar[Mapping[str, str | None]] = MappingProxyType({"api_key": None}) destination_parameters: ClassVar[Mapping[str, bool]] = MappingProxyType({"endpoint": True}) environment_backed_parameters: ClassVar[frozenset[str]] = frozenset({"endpoint"}) + COPY_LOCKED_PARAMETER_NAMES: ClassVar[frozenset[str]] = frozenset({"endpoint", "api_key", "auth_mode"}) _endpoint: str _api_key: str | Callable[[], str] | None @@ -198,6 +199,24 @@ def get_auth_mode_parameters(cls, *, auth_mode: AuthMode) -> dict[str, object]: """ return {"auth_mode": auth_mode} + def get_reconstruction_parameters(self) -> dict[str, object]: + """ + Return server-only inputs, including the resolved key or token provider. + + Returns: + dict[str, object]: Constructor inputs that rebuild this target. + """ + return { + "endpoint": self._endpoint, + # Reuse the resolved key or token provider, not the original credential-selection mode. + "api_key": self._api_key, + "auth_mode": "api_key", + "api_version": self._api_version, + "field": self._force_entry_field, + "max_requests_per_minute": self._max_requests_per_minute, + "custom_configuration": self.configuration, + } + def _build_identifier(self) -> ComponentIdentifier: """ Build the identifier with Prompt Shield-specific parameters. diff --git a/tests/unit/backend/test_target_detection.py b/tests/unit/backend/test_target_detection.py index 395c1b7407..0cd6308e96 100644 --- a/tests/unit/backend/test_target_detection.py +++ b/tests/unit/backend/test_target_detection.py @@ -12,7 +12,7 @@ from pathlib import Path from types import SimpleNamespace from typing import Any -from unittest.mock import AsyncMock, patch +from unittest.mock import AsyncMock, MagicMock, patch import pytest from fastapi import FastAPI @@ -45,7 +45,14 @@ ) from pyrit.models.catalog import RegistryEntryOrigin from pyrit.models.component_spec import SourceInstanceSpec, TargetBinding -from pyrit.prompt_target import OpenAIChatTarget, OpenAITTSTarget, RoundRobinTarget, TargetConfiguration +from pyrit.prompt_target import ( + LiteLLMDecisionTarget, + OpenAIChatTarget, + OpenAITTSTarget, + PromptShieldTarget, + RoundRobinTarget, + TargetConfiguration, +) from pyrit.prompt_target.common.discover_target_capabilities import DEFAULT_TEST_ASSETS, CapabilityDiscoveryError from pyrit.registry import TargetRegistry from pyrit.registry.instance_registry import SAVED_ENTRY_METADATA_KEY @@ -464,6 +471,67 @@ async def discover_async(*, target: OpenAIChatTarget, **kwargs: object) -> Targe await target.cleanup_target_async() +async def test_detection_rebuilds_decision_target_and_sends_a_valid_control_request_async( + detection_service: tuple[TargetService, _DetectableTarget], +) -> None: + litellm = pytest.importorskip("litellm") + from litellm.types.decisions import DecisionsResponse + + service, _ = detection_service + source = LiteLLMDecisionTarget(model_name="openrouter/decision", endpoint="https://example.test", api_key="key") + service._registry.instances.register(source, name="microsoft_decision") + original = source.capabilities + sdk = MagicMock(spec=litellm) + sdk.asystemone = None + sdk.adecisions = AsyncMock( + return_value=DecisionsResponse.model_validate( + {"model": "decision", "id": "probe", "answers": {"probe": {"type": "noul", "noul": 1.0}}, "usage": {}} + ) + ) + + with patch.object(LiteLLMDecisionTarget, "_import_litellm", return_value=sdk): + result = await service.detect_capabilities_async( + target_registry_name="microsoft_decision", expected_hash=source.get_identifier().hash + ) + + assert result.capabilities == original + assert source.capabilities == original + sdk.adecisions.assert_awaited_once() + body = sdk.adecisions.call_args.kwargs + assert body["api_key"] == "key" + assert body["api_base"] == "https://example.test" + assert set(body["questions"]) == {"probe"} + + +@pytest.mark.parametrize("api_key", ["key", MagicMock(return_value="token")], ids=["key", "token_provider"]) +async def test_detection_rebuilds_prompt_shield_and_keeps_its_declarations_async( + detection_service: tuple[TargetService, _DetectableTarget], api_key: str | MagicMock +) -> None: + service, _ = detection_service + source = PromptShieldTarget(endpoint="https://example.test", api_key=api_key) + service._registry.instances.register(source, name="azure_content_safety") + original = source.capabilities + response = SimpleNamespace(content=b'{"userPromptAnalysis": {"attackDetected": false}, "documentsAnalysis": []}') + + with patch( + "pyrit.prompt_target.prompt_shield_target.net_utility.make_request_and_raise_if_error_async", + new=AsyncMock(return_value=response), + ) as shield: + result = await service.detect_capabilities_async( + target_registry_name="azure_content_safety", expected_hash=source.get_identifier().hash + ) + + assert result.capabilities == original + assert source.capabilities == original + shield.assert_awaited_once() + assert shield.call_args.kwargs["request_body"] == {"userPrompt": "test", "documents": []} + headers = shield.call_args.kwargs["headers"] + if isinstance(api_key, str): + assert headers["Ocp-Apim-Subscription-Key"] == "key" + else: + assert headers["Authorization"] == "Bearer token" + + @pytest.mark.parametrize("error", [CapabilityDiscoveryError("Connection failed"), TimeoutError()]) async def test_detection_failure_keeps_source_and_releases_probe( detection_service: tuple[TargetService, _DetectableTarget], error: Exception @@ -525,7 +593,7 @@ async def test_detection_rejects_unsafe_targets( service, _ = detection_service target = MockPromptTarget() service._registry.instances.register(target, name="unsafe") - with pytest.raises(ValueError, match="reconstruction"): + with pytest.raises(ValueError, match="not supported for MockPromptTarget because it can't be rebuilt"): await service.detect_capabilities_async( target_registry_name="unsafe", expected_hash=target.get_identifier().hash ) diff --git a/tests/unit/prompt_target/target/test_litellm_decision_target.py b/tests/unit/prompt_target/target/test_litellm_decision_target.py index 24e2f91ce6..9d86820e86 100644 --- a/tests/unit/prompt_target/target/test_litellm_decision_target.py +++ b/tests/unit/prompt_target/target/test_litellm_decision_target.py @@ -13,6 +13,7 @@ from pyrit.exceptions import PyritException, RateLimitException, get_retry_max_num_attempts from pyrit.models import Message, MessagePiece from pyrit.prompt_target import LiteLLMChatTarget, LiteLLMDecisionTarget +from pyrit.registry import TargetRegistry MODEL = "openrouter/microsoft/microsoft-decision-1" ENDPOINT = "https://openrouter.ai/api" @@ -106,6 +107,35 @@ def test_reuses_chat_target_without_chat_capabilities(self, target: LiteLLMDecis assert not target.capabilities.supports_multi_message_pieces assert target.capabilities.supported_input_modalities == ["text"] + @pytest.mark.parametrize("api_key", ["test-api-key", AsyncMock(return_value="test-token")], ids=["key", "provider"]) + async def test_reconstruction_keeps_identity_and_credentials_async( + self, *, api_key: str | AsyncMock, decision_sdk: MagicMock + ) -> None: + source = LiteLLMDecisionTarget( + model_name=MODEL, endpoint=ENDPOINT, api_key=api_key, headers={"X-Route": "a", "Authorization": "secret"} + ) + + rebuilt = TargetRegistry.get_registry_singleton().recreate_instance(source=source, params={}) + + assert rebuilt is not source + assert rebuilt.get_identifier().hash == source.get_identifier().hash + assert rebuilt._api_key is source._api_key + assert rebuilt._headers == source._headers + assert rebuilt._headers is not source._headers + assert "secret" not in rebuilt.get_identifier().model_dump_json() + await rebuilt.send_prompt_async(message=_request(json.dumps(REQUEST))) + body = decision_sdk.adecisions.call_args.kwargs + assert body["api_key"] == ("test-api-key" if isinstance(api_key, str) else "test-token") + assert body["api_base"] == ENDPOINT + assert body["extra_headers"] == {"X-Route": "a", "Authorization": "secret"} + + @pytest.mark.parametrize("params", [{"model_name": "anthropic/x"}, {"endpoint": "https://other.test"}]) + def test_reconstruction_keeps_connection_settings( + self, *, target: LiteLLMDecisionTarget, params: dict[str, str] + ) -> None: + with pytest.raises(ValueError, match="keeps its source's connection settings"): + TargetRegistry.get_registry_singleton().recreate_instance(source=target, params=params, external_input=True) + def test_empty_model_raises(self) -> None: with pytest.raises(ValueError, match="model name"): LiteLLMDecisionTarget(model_name=" ") diff --git a/tests/unit/prompt_target/target/test_prompt_shield_target.py b/tests/unit/prompt_target/target/test_prompt_shield_target.py index aaa038e3f0..2fe2d2b3da 100644 --- a/tests/unit/prompt_target/target/test_prompt_shield_target.py +++ b/tests/unit/prompt_target/target/test_prompt_shield_target.py @@ -14,6 +14,7 @@ from pyrit.models import Message, MessagePiece, flatten_to_message_pieces from pyrit.prompt_normalizer import ConverterConfiguration, PromptNormalizer from pyrit.prompt_target import PromptShieldTarget +from pyrit.registry import TargetRegistry @pytest.fixture @@ -276,6 +277,44 @@ async def test_prompt_shield_sends_the_converted_value_async(converted_value: st assert mock_request.await_args.kwargs["request_body"] == expected_body +@pytest.mark.usefixtures("patch_central_database") +@pytest.mark.parametrize("api_key", ["test_key", MagicMock(return_value="test_token")], ids=["key", "token_provider"]) +def test_reconstruction_keeps_identity_and_credential(api_key: str | MagicMock) -> None: + source = PromptShieldTarget( + endpoint="https://test.endpoint.com", api_key=api_key, api_version="2024-02-15-preview", field="documents" + ) + + rebuilt = TargetRegistry.get_registry_singleton().recreate_instance(source=source, params={}) + + assert rebuilt is not source + assert rebuilt.get_identifier().hash == source.get_identifier().hash + assert rebuilt._api_key is source._api_key + assert rebuilt._force_entry_field == "documents" + assert "test_key" not in rebuilt.get_identifier().model_dump_json() + + +@pytest.mark.usefixtures("patch_central_database") +def test_identity_reconstruction_reuses_the_token_provider_without_minting() -> None: + token_provider = MagicMock(return_value="minted-token") + with patch( + "pyrit.prompt_target.prompt_shield_target.get_azure_token_provider", return_value=token_provider + ) as mint: + source = PromptShieldTarget(endpoint="https://myresource.cognitiveservices.azure.com", auth_mode="identity") + rebuilt = TargetRegistry.get_registry_singleton().recreate_instance(source=source, params={}) + + mint.assert_called_once() + assert rebuilt._api_key is token_provider + + +@pytest.mark.usefixtures("patch_central_database") +@pytest.mark.parametrize("params", [{"endpoint": "https://other.test"}, {"api_key": "other"}, {"auth_mode": "api_key"}]) +def test_reconstruction_keeps_connection_settings(params: dict[str, str]) -> None: + source = PromptShieldTarget(endpoint="https://test.endpoint.com", api_key="test_key") + + with pytest.raises(ValueError, match="keeps its source's connection settings"): + TargetRegistry.get_registry_singleton().recreate_instance(source=source, params=params, external_input=True) + + @pytest.mark.usefixtures("patch_central_database") async def test_prompt_shield_sends_the_prompt_normalizer_conversion_async() -> None: target = PromptShieldTarget(endpoint="https://test.endpoint.com", api_key="test_key") From ed28617512db647cd45a79940faf93318fb2b85b Mon Sep 17 00:00:00 2001 From: Richard Lundeen Date: Sat, 21 Nov 2026 10:39:57 -0800 Subject: [PATCH 2/2] Probe the live target task-locally instead of rebuilding it Capability detection built a private copy of each target so its probe settings could not leak into other requests. That only worked for target types that support rebuilding. Probes now run on the live target inside a task-local scope: the permissive configuration uses the existing configuration contextvar, and the tool settings probes switch off are task-local attributes, so concurrent sends keep the target's own values. This removes the Decision and Prompt Shield reconstruction support and the not-rebuildable check; any target type can now be detected. Decision keeps its valid capability probe text. Co-Authored-By: Claude Opus 5.5 --- pyrit/backend/services/target_service.py | 33 ++++------ .../common/discover_target_capabilities.py | 63 +++++++++--------- pyrit/prompt_target/common/prompt_target.py | 66 ++++++++++++++++++- .../prompt_target/litellm_decision_target.py | 20 +----- pyrit/prompt_target/openai/openai_target.py | 10 +++ pyrit/prompt_target/prompt_shield_target.py | 19 ------ tests/unit/backend/test_target_detection.py | 60 ++++++----------- .../target/test_litellm_decision_target.py | 30 --------- .../target/test_prompt_shield_target.py | 39 ----------- .../target/test_prompt_target.py | 36 ++++++++++ 10 files changed, 173 insertions(+), 203 deletions(-) diff --git a/pyrit/backend/services/target_service.py b/pyrit/backend/services/target_service.py index 7016b36af4..467f8b7b1b 100644 --- a/pyrit/backend/services/target_service.py +++ b/pyrit/backend/services/target_service.py @@ -40,7 +40,7 @@ TargetTypeResponse, UnregisteredTarget, ) -from pyrit.backend.services.component_lifecycle import construct_component_async, release_component_async +from pyrit.backend.services.component_lifecycle import release_component_async from pyrit.common import AUTH_MODES, REQUIRED_VALUE, AuthMode, default_values from pyrit.models import Parameter, PromptDataType, TargetCapabilities, TargetIdentifier from pyrit.models.catalog import ( @@ -82,7 +82,6 @@ RegistryNameTakenError, registry_entry_origin, ) -from pyrit.registry.registry import Reconstructable logger = logging.getLogger(__name__) @@ -142,7 +141,7 @@ def capabilities_scope( async def detect_capabilities_async(self, *, target_registry_name: str, expected_hash: str) -> TargetInstance: """ - Probe private targets and apply a completed result to the selected source. + Probe a live target and apply a completed result to it. Round-robin detection probes each child independently and combines their results. Only the selected parent is updated; live children are not changed. @@ -164,12 +163,6 @@ async def detect_capabilities_async(self, *, target_registry_name: str, expected if getattr(target, "inner_targets", None) and not isinstance(target, RoundRobinTarget): raise ValueError("Capability detection is not supported for this composite target type.") sources = target.inner_targets if isinstance(target, RoundRobinTarget) else [target] - # Detection probes a private copy, so a target that can't be rebuilt can't be checked. - for source in sources: - if not isinstance(source, Reconstructable): - raise ValueError( - f"Capability detection is not supported for {type(source).__name__} because it can't be rebuilt." - ) snapshots = [(source, source.configuration) for source in [target, *sources]] source_ids = {id(source) for source, _ in snapshots} if target_registry_name in self._detecting or source_ids & self._detecting_sources: @@ -214,23 +207,19 @@ async def detect_capabilities_async(self, *, target_registry_name: str, expected async def _probe_capabilities_async(self, target: PromptTarget) -> TargetCapabilities: """ - Check one private target and release its resources. + Check one live target without changing it. + + Probes see their permissive settings only in their own task, so concurrent + requests to the target are unaffected and any target type can be checked. Returns: TargetCapabilities: Completed capability results. """ - probe = await construct_component_async(self._registry.recreate_instance, source=target, params={}) - try: - probe.apply_capabilities(capabilities=target.capabilities) - modalities: set[frozenset[PromptDataType]] = {frozenset({"text"})} - for modality in DEFAULT_TEST_ASSETS: - modalities.update({frozenset({modality}), frozenset({"text", modality})}) - modalities.update(TOOL_CALL_INPUT_MODALITIES) - return await discover_target_capabilities_async( - target=probe, test_modalities=modalities, raise_on_error=True - ) - finally: - await release_component_async(probe) + modalities: set[frozenset[PromptDataType]] = {frozenset({"text"})} + for modality in DEFAULT_TEST_ASSETS: + modalities.update({frozenset({modality}), frozenset({"text", modality})}) + modalities.update(TOOL_CALL_INPUT_MODALITIES) + return await discover_target_capabilities_async(target=target, test_modalities=modalities, raise_on_error=True) def _build_instance_from_entry( self, entry: RegistryEntry[PromptTarget], *, origin: RegistryEntryOrigin | None = None diff --git a/pyrit/prompt_target/common/discover_target_capabilities.py b/pyrit/prompt_target/common/discover_target_capabilities.py index e7e227290a..1f10cac0b2 100644 --- a/pyrit/prompt_target/common/discover_target_capabilities.py +++ b/pyrit/prompt_target/common/discover_target_capabilities.py @@ -43,9 +43,10 @@ import logging import uuid from collections.abc import Awaitable, Callable, Generator, Iterable, Mapping -from contextlib import ExitStack, contextmanager +from contextlib import contextmanager from contextvars import ContextVar from pathlib import Path +from typing import Any from pyrit.common.attack_result_scope import get_current_attack_result_id from pyrit.common.path import DATASETS_PATH @@ -148,15 +149,17 @@ def _permissive_configuration( extra_input_modalities: Iterable[frozenset[PromptDataType]] | None = None, ) -> Generator[None, None, None]: """ - Temporarily replace ``target``'s configuration with one that declares every - boolean capability as natively supported. + For this task only, give ``target`` a configuration that declares every + boolean capability as natively supported, and keep configured tools out of + probe requests. This bypasses ``PromptTarget._validate_request``, which would otherwise short-circuit probes for capabilities the target declares as unsupported - before any API call is made. The original configuration is restored on exit. + before any API call is made. The target itself is never modified, so + probes can run on a live target while other tasks use it. Args: - target (PromptTarget): The target whose configuration is temporarily replaced. + target (PromptTarget): The target to probe. extra_input_modalities (Iterable[frozenset[PromptDataType]] | None): Additional modality combinations to include in ``input_modalities`` during the override. Used by modality probes so that @@ -184,40 +187,34 @@ def _permissive_configuration( # probes bypass preflight validation without inheriting ADAPT policy or # custom normalizer overrides from the target's runtime configuration. probe_configuration = TargetConfiguration(capabilities=permissive_caps) - target._configuration = probe_configuration - try: - with _disable_probe_tools(target=target): - yield - finally: - target._configuration = original + # Both overrides apply to this task only, so other requests to a live target are unaffected. + with target._probe_scope(configuration=probe_configuration, attributes=_probe_tool_settings(target=target)): + yield -@contextmanager -def _disable_probe_tools(*, target: PromptTarget) -> Generator[None, None, None]: - """Disable configured tools during probes and restore all settings on exit.""" +def _probe_tool_settings(*, target: PromptTarget) -> dict[str, Any]: + """ + Return task-local settings that keep configured tools out of probe requests. + + Returns: + dict[str, Any]: Attribute values for ``PromptTarget._probe_scope``. + """ from pyrit.prompt_target.litellm_chat_target import LiteLLMChatTarget from pyrit.prompt_target.openai.openai_chat_target import OpenAIChatTarget from pyrit.prompt_target.openai.openai_response_target import OpenAIResponseTarget - with ExitStack() as stack: - if isinstance(target, (OpenAIChatTarget, OpenAIResponseTarget, LiteLLMChatTarget)): - original_body = target._extra_body_parameters - stack.callback(setattr, target, "_extra_body_parameters", original_body) - tool_settings = {"tools", "tool_choice", "parallel_tool_calls", "functions", "function_call"} - target._extra_body_parameters = { - key: value for key, value in (original_body or {}).items() if key not in tool_settings - } - extra_body = target._extra_body_parameters.get("extra_body") - if isinstance(extra_body, Mapping): - target._extra_body_parameters["extra_body"] = { - key: value for key, value in extra_body.items() if key not in tool_settings - } - if isinstance(target, (OpenAIResponseTarget, LiteLLMChatTarget)): - stack.callback(setattr, target, "_execute_tools", target._execute_tools) - stack.callback(setattr, target, "_suppress_tools", target._suppress_tools) - target._execute_tools = False - target._suppress_tools = True - yield + settings: dict[str, Any] = {} + if isinstance(target, (OpenAIChatTarget, OpenAIResponseTarget, LiteLLMChatTarget)): + tool_settings = {"tools", "tool_choice", "parallel_tool_calls", "functions", "function_call"} + body = {key: value for key, value in (target._extra_body_parameters or {}).items() if key not in tool_settings} + extra_body = body.get("extra_body") + if isinstance(extra_body, Mapping): + body["extra_body"] = {key: value for key, value in extra_body.items() if key not in tool_settings} + settings["_extra_body_parameters"] = body + if isinstance(target, (OpenAIResponseTarget, LiteLLMChatTarget)): + settings["_execute_tools"] = False + settings["_suppress_tools"] = True + return settings def _new_conversation_id() -> str: diff --git a/pyrit/prompt_target/common/prompt_target.py b/pyrit/prompt_target/common/prompt_target.py index e0e97ae8df..c337a89bb1 100644 --- a/pyrit/prompt_target/common/prompt_target.py +++ b/pyrit/prompt_target/common/prompt_target.py @@ -78,6 +78,35 @@ def _is_credential_rejection(error: BaseException) -> bool: # compatibility); it is canonically defined in ``pyrit.common.auth_mode`` so # ``pyrit.auth`` resolvers can consume it without depending on the target layer. +_ATTRIBUTE_SCOPES: ContextVar[tuple[tuple["PromptTarget", Mapping[str, Any]], ...]] = ContextVar( + "target_attribute_scopes", default=() +) + + +class _TaskLocalAttribute: + """ + An instance attribute that ``PromptTarget._probe_scope`` can override for one task. + + Every other task, including a concurrent send on the same target, reads the stored value. + """ + + def __set_name__(self, owner: type, name: str) -> None: # pyrit-keyword-only-exempt descriptor protocol + self._name = name + + def __get__(self, instance: object, owner: type | None = None) -> Any: # pyrit-keyword-only-exempt descriptor + if instance is None: + return self + for target, overrides in reversed(_ATTRIBUTE_SCOPES.get()): + if target is instance and self._name in overrides: + return overrides[self._name] + try: + return instance.__dict__[self._name] + except KeyError: + raise AttributeError(self._name) from None + + def __set__(self, instance: object, value: Any) -> None: # pyrit-keyword-only-exempt descriptor protocol + instance.__dict__[self._name] = value + class PromptTarget(Identifiable): """ @@ -124,6 +153,10 @@ class PromptTarget(Identifiable): _CONFIGURATION_SCOPES: ClassVar[ContextVar[tuple[tuple["PromptTarget", TargetConfiguration], ...]]] = ContextVar( "target_configuration_scopes", default=() ) + # Tool settings that capability probes turn off for their own task only (see ``_probe_scope``). + _extra_body_parameters = _TaskLocalAttribute() + _execute_tools = _TaskLocalAttribute() + _suppress_tools = _TaskLocalAttribute() # Declarative auth facts consumed by the create-target service and catalog. # Kept off ``TargetCapabilities`` (auth is a construction/credential axis, not @@ -683,7 +716,7 @@ def _reset_credential_status(self) -> None: def attach_reconstruction_source(self, source: object) -> None: """ - Share request pacing and credential status, not clients or behavioral configuration. + Report credential rejections into the target this copy was built from. Args: source (object): The registered target this copy was built from. @@ -691,7 +724,6 @@ def attach_reconstruction_source(self, source: object) -> None: if isinstance(source, PromptTarget): self._credential_status_source = source._credential_status_owner() self._credential_generation = source._credential_generation - self._rate_limit_source = getattr(source, "_rate_limit_source", source) def _validate_request(self, *, normalized_conversation: list[Message]) -> None: """ @@ -1081,6 +1113,36 @@ def capabilities_scope(self, capabilities: TargetCapabilities) -> Generator[None finally: self._CONFIGURATION_SCOPES.reset(token) + @contextmanager + def _probe_scope( + self, *, configuration: TargetConfiguration, attributes: Mapping[str, Any] + ) -> Generator[None, None, None]: + """ + Use a configuration and tool settings for this task only, so probes can run on a live target. + + Unlike ``capabilities_scope``, the configuration is used as given, without masking. + + Args: + configuration: The configuration this task sees. + attributes: Values for this target's task-local attributes, such as ``_execute_tools``. + + Yields: + None: The task-local scope, restored even on cancellation. + + Raises: + ValueError: If an attribute is not task-local, so setting it would change every task. + """ + for name in attributes: + if not isinstance(getattr(type(self), name, None), _TaskLocalAttribute): + raise ValueError(f"{type(self).__name__}.{name} cannot be overridden for one task.") + configuration_token = self._CONFIGURATION_SCOPES.set((*self._CONFIGURATION_SCOPES.get(), (self, configuration))) + attribute_token = _ATTRIBUTE_SCOPES.set((*_ATTRIBUTE_SCOPES.get(), (self, dict(attributes)))) + try: + yield + finally: + _ATTRIBUTE_SCOPES.reset(attribute_token) + self._CONFIGURATION_SCOPES.reset(configuration_token) + @property def capabilities(self) -> TargetCapabilities: """ diff --git a/pyrit/prompt_target/litellm_decision_target.py b/pyrit/prompt_target/litellm_decision_target.py index 4525ebb6d1..0a0a880641 100644 --- a/pyrit/prompt_target/litellm_decision_target.py +++ b/pyrit/prompt_target/litellm_decision_target.py @@ -44,8 +44,7 @@ class LiteLLMDecisionTarget(LiteLLMChatTarget): _SUPPORTS_TOOL_CALL_HISTORY = False _DEFAULT_CONFIGURATION = TargetConfiguration(capabilities=TargetCapabilities()) - # The model name's provider prefix chooses where LiteLLM sends the key when no endpoint is set. - COPY_LOCKED_PARAMETER_NAMES: ClassVar[frozenset[str]] = frozenset({"model_name", "endpoint", "api_key", "headers"}) + # Capability detection's text probe must be a valid decision request, like DecisionScorer's. capability_probe_text: ClassVar[str] = json.dumps( { "state": "test", @@ -108,23 +107,6 @@ def _build_identifier(self) -> ComponentIdentifier: """ return self._create_identifier(params={"endpoint": self._endpoint, "headers": self._identifier_headers()}) - def get_reconstruction_parameters(self) -> dict[str, object]: - """ - Return server-only inputs, including the resolved key or token provider. - - Returns: - dict[str, object]: Constructor inputs that rebuild this target. - """ - return { - "model_name": self._model_name, - "endpoint": self._endpoint, - "api_key": self._api_key, - "headers": self._headers, - "max_requests_per_minute": self._max_requests_per_minute, - "custom_configuration": self.configuration, - "trace_config": self._trace_config, - } - @pyrit_target_retry @limit_requests_per_minute async def _send_prompt_to_target_async(self, *, normalized_conversation: list[Message]) -> list[Message]: diff --git a/pyrit/prompt_target/openai/openai_target.py b/pyrit/prompt_target/openai/openai_target.py index e0c5ea3bab..9e6d58b62e 100644 --- a/pyrit/prompt_target/openai/openai_target.py +++ b/pyrit/prompt_target/openai/openai_target.py @@ -504,6 +504,16 @@ async def cleanup_target_async(self) -> None: if self._async_client is not None: await self._async_client.close() + def attach_reconstruction_source(self, source: object) -> None: + """ + Share request pacing and credential status, not clients or behavioral configuration. + + Args: + source (object): The registered target this copy was built from. + """ + super().attach_reconstruction_source(source) + self._rate_limit_source = getattr(source, "_rate_limit_source", source) + @property def supports_credential_updates(self) -> bool: """Whether this target can replace its API key or request headers in place; not with its own HTTP client.""" diff --git a/pyrit/prompt_target/prompt_shield_target.py b/pyrit/prompt_target/prompt_shield_target.py index a89a55f593..0c9cf411c3 100644 --- a/pyrit/prompt_target/prompt_shield_target.py +++ b/pyrit/prompt_target/prompt_shield_target.py @@ -70,7 +70,6 @@ class PromptShieldTarget(PromptTarget): server_fallback_parameters: ClassVar[Mapping[str, str | None]] = MappingProxyType({"api_key": None}) destination_parameters: ClassVar[Mapping[str, bool]] = MappingProxyType({"endpoint": True}) environment_backed_parameters: ClassVar[frozenset[str]] = frozenset({"endpoint"}) - COPY_LOCKED_PARAMETER_NAMES: ClassVar[frozenset[str]] = frozenset({"endpoint", "api_key", "auth_mode"}) _endpoint: str _api_key: str | Callable[[], str] | None @@ -199,24 +198,6 @@ def get_auth_mode_parameters(cls, *, auth_mode: AuthMode) -> dict[str, object]: """ return {"auth_mode": auth_mode} - def get_reconstruction_parameters(self) -> dict[str, object]: - """ - Return server-only inputs, including the resolved key or token provider. - - Returns: - dict[str, object]: Constructor inputs that rebuild this target. - """ - return { - "endpoint": self._endpoint, - # Reuse the resolved key or token provider, not the original credential-selection mode. - "api_key": self._api_key, - "auth_mode": "api_key", - "api_version": self._api_version, - "field": self._force_entry_field, - "max_requests_per_minute": self._max_requests_per_minute, - "custom_configuration": self.configuration, - } - def _build_identifier(self) -> ComponentIdentifier: """ Build the identifier with Prompt Shield-specific parameters. diff --git a/tests/unit/backend/test_target_detection.py b/tests/unit/backend/test_target_detection.py index 0cd6308e96..93a9cff530 100644 --- a/tests/unit/backend/test_target_detection.py +++ b/tests/unit/backend/test_target_detection.py @@ -95,7 +95,7 @@ def composite_detection( return service, parent -async def test_composite_detection_probes_each_child_privately_and_updates_only_parent( +async def test_composite_detection_probes_each_live_child_and_updates_only_parent( composite_detection: tuple[TargetService, RoundRobinTarget], ) -> None: service, parent = composite_detection @@ -116,7 +116,6 @@ async def test_composite_detection_probes_each_child_privately_and_updates_only_ probes: list[_DetectableTarget] = [] async def discover_async(*, target: _DetectableTarget, **kwargs: object) -> TargetCapabilities: - assert all(target is not child for child in children) probes.append(target) return results[len(probes) - 1] @@ -125,9 +124,7 @@ async def discover_async(*, target: _DetectableTarget, **kwargs: object) -> Targ target_registry_name="round-robin", expected_hash=expected_hash ) - assert len(probes) == 2 - assert probes[0] is not probes[1] - assert all(probe.closed for probe in probes) + assert probes == children assert response.capabilities == parent.aggregate_capabilities(child_capabilities=results) assert parent.capabilities == response.capabilities assert parent.capabilities.supports_json_output @@ -162,8 +159,7 @@ async def discover_async(*, target: _DetectableTarget, **kwargs: object) -> Targ target_registry_name="round-robin", expected_hash=parent.get_identifier().hash ) - assert len(probes) == 2 - assert all(probe.closed for probe in probes) + assert probes == children assert parent.configuration is original assert all(child.configuration is original for child, original in zip(children, originals, strict=True)) assert not service._detecting @@ -292,7 +288,7 @@ async def probe_async(target: _DetectableTarget) -> TargetCapabilities: assert not service._detecting_sources -async def test_composite_detection_reconstructs_each_openai_endpoint_with_its_own_client( +async def test_composite_detection_probes_each_openai_child_with_its_open_client( detection_service: tuple[TargetService, _DetectableTarget], ) -> None: service, _ = detection_service @@ -317,14 +313,8 @@ async def discover_async(*, target: OpenAIChatTarget, **kwargs: object) -> Targe target_registry_name="openai-round-robin", expected_hash=parent.get_identifier().hash ) assert result.capabilities.supports_json_output - assert len(probes) == len(children) - for probe, child in zip(probes, children, strict=True): - assert probe.get_identifier().hash == child.get_identifier().hash - assert probe._async_client is not child._async_client - assert probe._async_client is not None - assert probe._async_client.is_closed() - assert child._async_client is not None - assert not child._async_client.is_closed() + assert probes == children + assert all(child._async_client is not None and not child._async_client.is_closed() for child in children) finally: for child in children: await child.cleanup_target_async() @@ -371,12 +361,12 @@ async def wait_async(*, target: _DetectableTarget, **kwargs: object) -> TargetCa with pytest.raises(asyncio.CancelledError): await task assert parent.configuration is original - assert all(probe.closed for probe in probes) + assert not any(probe.closed for probe in probes) assert not service._detecting assert not service._detecting_sources -async def test_detection_applies_private_result_and_releases_probe( +async def test_detection_probes_and_updates_the_live_target( detection_service: tuple[TargetService, _DetectableTarget], ) -> None: service, target = detection_service @@ -387,8 +377,8 @@ async def test_detection_applies_private_result_and_releases_probe( async def discover_async(*, target: _DetectableTarget, **kwargs: object) -> TargetCapabilities: probes.append(target) - assert target is not detection_service[1] - assert detection_service[1].configuration is original + assert target is detection_service[1] + assert target.configuration is original assert kwargs["raise_on_error"] is True assert frozenset({"text", "image_path"}) in kwargs["test_modalities"] return detected @@ -402,11 +392,8 @@ async def discover_async(*, target: _DetectableTarget, **kwargs: object) -> Targ assert target.capabilities == detected assert target.configuration.policy == original.policy assert result.identifier.hash == expected_hash - assert probes[0].closed + assert probes == [target] assert not target.closed - rebuilt = service._registry.recreate_instance(source=target, params={}) - assert rebuilt.capabilities == detected - await rebuilt.cleanup_target_async() async def test_detection_returns_the_origin_of_the_registered_target( @@ -441,7 +428,7 @@ async def test_detection_preserves_declarations_without_verified_adapter_probes( assert result.capabilities.output_modalities == frozenset({frozenset({"text"})}) -async def test_detection_reconstructs_openai_without_closing_the_live_client( +async def test_detection_probes_openai_with_its_open_client( detection_service: tuple[TargetService, _DetectableTarget], ) -> None: service, _ = detection_service @@ -462,16 +449,14 @@ async def discover_async(*, target: OpenAIChatTarget, **kwargs: object) -> Targe target_registry_name="openai", expected_hash=target.get_identifier().hash ) assert result.capabilities.supports_json_output - assert probes[0]._async_client is not target._async_client - assert probes[0]._async_client is not None + assert probes == [target] assert target._async_client is not None - assert probes[0]._async_client.is_closed() assert not target._async_client.is_closed() finally: await target.cleanup_target_async() -async def test_detection_rebuilds_decision_target_and_sends_a_valid_control_request_async( +async def test_detection_sends_a_valid_control_request_to_the_decision_target_async( detection_service: tuple[TargetService, _DetectableTarget], ) -> None: litellm = pytest.importorskip("litellm") @@ -504,7 +489,7 @@ async def test_detection_rebuilds_decision_target_and_sends_a_valid_control_requ @pytest.mark.parametrize("api_key", ["key", MagicMock(return_value="token")], ids=["key", "token_provider"]) -async def test_detection_rebuilds_prompt_shield_and_keeps_its_declarations_async( +async def test_detection_probes_prompt_shield_and_keeps_its_declarations_async( detection_service: tuple[TargetService, _DetectableTarget], api_key: str | MagicMock ) -> None: service, _ = detection_service @@ -533,7 +518,7 @@ async def test_detection_rebuilds_prompt_shield_and_keeps_its_declarations_async @pytest.mark.parametrize("error", [CapabilityDiscoveryError("Connection failed"), TimeoutError()]) -async def test_detection_failure_keeps_source_and_releases_probe( +async def test_detection_failure_keeps_the_source_unchanged( detection_service: tuple[TargetService, _DetectableTarget], error: Exception ) -> None: service, target = detection_service @@ -550,7 +535,7 @@ async def fail_async(*, target: _DetectableTarget, **kwargs: object) -> TargetCa target_registry_name="test-target", expected_hash=target.get_identifier().hash ) assert target.configuration is original - assert probes[0].closed + assert probes == [target] assert not service._detecting @@ -587,16 +572,12 @@ async def test_detection_rejects_missing_stale_and_duplicate_requests( ) -async def test_detection_rejects_unsafe_targets( +async def test_detection_rejects_unsupported_composites( detection_service: tuple[TargetService, _DetectableTarget], ) -> None: service, _ = detection_service target = MockPromptTarget() service._registry.instances.register(target, name="unsafe") - with pytest.raises(ValueError, match="not supported for MockPromptTarget because it can't be rebuilt"): - await service.detect_capabilities_async( - target_registry_name="unsafe", expected_hash=target.get_identifier().hash - ) target.inner_targets = [MockPromptTarget()] with pytest.raises(ValueError, match="composite"): await service.detect_capabilities_async( @@ -627,7 +608,7 @@ async def wait_async(**kwargs: object) -> TargetCapabilities: assert not service._detecting -async def test_detection_cancellation_releases_probe_and_admission( +async def test_detection_cancellation_releases_admission( detection_service: tuple[TargetService, _DetectableTarget], ) -> None: service, target = detection_service @@ -653,7 +634,8 @@ async def wait_async(*, target: _DetectableTarget, **kwargs: object) -> TargetCa task.cancel() with pytest.raises(asyncio.CancelledError): await task - assert probes[0].closed + assert probes == [target] + assert not target.closed assert target.configuration is original assert not service._detecting assert not service._detecting_sources diff --git a/tests/unit/prompt_target/target/test_litellm_decision_target.py b/tests/unit/prompt_target/target/test_litellm_decision_target.py index 9d86820e86..24e2f91ce6 100644 --- a/tests/unit/prompt_target/target/test_litellm_decision_target.py +++ b/tests/unit/prompt_target/target/test_litellm_decision_target.py @@ -13,7 +13,6 @@ from pyrit.exceptions import PyritException, RateLimitException, get_retry_max_num_attempts from pyrit.models import Message, MessagePiece from pyrit.prompt_target import LiteLLMChatTarget, LiteLLMDecisionTarget -from pyrit.registry import TargetRegistry MODEL = "openrouter/microsoft/microsoft-decision-1" ENDPOINT = "https://openrouter.ai/api" @@ -107,35 +106,6 @@ def test_reuses_chat_target_without_chat_capabilities(self, target: LiteLLMDecis assert not target.capabilities.supports_multi_message_pieces assert target.capabilities.supported_input_modalities == ["text"] - @pytest.mark.parametrize("api_key", ["test-api-key", AsyncMock(return_value="test-token")], ids=["key", "provider"]) - async def test_reconstruction_keeps_identity_and_credentials_async( - self, *, api_key: str | AsyncMock, decision_sdk: MagicMock - ) -> None: - source = LiteLLMDecisionTarget( - model_name=MODEL, endpoint=ENDPOINT, api_key=api_key, headers={"X-Route": "a", "Authorization": "secret"} - ) - - rebuilt = TargetRegistry.get_registry_singleton().recreate_instance(source=source, params={}) - - assert rebuilt is not source - assert rebuilt.get_identifier().hash == source.get_identifier().hash - assert rebuilt._api_key is source._api_key - assert rebuilt._headers == source._headers - assert rebuilt._headers is not source._headers - assert "secret" not in rebuilt.get_identifier().model_dump_json() - await rebuilt.send_prompt_async(message=_request(json.dumps(REQUEST))) - body = decision_sdk.adecisions.call_args.kwargs - assert body["api_key"] == ("test-api-key" if isinstance(api_key, str) else "test-token") - assert body["api_base"] == ENDPOINT - assert body["extra_headers"] == {"X-Route": "a", "Authorization": "secret"} - - @pytest.mark.parametrize("params", [{"model_name": "anthropic/x"}, {"endpoint": "https://other.test"}]) - def test_reconstruction_keeps_connection_settings( - self, *, target: LiteLLMDecisionTarget, params: dict[str, str] - ) -> None: - with pytest.raises(ValueError, match="keeps its source's connection settings"): - TargetRegistry.get_registry_singleton().recreate_instance(source=target, params=params, external_input=True) - def test_empty_model_raises(self) -> None: with pytest.raises(ValueError, match="model name"): LiteLLMDecisionTarget(model_name=" ") diff --git a/tests/unit/prompt_target/target/test_prompt_shield_target.py b/tests/unit/prompt_target/target/test_prompt_shield_target.py index 2fe2d2b3da..aaa038e3f0 100644 --- a/tests/unit/prompt_target/target/test_prompt_shield_target.py +++ b/tests/unit/prompt_target/target/test_prompt_shield_target.py @@ -14,7 +14,6 @@ from pyrit.models import Message, MessagePiece, flatten_to_message_pieces from pyrit.prompt_normalizer import ConverterConfiguration, PromptNormalizer from pyrit.prompt_target import PromptShieldTarget -from pyrit.registry import TargetRegistry @pytest.fixture @@ -277,44 +276,6 @@ async def test_prompt_shield_sends_the_converted_value_async(converted_value: st assert mock_request.await_args.kwargs["request_body"] == expected_body -@pytest.mark.usefixtures("patch_central_database") -@pytest.mark.parametrize("api_key", ["test_key", MagicMock(return_value="test_token")], ids=["key", "token_provider"]) -def test_reconstruction_keeps_identity_and_credential(api_key: str | MagicMock) -> None: - source = PromptShieldTarget( - endpoint="https://test.endpoint.com", api_key=api_key, api_version="2024-02-15-preview", field="documents" - ) - - rebuilt = TargetRegistry.get_registry_singleton().recreate_instance(source=source, params={}) - - assert rebuilt is not source - assert rebuilt.get_identifier().hash == source.get_identifier().hash - assert rebuilt._api_key is source._api_key - assert rebuilt._force_entry_field == "documents" - assert "test_key" not in rebuilt.get_identifier().model_dump_json() - - -@pytest.mark.usefixtures("patch_central_database") -def test_identity_reconstruction_reuses_the_token_provider_without_minting() -> None: - token_provider = MagicMock(return_value="minted-token") - with patch( - "pyrit.prompt_target.prompt_shield_target.get_azure_token_provider", return_value=token_provider - ) as mint: - source = PromptShieldTarget(endpoint="https://myresource.cognitiveservices.azure.com", auth_mode="identity") - rebuilt = TargetRegistry.get_registry_singleton().recreate_instance(source=source, params={}) - - mint.assert_called_once() - assert rebuilt._api_key is token_provider - - -@pytest.mark.usefixtures("patch_central_database") -@pytest.mark.parametrize("params", [{"endpoint": "https://other.test"}, {"api_key": "other"}, {"auth_mode": "api_key"}]) -def test_reconstruction_keeps_connection_settings(params: dict[str, str]) -> None: - source = PromptShieldTarget(endpoint="https://test.endpoint.com", api_key="test_key") - - with pytest.raises(ValueError, match="keeps its source's connection settings"): - TargetRegistry.get_registry_singleton().recreate_instance(source=source, params=params, external_input=True) - - @pytest.mark.usefixtures("patch_central_database") async def test_prompt_shield_sends_the_prompt_normalizer_conversion_async() -> None: target = PromptShieldTarget(endpoint="https://test.endpoint.com", api_key="test_key") diff --git a/tests/unit/prompt_target/target/test_prompt_target.py b/tests/unit/prompt_target/target/test_prompt_target.py index a2264ed070..9280792894 100644 --- a/tests/unit/prompt_target/target/test_prompt_target.py +++ b/tests/unit/prompt_target/target/test_prompt_target.py @@ -113,6 +113,42 @@ def scoped_operation() -> None: assert other.configuration is other_original +@pytest.mark.usefixtures("patch_central_database") +async def test_probe_scope_changes_settings_only_for_its_own_task() -> None: + target = MockPromptTarget() + target._execute_tools = True + original = target.configuration + probe_configuration = TargetConfiguration(capabilities=TargetCapabilities(supports_json_output=True)) + probing = asyncio.Event() + probed = asyncio.Event() + seen_by_other_task: list[object] = [] + + async def concurrent_send_async() -> None: + await probing.wait() + seen_by_other_task.extend([target.configuration, target._execute_tools]) + probed.set() + + other_task = asyncio.create_task(concurrent_send_async()) + with target._probe_scope(configuration=probe_configuration, attributes={"_execute_tools": False}): + assert target.configuration is probe_configuration + assert target._execute_tools is False + probing.set() + await asyncio.wait_for(probed.wait(), timeout=TEST_WATCHDOG_SECONDS) + await other_task + + assert seen_by_other_task == [original, True] + assert target.configuration is original + assert target._execute_tools is True + + +@pytest.mark.usefixtures("patch_central_database") +def test_probe_scope_rejects_attributes_that_would_change_every_task() -> None: + target = MockPromptTarget() + with pytest.raises(ValueError, match="MockPromptTarget._endpoint cannot be overridden for one task"): + with target._probe_scope(configuration=target.configuration, attributes={"_endpoint": "elsewhere"}): + pass + + @pytest.mark.usefixtures("patch_central_database") async def test_capabilities_scope_does_not_change_concurrent_target_reads_async() -> None: target = MockPromptTarget()