Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 0 additions & 1 deletion frontend/e2e/converters.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -294,7 +294,6 @@ async function mockBackendAPIs(page: Page) {
convertedText = textPiece?.converted_value ?? null;
converterIds = textPiece?.applied_converter_ids ?? body?.request_converter_configurations
?.flatMap((configuration: { converter_ids?: string[] }) => configuration.converter_ids ?? [])
?? body?.converter_ids
?? [];
} catch {
// ignore
Expand Down
1 change: 0 additions & 1 deletion frontend/src/types/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1397,7 +1397,6 @@ export interface AddMessageRequest extends MessageRequest {
send: boolean
target_registry_name?: string
target_binding?: TargetBinding
converter_ids?: string[]
request_converter_configurations?: ConverterConfigurationRequest[]
response_converter_configurations?: ConverterConfigurationRequest[]
start_token?: string
Expand Down
31 changes: 22 additions & 9 deletions pyrit/backend/models/attacks.py
Original file line number Diff line number Diff line change
Expand Up @@ -861,11 +861,6 @@ class AddMessageRequest(MessageRequest):
description="Target registry name. Required when send=True so the backend knows which target to use.",
)
target_binding: TargetBindingInput | None = None
converter_ids: list[IdentifierStr] | None = Field(
None,
max_length=MAX_ITEMS,
description="Deprecated global request converter pipeline. Use request_converter_configurations instead.",
)
request_converter_configurations: list[ConverterConfigurationRequest] | None = Field(
None,
min_length=1,
Expand Down Expand Up @@ -896,6 +891,27 @@ class AddMessageRequest(MessageRequest):
"Usually the attack's main conversation, but can be a related conversation.",
)

@model_validator(mode="before")
@classmethod
def _reject_removed_converter_ids(cls, data: Any) -> Any:
"""
Reject the removed top-level ``converter_ids`` field instead of silently ignoring it.

Unknown fields are otherwise ignored, so a client still sending ``converter_ids``
would have its message sent without converters and without any error.

Returns:
The unchanged model input.

Raises:
ValueError: If the input has a top-level ``converter_ids`` field.
"""
if isinstance(data, dict) and "converter_ids" in data:
raise ValueError(
"converter_ids is no longer supported on this request; use request_converter_configurations instead"
)
return data

@model_validator(mode="after")
def _validate_converter_configurations(self) -> "AddMessageRequest":
"""
Expand All @@ -909,11 +925,8 @@ def _validate_converter_configurations(self) -> "AddMessageRequest":
"""
if any(piece.source_piece_id is not None for piece in self.pieces):
raise ValueError("source_piece_id requires a complete conversation save")
if self.converter_ids and self.request_converter_configurations:
raise ValueError("converter_ids and request_converter_configurations cannot both be provided")

has_converter_configurations = bool(
self.converter_ids or self.request_converter_configurations or self.response_converter_configurations
self.request_converter_configurations or self.response_converter_configurations
)
if not self.send and has_converter_configurations:
raise ValueError("Converter configurations require send=True")
Expand Down
3 changes: 1 addition & 2 deletions pyrit/backend/routes/attacks.py
Original file line number Diff line number Diff line change
Expand Up @@ -680,8 +680,7 @@ async def add_message( # pyrit-async-suffix-exempt

Request and response converters can be supplied as ordered, registry-backed
configurations. Each configuration can target message piece indexes, prompt
data types, or both. The global ``converter_ids`` request pipeline remains
available for compatibility but is deprecated.
data types, or both.

Returns:
AddMessageResponse: Updated attack with new message(s).
Expand Down
13 changes: 1 addition & 12 deletions pyrit/backend/services/message_send_service.py
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,6 @@
)
from pyrit.backend.services.media_persistence import persist_message_pieces_async
from pyrit.backend.services.target_service import get_target_service
from pyrit.common import print_deprecation_message
from pyrit.common.attack_result_scope import attack_result_id_scope
from pyrit.memory import CentralMemory, data_serializer_factory
from pyrit.models import (
Expand Down Expand Up @@ -1249,21 +1248,11 @@ async def _resolve_video_remix_metadata_async(self, request: AddMessageRequest)

def _resolve_request_converter_configs(self, *, request: AddMessageRequest) -> list[ConverterConfiguration]:
"""
Resolve legacy or structured request converter configurations.
Resolve the request's converter configurations.

Returns:
list[ConverterConfiguration]: Resolved request configurations.
"""
if request.converter_ids is not None:
print_deprecation_message(
old_item="AddMessageRequest.converter_ids",
new_item="AddMessageRequest.request_converter_configurations",
removed_in="1.3.0",
)
if request.converter_ids:
converters = get_converter_service().get_converter_objects_for_ids(converter_ids=request.converter_ids)
return ConverterConfiguration.from_converters(converters=converters)

return self._resolve_converter_configs(configurations=request.request_converter_configurations)

def _resolve_converter_configs(
Expand Down
24 changes: 19 additions & 5 deletions tests/unit/backend/test_api_routes.py
Original file line number Diff line number Diff line change
Expand Up @@ -635,10 +635,6 @@ def test_add_message_success(self, client: TestClient) -> None:
@pytest.mark.parametrize(
"converter_fields",
[
{
"converter_ids": ["legacy-converter"],
"request_converter_configurations": [{"converter_ids": ["request-converter"]}],
},
{"request_converter_configurations": []},
{"request_converter_configurations": [{"converter_ids": []}]},
{"response_converter_configurations": []},
Expand Down Expand Up @@ -678,11 +674,29 @@ def test_add_message_rejects_converter_configuration_when_send_is_false(self, cl
"pieces": [{"original_value": "Hello"}],
"target_conversation_id": "attack-1",
"send": False,
"converter_ids": ["legacy-converter"],
"request_converter_configurations": [{"converter_ids": ["request-converter"]}],
},
)
assert response.status_code == status.HTTP_422_UNPROCESSABLE_CONTENT
mock_get_service.return_value.add_message_async.assert_not_called()

@pytest.mark.parametrize("converter_ids", [["legacy-converter"], [], None])
def test_add_message_rejects_removed_top_level_converter_ids(
self, client: TestClient, converter_ids: list[str] | None
) -> None:
"""Test that a client still sending converter_ids is rejected instead of sent without converters."""
with patch("pyrit.backend.routes.attacks.get_attack_service") as mock_get_service:
response = client.post(
"/api/attacks/attack-1/messages",
json={
"pieces": [{"original_value": "Hello"}],
"target_conversation_id": "attack-1",
"target_registry_name": "test-target",
"converter_ids": converter_ids,
},
)
assert response.status_code == status.HTTP_422_UNPROCESSABLE_CONTENT
assert "request_converter_configurations" in response.text
mock_get_service.return_value.add_message_async.assert_not_called()

def test_update_attack_not_found(self, client: TestClient) -> None:
Expand Down
1 change: 0 additions & 1 deletion tests/unit/backend/test_common_models.py
Original file line number Diff line number Diff line change
Expand Up @@ -600,7 +600,6 @@ def test_update_attack_request_expected_objective_is_not_length_limited() -> Non
"overrides",
[
{"target_conversation_id": "c" * (MAX_IDENTIFIER_LENGTH + 1)},
{"converter_ids": ["converter"] * (MAX_ITEMS + 1)},
{"request_converter_configurations": [{"converter_ids": ["converter"]}] * (MAX_ITEMS + 1)},
{"pieces": [{"original_value": "text", "mime_type": "m" * (MAX_IDENTIFIER_LENGTH + 1)}]},
{"start_token": "s" * (MAX_IDENTIFIER_LENGTH + 1)},
Expand Down
90 changes: 0 additions & 90 deletions tests/unit/backend/test_message_send_service.py
Original file line number Diff line number Diff line change
Expand Up @@ -413,96 +413,6 @@ async def test_add_message_reraises_when_send_fails_without_stored_error_piece(
with pytest.raises(RuntimeError, match="boom"):
await message_send_service.add_message_async(attack_result_id="test-id", request=request)

async def test_add_message_with_legacy_converter_ids_warns_and_preserves_behavior(
self, message_send_service, mock_memory
) -> None:
"""Test that legacy converter IDs warn and remain an unrestricted pipeline."""
ar = make_attack_result(conversation_id="test-id")
mock_memory.get_attack_results_async.return_value = [ar]
mock_memory.get_message_pieces_async.return_value = []
mock_memory.get_conversation_messages_async.return_value = []

with (
patch("pyrit.backend.services.message_send_service.get_target_service") as mock_get_target_svc,
patch("pyrit.backend.services.message_send_service.get_converter_service") as mock_get_conv_svc,
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()
mock_get_target_svc.return_value = mock_target_svc

first_converter = MagicMock()
first_converter.get_identifier.return_value = ComponentIdentifier(
class_name="FirstConverter",
class_module="test_module",
params={"supported_input_types": ("text",), "supported_output_types": ("text",)},
)
second_converter = MagicMock()
second_converter.get_identifier.return_value = ComponentIdentifier(
class_name="SecondConverter",
class_module="test_module",
params={"supported_input_types": ("text",), "supported_output_types": ("text",)},
)
mock_conv_svc = MagicMock()
mock_conv_svc.get_converter_objects_for_ids.return_value = [first_converter, second_converter]
mock_get_conv_svc.return_value = mock_conv_svc

mock_normalizer = MagicMock()
mock_normalizer.send_prompt_async = AsyncMock()
mock_normalizer_cls.return_value = mock_normalizer

request = AddMessageRequest(
pieces=[MessagePieceRequest(original_value="Hello")],
target_conversation_id="test-id",
send=True,
converter_ids=["first", "second"],
target_registry_name="test-target",
)

with pytest.warns(DeprecationWarning, match="AddMessageRequest.converter_ids is deprecated"):
await message_send_service.add_message_async(attack_result_id="test-id", request=request)

configurations = mock_normalizer.send_prompt_async.call_args.kwargs["request_converter_configurations"]
assert [configuration.converters for configuration in configurations] == [
[first_converter],
[second_converter],
]
assert all(configuration.indexes_to_apply is None for configuration in configurations)
mock_conv_svc.get_converter_objects_for_ids.assert_called_once_with(converter_ids=["first", "second"])

def test_empty_legacy_converter_ids_allow_store_only_request(self) -> None:
"""Test that an empty legacy converter list remains a no-op when send is false."""
request = AddMessageRequest(
pieces=[MessagePieceRequest(original_value="Hello")],
target_conversation_id="test-id",
send=False,
converter_ids=[],
)

assert request.converter_ids == []

def test_empty_legacy_converter_ids_warn_and_use_structured_configuration(self, message_send_service) -> None:
"""Test that an empty legacy list does not override a structured configuration."""
converter = MagicMock()
request = AddMessageRequest(
pieces=[MessagePieceRequest(original_value="Hello")],
target_conversation_id="test-id",
converter_ids=[],
request_converter_configurations=[ConverterConfigurationRequest(converter_ids=["structured"])],
)

with patch("pyrit.backend.services.message_send_service.get_converter_service") as mock_get_converter_service:
mock_get_converter_service.return_value.get_converter_objects_for_ids.return_value = [converter]

with pytest.warns(DeprecationWarning, match="AddMessageRequest.converter_ids is deprecated"):
configurations = message_send_service._resolve_request_converter_configs(request=request)

assert len(configurations) == 1
assert configurations[0].converters == [converter]
mock_get_converter_service.return_value.get_converter_objects_for_ids.assert_called_once_with(
converter_ids=["structured"]
)

async def test_add_message_preserves_converter_configuration_targeting(
self, message_send_service, mock_memory
) -> None:
Expand Down
Loading