From fd1f38d065cf180cf561fdffc56a350d603cef2b Mon Sep 17 00:00:00 2001 From: Dev3 ^~^ Date: Wed, 18 Nov 2026 22:37:31 +0530 Subject: [PATCH 1/2] FEAT: Add JsonFieldConverter --- doc/code/converters/0_converters.ipynb | 97 ++--- .../converters/6_selectively_converting.ipynb | 45 +++ .../converters/6_selectively_converting.py | 24 ++ pyrit/converter/__init__.py | 2 + pyrit/converter/json_field_converter.py | 327 ++++++++++++++++ tests/unit/backend/test_converter_service.py | 42 ++ .../converter/test_json_field_converter.py | 358 ++++++++++++++++++ .../registry/converter_identifier_samples.py | 1 + 8 files changed, 848 insertions(+), 48 deletions(-) create mode 100644 pyrit/converter/json_field_converter.py create mode 100644 tests/unit/converter/test_json_field_converter.py diff --git a/doc/code/converters/0_converters.ipynb b/doc/code/converters/0_converters.ipynb index ef838be974..4dbf450b56 100644 --- a/doc/code/converters/0_converters.ipynb +++ b/doc/code/converters/0_converters.ipynb @@ -96,54 +96,55 @@ "52 text text IPAConverter\n", "53 text text ImagePromptStyleConverter\n", "54 text text InsertPunctuationConverter\n", - "55 text text JsonStringConverter\n", - "56 text text LLMGenericTextConverter\n", - "57 text text LeetspeakConverter\n", - "58 text text LetterBijectionConverter\n", - "59 text text LogicJailbreakConverter\n", - "60 text text MaliciousQuestionGeneratorConverter\n", - "61 text text MathObfuscationConverter\n", - "62 text text MathPromptConverter\n", - "63 text text MorseConverter\n", - "64 text text NatoConverter\n", - "65 text text NegationTrapConverter\n", - "66 text text NoiseConverter\n", - "67 text text PersuasionConverter\n", - "68 text text PinyinConverter\n", - "69 text text PolicyPuppetryConverter\n", - "70 text text PromptTemplateConverter\n", - "71 text text PuzzledConverter\n", - "72 text text ROT13Converter\n", - "73 text text RandomCapitalLettersConverter\n", - "74 text text RandomTranslationConverter\n", - "75 text text RepeatTokenConverter\n", - "76 text text RolePlayToolCallConverter\n", - "77 text text SATAMaskingConverter\n", - "78 text text ScientificTranslationConverter\n", - "79 text text SearchReplaceConverter\n", - "80 text text SelectiveTextConverter\n", - "81 text text SneakyBitsSmugglerConverter\n", - "82 text text StringJoinConverter\n", - "83 text text SuffixAppendConverter\n", - "84 text text SuperscriptConverter\n", - "85 text text TaskFramingConverter\n", - "86 text text TatweelConverter\n", - "87 text text TemplateSegmentConverter\n", - "88 text text TenseConverter\n", - "89 text text TextJailbreakConverter\n", - "90 text text TokenBijectionConverter\n", - "91 text text ToneConverter\n", - "92 text text ToxicSentenceGeneratorConverter\n", - "93 text text TranslationConverter\n", - "94 text text UnicodeConfusableConverter\n", - "95 text text UnicodeReplacementConverter\n", - "96 text text UnicodeSubstitutionConverter\n", - "97 text text UrlConverter\n", - "98 text text VariationConverter\n", - "99 text text VariationSelectorSmugglerConverter\n", - "100 text text VigenereConverter\n", - "101 text text ZalgoConverter\n", - "102 text text ZeroWidthConverter\n" + "55 text text JsonFieldConverter\n", + "56 text text JsonStringConverter\n", + "57 text text LLMGenericTextConverter\n", + "58 text text LeetspeakConverter\n", + "59 text text LetterBijectionConverter\n", + "60 text text LogicJailbreakConverter\n", + "61 text text MaliciousQuestionGeneratorConverter\n", + "62 text text MathObfuscationConverter\n", + "63 text text MathPromptConverter\n", + "64 text text MorseConverter\n", + "65 text text NatoConverter\n", + "66 text text NegationTrapConverter\n", + "67 text text NoiseConverter\n", + "68 text text PersuasionConverter\n", + "69 text text PinyinConverter\n", + "70 text text PolicyPuppetryConverter\n", + "71 text text PromptTemplateConverter\n", + "72 text text PuzzledConverter\n", + "73 text text ROT13Converter\n", + "74 text text RandomCapitalLettersConverter\n", + "75 text text RandomTranslationConverter\n", + "76 text text RepeatTokenConverter\n", + "77 text text RolePlayToolCallConverter\n", + "78 text text SATAMaskingConverter\n", + "79 text text ScientificTranslationConverter\n", + "80 text text SearchReplaceConverter\n", + "81 text text SelectiveTextConverter\n", + "82 text text SneakyBitsSmugglerConverter\n", + "83 text text StringJoinConverter\n", + "84 text text SuffixAppendConverter\n", + "85 text text SuperscriptConverter\n", + "86 text text TaskFramingConverter\n", + "87 text text TatweelConverter\n", + "88 text text TemplateSegmentConverter\n", + "89 text text TenseConverter\n", + "90 text text TextJailbreakConverter\n", + "91 text text TokenBijectionConverter\n", + "92 text text ToneConverter\n", + "93 text text ToxicSentenceGeneratorConverter\n", + "94 text text TranslationConverter\n", + "95 text text UnicodeConfusableConverter\n", + "96 text text UnicodeReplacementConverter\n", + "97 text text UnicodeSubstitutionConverter\n", + "98 text text UrlConverter\n", + "99 text text VariationConverter\n", + "100 text text VariationSelectorSmugglerConverter\n", + "101 text text VigenereConverter\n", + "102 text text ZalgoConverter\n", + "103 text text ZeroWidthConverter\n" ] } ], diff --git a/doc/code/converters/6_selectively_converting.ipynb b/doc/code/converters/6_selectively_converting.ipynb index d146655b81..53f615e43f 100644 --- a/doc/code/converters/6_selectively_converting.ipynb +++ b/doc/code/converters/6_selectively_converting.ipynb @@ -566,6 +566,51 @@ "assert mixed.output_text == \"prefix [⟪jbeq⟫] suffix\"" ] }, + { + "cell_type": "markdown", + "id": "9aaf21b2", + "metadata": {}, + "source": [ + "## 8. Convert One Field of a JSON Request\n", + "\n", + "Some targets take a JSON request, such as a decision model request with `state` and `questions`.\n", + "`JsonFieldConverter` applies a text converter to the string at one RFC 6901 JSON Pointer\n", + "(`/state`, `/messages/0/content`; `~1` and `~0` escape `/` and `~` in a key) and leaves the rest\n", + "of the request as it was, byte for byte. Markers are resolved inside that field, so they cannot\n", + "split the JSON, and markers in other fields stay in place for a later converter." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "6d001bdc", + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "{\"state\": \"UmVmdW5kIG15IOKfqm9yZGVy4p+r\", \"questions\": {\"refund\": {\"type\": \"noul\", \"instructions\": \"Is this a refund?\"}}}\n", + "{\"state\": \"Refund my b3JkZXI=\", \"questions\": {\"refund\": {\"type\": \"noul\", \"instructions\": \"Is this a refund?\"}}}\n" + ] + } + ], + "source": [ + "from pyrit.converter import JsonFieldConverter\n", + "\n", + "request = (\n", + " '{\"state\": \"Refund my ⟪order⟫\", \"questions\": {\"refund\": {\"type\": \"noul\", \"instructions\": \"Is this a refund?\"}}}'\n", + ")\n", + "json_field = JsonFieldConverter(sub_converter=Base64Converter(), json_pointer=\"/state\")\n", + "\n", + "whole_field = await json_field.convert_async(prompt=request) # type: ignore\n", + "marked_only = await json_field.convert_tokens_async(prompt=request) # type: ignore\n", + "print(whole_field.output_text)\n", + "print(marked_only.output_text)\n", + "assert whole_field.output_text == request.replace('\"Refund my ⟪order⟫\"', '\"UmVmdW5kIG15IOKfqm9yZGVy4p+r\"')\n", + "assert marked_only.output_text == request.replace('\"Refund my ⟪order⟫\"', '\"Refund my b3JkZXI=\"')" + ] + }, { "cell_type": "markdown", "id": "25", diff --git a/doc/code/converters/6_selectively_converting.py b/doc/code/converters/6_selectively_converting.py index d767977b0a..b25a388849 100644 --- a/doc/code/converters/6_selectively_converting.py +++ b/doc/code/converters/6_selectively_converting.py @@ -312,6 +312,30 @@ print(mixed.output_text) assert mixed.output_text == "prefix [⟪jbeq⟫] suffix" +# %% [markdown] +# ## 8. Convert One Field of a JSON Request +# +# Some targets take a JSON request, such as a decision model request with `state` and `questions`. +# `JsonFieldConverter` applies a text converter to the string at one RFC 6901 JSON Pointer +# (`/state`, `/messages/0/content`; `~1` and `~0` escape `/` and `~` in a key) and leaves the rest +# of the request as it was, byte for byte. Markers are resolved inside that field, so they cannot +# split the JSON, and markers in other fields stay in place for a later converter. + +# %% +from pyrit.converter import JsonFieldConverter + +request = ( + '{"state": "Refund my ⟪order⟫", "questions": {"refund": {"type": "noul", "instructions": "Is this a refund?"}}}' +) +json_field = JsonFieldConverter(sub_converter=Base64Converter(), json_pointer="/state") + +whole_field = await json_field.convert_async(prompt=request) # type: ignore +marked_only = await json_field.convert_tokens_async(prompt=request) # type: ignore +print(whole_field.output_text) +print(marked_only.output_text) +assert whole_field.output_text == request.replace('"Refund my ⟪order⟫"', '"UmVmdW5kIG15IOKfqm9yZGVy4p+r"') +assert marked_only.output_text == request.replace('"Refund my ⟪order⟫"', '"Refund my b3JkZXI="') + # %% [markdown] # ## Limits and Custom Converters # diff --git a/pyrit/converter/__init__.py b/pyrit/converter/__init__.py index cecfd7b2e0..c749d42c7d 100644 --- a/pyrit/converter/__init__.py +++ b/pyrit/converter/__init__.py @@ -70,6 +70,7 @@ from pyrit.converter.image_rotation_converter import ImageRotationConverter from pyrit.converter.insert_punctuation_converter import InsertPunctuationConverter from pyrit.converter.ipa_converter import IPAConverter + from pyrit.converter.json_field_converter import JsonFieldConverter from pyrit.converter.json_string_converter import JsonStringConverter from pyrit.converter.leetspeak_converter import LeetspeakConverter from pyrit.converter.llm_generic_text_converter import LLMGenericTextConverter @@ -202,6 +203,7 @@ "IndexSelectionStrategy": "pyrit.converter.text_selection_strategy", "InsertPunctuationConverter": "pyrit.converter.insert_punctuation_converter", "IPAConverter": "pyrit.converter.ipa_converter", + "JsonFieldConverter": "pyrit.converter.json_field_converter", "JsonStringConverter": "pyrit.converter.json_string_converter", "KeywordSelectionStrategy": "pyrit.converter.text_selection_strategy", "LeetspeakConverter": "pyrit.converter.leetspeak_converter", diff --git a/pyrit/converter/json_field_converter.py b/pyrit/converter/json_field_converter.py new file mode 100644 index 0000000000..4b414bf332 --- /dev/null +++ b/pyrit/converter/json_field_converter.py @@ -0,0 +1,327 @@ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT license. + +import json +import re +from collections.abc import Awaitable, Callable + +from pyrit.converter.converter import Converter, ConverterResult +from pyrit.models import ComponentIdentifier, PromptDataType + +_ARRAY_INDEX = re.compile(r"0|[1-9][0-9]*") +_LONE_SURROGATE = re.compile("[\ud800-\udfff]") +_DECODER = json.JSONDecoder() + + +class JsonFieldConverter(Converter): + """ + Apply another converter to one string field of a JSON request. + + Structured targets read a JSON request, such as a decision model request with ``state`` and + ``questions``. Converting the whole request would also rewrite its keys and syntax. This + wrapper converts only the string at ``json_pointer`` and writes it back as a JSON string. + Everything else in the request, including whitespace and number formatting, stays as it was. + + ``json_pointer`` follows RFC 6901: ``""`` is the whole document, ``"/state"`` is the + ``state`` key, ``"/messages/0/content"`` indexes into an array, and ``~1`` and ``~0`` + escape ``/`` and ``~`` inside a key. + + Example: + >>> from pyrit.converter import Base64Converter, JsonFieldConverter + >>> + >>> converter = JsonFieldConverter(sub_converter=Base64Converter(), json_pointer="/state") + >>> result = await converter.convert_async( + ... prompt='{"state": "hello", "questions": {"q": {"type": "noul", "instructions": "Is it a greeting?"}}}' + ... ) + >>> # Result: '{"state": "aGVsbG8=", "questions": {"q": {"type": "noul", "instructions": "Is it a greeting?"}}}' + """ + + SUPPORTED_INPUT_TYPES = ("text",) + SUPPORTED_OUTPUT_TYPES = ("text",) + + def __init__(self, *, sub_converter: Converter, json_pointer: str) -> None: + """ + Initialize the JSON field converter. + + Args: + sub_converter (Converter): The text converter to apply to the field. + json_pointer (str): The RFC 6901 JSON Pointer of the string field to convert. + + Raises: + ValueError: If the wrapped converter does not support text input and output. + ValueError: If ``json_pointer`` is not a valid JSON Pointer. + """ + super().__init__() + + if not sub_converter.input_supported("text"): + raise ValueError(f"The converter {sub_converter.__class__.__name__} does not support text input") + if not sub_converter.output_supported("text"): + raise ValueError(f"The converter {sub_converter.__class__.__name__} does not support text output") + + self._sub_converter = sub_converter + self._json_pointer = json_pointer + self._reference_tokens = self._parse_json_pointer(json_pointer) + + def _build_identifier(self) -> ComponentIdentifier: + """ + Build identifier with the field pointer and the wrapped converter. + + Returns: + ComponentIdentifier: The identifier for this converter. + """ + return self._create_identifier( + params={"json_pointer": self._json_pointer}, + sub_converter=self._sub_converter.get_identifier(), + ) + + async def convert_async(self, *, prompt: str, input_type: PromptDataType = "text") -> ConverterResult: + """ + Convert the field at ``json_pointer`` with the wrapped converter. + + Args: + prompt (str): The JSON request. + input_type (PromptDataType): The type of input data. Must be "text". + + Returns: + ConverterResult: The JSON request with the field converted. + + Raises: + ValueError: If the input type is not "text". + ValueError: If the prompt is not JSON or ``json_pointer`` does not select a string in it. + ValueError: If the wrapped converter does not return text. + """ + if not self.input_supported(input_type): + raise ValueError(f"JsonFieldConverter only supports text input, got {input_type}") + + async def convert_field_async(text: str) -> ConverterResult: + return await self._sub_converter.convert_async(prompt=text, input_type="text") + + return await self._convert_field_async(prompt=prompt, convert_text_async=convert_field_async) + + async def convert_tokens_async( + self, + *, + prompt: str, + input_type: PromptDataType = "text", + start_token: str = "⟪", + end_token: str = "⟫", + keep_tokens: bool = False, + ) -> ConverterResult: + """ + Convert marked regions of the field, or the whole field when it has no markers. + + Attack converter pipelines call this method. Markers are resolved inside the field's + decoded text, so a marked region cannot split the JSON. Markers in other fields are left + in place for a later converter in the stack. + + Args: + prompt (str): The JSON request. + input_type (PromptDataType): The type of input data. Must be "text". + start_token (str): The token that starts a region to convert. Defaults to "⟪". + end_token (str): The token that ends a region to convert. Defaults to "⟫". + keep_tokens (bool): Retain each selected marker pair around its converted text. + Defaults to False. + + Returns: + ConverterResult: The JSON request with the field converted. + + Raises: + ValueError: If the input type is not "text". + ValueError: If the prompt is not JSON or ``json_pointer`` does not select a string in it. + ValueError: If the field's markers are malformed or the wrapped converter does not return text. + """ + if not self.input_supported(input_type): + raise ValueError(f"JsonFieldConverter only supports text input, got {input_type}") + + async def convert_field_async(text: str) -> ConverterResult: + return await self._sub_converter.convert_tokens_async( + prompt=text, + input_type="text", + start_token=start_token, + end_token=end_token, + keep_tokens=keep_tokens, + ) + + return await self._convert_field_async(prompt=prompt, convert_text_async=convert_field_async) + + async def _convert_field_async( + self, *, prompt: str, convert_text_async: Callable[[str], Awaitable[ConverterResult]] + ) -> ConverterResult: + """ + Find the field, convert its text, and splice it back as a JSON string. + + Args: + prompt (str): The JSON request. + convert_text_async (Callable[[str], Awaitable[ConverterResult]]): Converts the field text. + + Returns: + ConverterResult: The JSON request with the field converted. + + Raises: + ValueError: If the wrapped converter does not return text. + """ + text, start, end = self._find_string_field(prompt) + result = await convert_text_async(text) + if result.output_type != "text": + raise ValueError(f"JsonFieldConverter requires text output, but received {result.output_type}.") + + # Splicing instead of re-serializing keeps the rest of the request byte for byte, so + # number formatting, duplicate keys elsewhere, and whitespace reach the target unchanged. + converted = json.dumps(result.output_text, ensure_ascii=False) + # A lone surrogate is valid as a JSON escape but cannot be encoded as UTF-8 when stored or sent. + converted = _LONE_SURROGATE.sub(lambda match: f"\\u{ord(match.group()):04x}", converted) + return ConverterResult(output_text=f"{prompt[:start]}{converted}{prompt[end:]}", output_type="text") + + def _find_string_field(self, prompt: str) -> tuple[str, int, int]: + """ + Locate the string the pointer selects. + + Args: + prompt (str): The JSON request. + + Returns: + tuple[str, int, int]: The decoded string and the start and end offsets of its JSON literal. + + Raises: + ValueError: If the prompt is not JSON, the pointer does not resolve, a key on the + path is duplicated, or the selected value is not a string. + """ + try: + json.loads(prompt) + except (json.JSONDecodeError, RecursionError) as exc: + raise ValueError(f"JsonFieldConverter requires a JSON document: {exc}") from exc + + # The document is valid JSON, so the walk below only has to find offsets, not validate. + position = _skip_whitespace(prompt, position=0) + location = "" + for token in self._reference_tokens: + if prompt[position] == "{": + position = _find_member(prompt, position=position, token=token, location=location) + elif prompt[position] == "[": + position = _find_element(prompt, position=position, token=token, location=location) + else: + raise ValueError( + f"JSON Pointer {self._json_pointer!r} cannot resolve: the value at {location!r} " + "is not an object or array." + ) + location = f"{location}/{_escape_reference_token(token)}" + + if prompt[position] != '"': + value, _ = _DECODER.raw_decode(prompt, position) + raise ValueError( + f"JSON Pointer {self._json_pointer!r} selects {_describe_json_value(value)}, not a string." + ) + text, end = _DECODER.raw_decode(prompt, position) + return str(text), position, end + + @staticmethod + def _parse_json_pointer(json_pointer: str) -> list[str]: + """ + Split an RFC 6901 JSON Pointer into its unescaped reference tokens. + + Args: + json_pointer (str): The pointer. + + Returns: + list[str]: The reference tokens, empty for the whole document. + + Raises: + ValueError: If the pointer is nonempty without a leading ``/``, or contains ``~`` + not followed by ``0`` or ``1``. + """ + if not json_pointer: + return [] + if not json_pointer.startswith("/"): + raise ValueError(f"json_pointer must be empty or start with '/', got {json_pointer!r}.") + if re.search(r"~(?![01])", json_pointer): + raise ValueError(f"json_pointer {json_pointer!r} has '~' not followed by '0' or '1'.") + return [token.replace("~1", "/").replace("~0", "~") for token in json_pointer[1:].split("/")] + + +def _escape_reference_token(token: str) -> str: + return token.replace("~", "~0").replace("/", "~1") + + +def _skip_whitespace(document: str, *, position: int) -> int: + while position < len(document) and document[position] in " \t\n\r": + position += 1 + return position + + +def _describe_json_value(value: object) -> str: + if isinstance(value, dict): + return "an object" + if isinstance(value, list): + return "an array" + if isinstance(value, bool): + return "a boolean" + if value is None: + return "null" + return "a number" + + +def _find_member(document: str, *, position: int, token: str, location: str) -> int: + """ + Return the offset of the value under ``token`` in the object starting at ``position``. + + Args: + document (str): A valid JSON document. + position (int): The offset of the object's ``{``. + token (str): The key to find. + location (str): The pointer to the object, for error messages. + + Returns: + int: The offset of the member's value. + + Raises: + ValueError: If the key is missing or appears more than once. + """ + found: int | None = None + position = _skip_whitespace(document, position=position + 1) + while document[position] != "}": + key, position = _DECODER.raw_decode(document, position) + position = _skip_whitespace(document, position=_skip_whitespace(document, position=position) + 1) + if key == token: + if found is not None: + # Parsers disagree on which duplicate wins, so the field to convert is ambiguous. + raise ValueError(f"The object at {location!r} has the key {token!r} more than once.") + found = position + _, position = _DECODER.raw_decode(document, position) + position = _skip_whitespace(document, position=position) + if document[position] == ",": + position = _skip_whitespace(document, position=position + 1) + if found is None: + raise ValueError(f"The object at {location!r} has no key {token!r}.") + return found + + +def _find_element(document: str, *, position: int, token: str, location: str) -> int: + """ + Return the offset of the element at index ``token`` in the array starting at ``position``. + + Args: + document (str): A valid JSON document. + position (int): The offset of the array's ``[``. + token (str): The index to find, in decimal without leading zeros. + location (str): The pointer to the array, for error messages. + + Returns: + int: The offset of the element. + + Raises: + ValueError: If the token is not an array index or the index is out of range. + """ + if not _ARRAY_INDEX.fullmatch(token): + raise ValueError(f"The value at {location!r} is an array, and {token!r} is not an array index.") + index = int(token) + position = _skip_whitespace(document, position=position + 1) + count = 0 + while document[position] != "]": + if count == index: + return position + _, position = _DECODER.raw_decode(document, position) + position = _skip_whitespace(document, position=position) + if document[position] == ",": + position = _skip_whitespace(document, position=position + 1) + count += 1 + raise ValueError(f"The array at {location!r} has {count} elements, so index {index} is out of range.") diff --git a/tests/unit/backend/test_converter_service.py b/tests/unit/backend/test_converter_service.py index fb0937cf29..881719decf 100644 --- a/tests/unit/backend/test_converter_service.py +++ b/tests/unit/backend/test_converter_service.py @@ -1736,6 +1736,47 @@ async def test_preview_conversion_nested_remaining_markers_async(self, *, upload ) assert result.converted_value == "keep ⟪dGVzdA==⟫ and ⟪dGVzdDI=⟫" + async def test_preview_conversion_runs_json_field_converter_built_from_api_params_async( + self, *, upload_service: ConverterService + ) -> None: + await upload_service.create_converter_async(request=CreateConverterRequest(name="b64", type="Base64Converter")) + created = await upload_service.create_converter_async( + request=CreateConverterRequest( + name="state_b64", + type="JsonFieldConverter", + params={"sub_converter": "b64", "json_pointer": "/state"}, + ) + ) + + result = await upload_service.preview_conversion_async( + request=ConverterPreviewRequest( + original_value='{"state": "hello", "n": 1.10}', + original_value_data_type="text", + converter_ids=[created.converter_id], + ) + ) + + assert result.converted_value == '{"state": "aGVsbG8=", "n": 1.10}' + + @pytest.mark.parametrize( + "params", + [ + {"sub_converter": "missing", "json_pointer": "/state"}, + {"sub_converter": "b64", "json_pointer": "state"}, + ], + ) + async def test_create_json_field_converter_rejects_invalid_api_params_async( + self, *, upload_service: ConverterService, params: dict[str, str] + ) -> None: + await upload_service.create_converter_async(request=CreateConverterRequest(name="b64", type="Base64Converter")) + + with pytest.raises(ValueError): + await upload_service.create_converter_async( + request=CreateConverterRequest(name="state_b64", type="JsonFieldConverter", params=params) + ) + + assert await upload_service.get_converter_async(converter_id="state_b64") is None + @pytest.mark.parametrize("preserve_tokens", [False, True]) async def test_preview_conversion_token_selection_matches_direct_async( self, *, upload_service: ConverterService, preserve_tokens: bool @@ -2152,6 +2193,7 @@ def _try_instantiate_converter(converter_name: str): "PersuasionConverter": {"persuasion_technique": "logical_appeal"}, "PromptTemplateConverter": {"template": "Test {{ prompt }}"}, "ImagePromptStyleConverter": {"filter_name": "gritty_documentary"}, + "JsonFieldConverter": {"json_pointer": "/state"}, "VigenereConverter": {"key": "testvalue"}, "GridCompositeConverter": {"innocuous_images": ["a.png", "b.png", "c.png"]}, } diff --git a/tests/unit/converter/test_json_field_converter.py b/tests/unit/converter/test_json_field_converter.py new file mode 100644 index 0000000000..50d643d3e2 --- /dev/null +++ b/tests/unit/converter/test_json_field_converter.py @@ -0,0 +1,358 @@ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT license. + +import json +import re +from unittest.mock import AsyncMock, MagicMock, patch + +import pytest + +from pyrit.common.random_context import configure_random_seed +from pyrit.converter import ( + Base64Converter, + Converter, + ConverterResult, + JsonFieldConverter, + RandomCapitalLettersConverter, + ROT13Converter, + SelectiveTextConverter, + TokenSelectionStrategy, +) +from pyrit.memory import MemoryInterface +from pyrit.models import Message, PromptDataType +from pyrit.prompt_normalizer import ConverterConfiguration, PromptNormalizer + + +class _UpperConverter(Converter): + SUPPORTED_INPUT_TYPES = ("text",) + SUPPORTED_OUTPUT_TYPES = ("text",) + + async def convert_async(self, *, prompt: str, input_type: PromptDataType = "text") -> ConverterResult: + return ConverterResult(output_text=prompt.upper(), output_type="text") + + +class _ImageConverter(Converter): + SUPPORTED_INPUT_TYPES = ("text",) + SUPPORTED_OUTPUT_TYPES = ("text", "image_path") + + async def convert_async(self, *, prompt: str, input_type: PromptDataType = "text") -> ConverterResult: + return ConverterResult(output_text="image.png", output_type="image_path") + + +_REQUEST = '{"state": "hello", "questions": {"q": {"type": "noul", "instructions": "Is it a greeting?"}}}' + + +async def _convert(prompt: str, json_pointer: str, sub_converter: Converter | None = None) -> str: + converter = JsonFieldConverter(sub_converter=sub_converter or _UpperConverter(), json_pointer=json_pointer) + result = await converter.convert_async(prompt=prompt) + assert result.output_type == "text" + return result.output_text + + +async def test_converts_only_the_selected_field(): + result = await _convert(_REQUEST, "/state", Base64Converter()) + + assert result == _REQUEST.replace('"hello"', '"aGVsbG8="') + + +async def test_keeps_the_rest_of_the_document_byte_for_byte(): + # Re-serializing would turn 1e400 into Infinity, 1.10 into 1.1, drop the duplicate key, and + # reflow the whitespace. The splice keeps all of them. + prompt = ( + '{\n "n": [1.10, 1E5, -0.0, 1e400, 123456789012345678901234567890, NaN],\n' + ' "dup": 1, "dup": 2,\n "state" : "hello",\n "tail": "\\u00e9"\n}' + ) + + result = await _convert(prompt, "/state") + + assert result == prompt.replace('"hello"', '"HELLO"') + + +@pytest.mark.parametrize( + ("prompt", "json_pointer", "expected"), + [ + ('{"a": {"b": {"c": "x"}}}', "/a/b/c", '{"a": {"b": {"c": "X"}}}'), + ('{"m": ["x", "y", "z"]}', "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/m/2", '{"m": ["x", "y", "Z"]}'), + ('[{"content": "x"}, {"content": "y"}]', "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/1/content", '[{"content": "x"}, {"content": "Y"}]'), + ('{"a/b": "x", "a": {"b": "y"}}', "/a~1b", '{"a/b": "X", "a": {"b": "y"}}'), + ('{"~1": "x", "/": "y"}', "/~01", '{"~1": "X", "/": "y"}'), + ('{"": "x", "a": "y"}', "/", '{"": "X", "a": "y"}'), + ('{"\\u0073tate": "x"}', "/state", '{"\\u0073tate": "X"}'), + (' "x" ', "", ' "X" '), + ('{"a": "x", "b": {"a": "y"}}', "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/b/a", '{"a": "x", "b": {"a": "Y"}}'), + ], +) +async def test_resolves_json_pointers(prompt: str, json_pointer: str, expected: str): + assert await _convert(prompt, json_pointer) == expected + + +@pytest.mark.parametrize( + ("field", "converted"), + [ + ('"say \\"hi\\""', 'SAY "HI"'), + ('"a\\\\b\\nc"', "A\\B\nC"), + ('"\\u00e9t\\u00e9 \\ud83d\\ude00"', "ÉTÉ 😀"), + ('""', ""), + ], +) +async def test_decodes_the_field_and_writes_valid_json(field: str, converted: str): + result = await _convert(f'{{"state": {field}, "k": 1}}', "/state") + + assert json.loads(result) == {"state": converted, "k": 1} + + +async def test_keeps_non_ascii_output_readable(): + result = await _convert('{"state": "e"}', "/state", ROT13Converter()) + + assert result == '{"state": "r"}' + homoglyphs = await _convert('{"state": "x"}', "/state", _HomoglyphConverter()) + assert homoglyphs == '{"state": "Ⓗ"}' + + +@pytest.mark.parametrize( + ("field", "expected"), + [ + ('"\\ud800"', '"\\ud800"'), + ('"a\\udc00b"', '"A\\udc00B"'), + ('"\\\\\\ud800"', '"\\\\\\ud800"'), + ('"\\ud83d\\ude00"', '"😀"'), + ], +) +async def test_writes_lone_surrogates_as_escapes(field: str, expected: str): + result = await _convert(f'{{"state": {field}}}', "/state") + + assert result == f'{{"state": {expected}}}' + result.encode("utf-8") + + +class _HomoglyphConverter(Converter): + SUPPORTED_INPUT_TYPES = ("text",) + SUPPORTED_OUTPUT_TYPES = ("text",) + + async def convert_async(self, *, prompt: str, input_type: PromptDataType = "text") -> ConverterResult: + return ConverterResult(output_text="Ⓗ", output_type="text") + + +@pytest.mark.parametrize( + ("prompt", "json_pointer", "message"), + [ + ("", "/state", "requires a JSON document"), + ("not json", "/state", "requires a JSON document"), + ('{"state": "x"', "/state", "requires a JSON document"), + ('{"state": "x"} trailing', "/state", "requires a JSON document"), + ("[" * 100_000 + "]" * 100_000, "/0", "requires a JSON document"), + ('{"other": "x"}', "/state", "The object at '' has no key 'state'"), + ("{}", "/state", "has no key 'state'"), + ('{"a": {}}', "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/a/b", "The object at '/a' has no key 'b'"), + ('{"state": "x", "state": "y"}', "/state", "has the key 'state' more than once"), + ('{"a": 1}', "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/a/b", "the value at '/a' is not an object or array"), + ('{"a": "x"}', "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/a/0", "the value at '/a' is not an object or array"), + ('{"m": ["x"]}', "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/m/1", "has 1 elements, so index 1 is out of range"), + ('{"m": []}', "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/m/0", "has 0 elements, so index 0 is out of range"), + ('{"m": ["x"]}', "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/m/-", "'-' is not an array index"), + ('{"m": ["x", "y"]}', "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/m/01", "'01' is not an array index"), + ('{"m": ["x"]}', "/m/+0", "'+0' is not an array index"), + ('{"m": ["x"]}', "/m/", "'' is not an array index"), + ('{"m": ["x"]}', "/m/\u0660", "is not an array index"), + ('{"state": {"text": "x"}}', "/state", "selects an object, not a string"), + ('{"state": ["x"]}', "/state", "selects an array, not a string"), + ('{"state": 1}', "/state", "selects a number, not a string"), + ('{"state": true}', "/state", "selects a boolean, not a string"), + ('{"state": null}', "/state", "selects null, not a string"), + ('{"state": "x"}', "", "selects an object, not a string"), + ], +) +async def test_rejects_documents_the_pointer_cannot_convert(prompt: str, json_pointer: str, message: str): + sub_converter = AsyncMock(spec=_UpperConverter()) + converter = JsonFieldConverter(sub_converter=sub_converter, json_pointer=json_pointer) + + with pytest.raises(ValueError, match=re.escape(message)): + await converter.convert_async(prompt=prompt) + sub_converter.convert_async.assert_not_called() + + +async def test_reports_the_escaped_path_of_a_missing_key(): + converter = JsonFieldConverter(sub_converter=_UpperConverter(), json_pointer="/a~1b/c~0d/e") + + with pytest.raises(ValueError, match=r"The object at '/a~1b/c~0d' has no key 'e'"): + await converter.convert_async(prompt='{"a/b": {"c~d": {}}}') + + +@pytest.mark.parametrize("json_pointer", ["state", "#/state", "/~2", "/a~", "/~/b"]) +def test_init_rejects_invalid_json_pointers(json_pointer: str): + with pytest.raises(ValueError, match="json_pointer"): + JsonFieldConverter(sub_converter=_UpperConverter(), json_pointer=json_pointer) + + +def test_init_rejects_sub_converter_without_text_input(): + sub_converter = MagicMock(spec=Converter) + sub_converter.input_supported.return_value = False + + with pytest.raises(ValueError, match="does not support text input"): + JsonFieldConverter(sub_converter=sub_converter, json_pointer="/state") + + +def test_init_rejects_sub_converter_without_text_output(): + sub_converter = MagicMock(spec=Converter) + sub_converter.input_supported.return_value = True + sub_converter.output_supported.return_value = False + + with pytest.raises(ValueError, match="does not support text output"): + JsonFieldConverter(sub_converter=sub_converter, json_pointer="/state") + + +async def test_rejects_non_text_input_type(): + converter = JsonFieldConverter(sub_converter=_UpperConverter(), json_pointer="/state") + + with pytest.raises(ValueError, match="only supports text input"): + await converter.convert_async(prompt=_REQUEST, input_type="image_path") + with pytest.raises(ValueError, match="only supports text input"): + await converter.convert_tokens_async(prompt=_REQUEST, input_type="image_path") + + +async def test_rejects_non_text_sub_converter_output(): + converter = JsonFieldConverter(sub_converter=_ImageConverter(), json_pointer="/state") + + with pytest.raises(ValueError, match="requires text output, but received image_path"): + await converter.convert_async(prompt=_REQUEST) + with pytest.raises(ValueError, match="requires text output, but received image_path"): + await converter.convert_tokens_async(prompt=_REQUEST) + + +async def test_sub_converter_errors_propagate(): + sub_converter = _UpperConverter() + converter = JsonFieldConverter(sub_converter=sub_converter, json_pointer="/state") + + with ( + patch.object(sub_converter, "convert_async", AsyncMock(side_effect=RuntimeError("boom"))), + pytest.raises(RuntimeError, match="boom"), + ): + await converter.convert_async(prompt=_REQUEST) + + +@pytest.mark.parametrize( + ("field", "keep_tokens", "expected_state"), + [ + ('"a ⟪b⟫ c"', False, "a Yg== c"), + ('"a \\u27eab\\u27eb c"', False, "a Yg== c"), + ('"a ⟪b⟫ c"', True, "a ⟪Yg==⟫ c"), + ('"⟪⟪b⟫⟫ ⟪c⟫"', False, "⟪Yg==⟫ Yw=="), + ('"abc"', False, "YWJj"), + ('"abc"', True, "⟪YWJj⟫"), + ], +) +async def test_convert_tokens_async_resolves_markers_inside_the_field( + field: str, keep_tokens: bool, expected_state: str +): + converter = JsonFieldConverter(sub_converter=Base64Converter(), json_pointer="/state") + + result = await converter.convert_tokens_async(prompt=f'{{"state": {field}, "n": 1.10}}', keep_tokens=keep_tokens) + + assert result.output_type == "text" + assert json.loads(result.output_text) == {"state": expected_state, "n": 1.1} + assert result.output_text.endswith(', "n": 1.10}') + + +async def test_convert_tokens_async_leaves_markers_in_other_fields(): + converter = JsonFieldConverter(sub_converter=Base64Converter(), json_pointer="/state") + prompt = '{"⟪key⟫": "⟪x⟫", "state": "abc", "other": "keep ⟪this⟫"}' + + result = await converter.convert_tokens_async(prompt=prompt) + + assert result.output_text == prompt.replace('"abc"', '"YWJj"') + + +async def test_convert_tokens_async_rejects_malformed_markers_in_the_field(): + converter = JsonFieldConverter(sub_converter=Base64Converter(), json_pointer="/state") + + with pytest.raises(ValueError, match="Unmatched start token"): + await converter.convert_tokens_async(prompt='{"state": "a ⟪b"}') + + +async def test_convert_tokens_async_uses_custom_tokens(): + converter = JsonFieldConverter(sub_converter=Base64Converter(), json_pointer="/state") + + result = await converter.convert_tokens_async(prompt='{"state": "a [[b]] ⟪c⟫"}', start_token="[[", end_token="]]") + + assert json.loads(result.output_text) == {"state": "a Yg== ⟪c⟫"} + + +async def test_convert_tokens_async_passes_markers_to_a_selective_sub_converter(): + sub_converter = SelectiveTextConverter( + sub_converter=Base64Converter(), selection_strategy=TokenSelectionStrategy(), preserve_tokens=True + ) + converter = JsonFieldConverter(sub_converter=sub_converter, json_pointer="/state") + + result = await converter.convert_tokens_async(prompt='{"state": "a ⟪b⟫ c"}') + + assert json.loads(result.output_text) == {"state": "a ⟪Yg==⟫ c"} + + +async def test_stacked_converters_convert_their_own_fields(patch_central_database: MemoryInterface): + prompt = '{"state": "a ⟪b⟫", "note": "⟪c⟫ d", "questions": {}}' + message = Message.from_prompt(prompt=prompt, role="user") + converters = [ + JsonFieldConverter(sub_converter=Base64Converter(), json_pointer="/state"), + JsonFieldConverter(sub_converter=ROT13Converter(), json_pointer="/note"), + ] + + await PromptNormalizer().convert_values_async( + converter_configurations=[ConverterConfiguration(converters=converters)], message=message + ) + + assert message.message_pieces[0].converted_value == '{"state": "a Yg==", "note": "p d", "questions": {}}' + assert message.message_pieces[0].original_value == prompt + + +async def test_wrapped_stochastic_converter_follows_the_configured_seed(): + converter = JsonFieldConverter(sub_converter=RandomCapitalLettersConverter(percentage=50.0), json_pointer="/state") + prompt = '{"state": "abcdefghijklmnopqrstuvwxyz"}' + + configure_random_seed(seed=3) + try: + first = await converter.convert_async(prompt=prompt) + second = await converter.convert_async(prompt=prompt) + configure_random_seed(seed=4) + other = await converter.convert_async(prompt=prompt) + finally: + configure_random_seed(seed=None) + + assert first.output_text == second.output_text + assert first.output_text != other.output_text + + +def test_identifier_includes_pointer_and_sub_converter(): + identifier = JsonFieldConverter(sub_converter=Base64Converter(), json_pointer="/state").get_identifier() + + assert identifier.params["json_pointer"] == "/state" + assert ( + identifier.hash + != JsonFieldConverter(sub_converter=Base64Converter(), json_pointer="/note").get_identifier().hash + ) + assert ( + identifier.hash + != JsonFieldConverter(sub_converter=ROT13Converter(), json_pointer="/state").get_identifier().hash + ) + + +async def test_output_reaches_the_decision_sdk_as_a_valid_request(patch_central_database: MemoryInterface): + litellm = pytest.importorskip("litellm") + from litellm.types.decisions import DecisionsResponse + + from pyrit.prompt_target import LiteLLMDecisionTarget + + sdk = MagicMock(spec=litellm) + sdk.asystemone = None + sdk.adecisions = AsyncMock( + return_value=DecisionsResponse.model_validate({"answers": {"q": {"type": "noul", "noul": 0.2}}}) + ) + converted = await JsonFieldConverter(sub_converter=Base64Converter(), json_pointer="/state").convert_async( + prompt=_REQUEST + ) + + with patch.object(LiteLLMDecisionTarget, "_import_litellm", return_value=sdk): + target = LiteLLMDecisionTarget(model_name="provider/decision-model", api_key="test-api-key") + await target.send_prompt_async(message=Message.from_prompt(prompt=converted.output_text, role="user")) + + assert sdk.adecisions.call_args.kwargs["state"] == "aGVsbG8=" + assert sdk.adecisions.call_args.kwargs["questions"] == json.loads(_REQUEST)["questions"] diff --git a/tests/unit/registry/converter_identifier_samples.py b/tests/unit/registry/converter_identifier_samples.py index 117d61e2ee..98ac0b946e 100644 --- a/tests/unit/registry/converter_identifier_samples.py +++ b/tests/unit/registry/converter_identifier_samples.py @@ -308,6 +308,7 @@ def make_samples(folder: Path) -> dict[str, tuple[Any, ...]]: SeedPrompt(value="Second {{ prompt }}", parameters=["prompt"]), ), "LLMGenericTextConverter.system_prompt_template": (SeedPrompt(value="First"), SeedPrompt(value="Second")), + "JsonFieldConverter.json_pointer": ("/state", "/note", "", "/a~1b"), "PuzzledConverter.essential_words": (["value", "valuex"], ["valuex", "valuex"], ["value", "valuexy"]), "TranslationConverter.language": ("first", "second", f"{LONG_TEXT}a", f"{LONG_TEXT}b"), "TranslationConverter.prompt_template": ( From d28a072b8fc676ab8400a9d7f0fdce28a96acf73 Mon Sep 17 00:00:00 2001 From: Dev3 ^~^ Date: Wed, 18 Nov 2026 23:05:25 +0530 Subject: [PATCH 2/2] FIX: Match seeded JsonFieldConverter results across entry points --- pyrit/converter/json_field_converter.py | 5 +++ .../converter/test_json_field_converter.py | 39 ++++++++++++++++++- 2 files changed, 43 insertions(+), 1 deletion(-) diff --git a/pyrit/converter/json_field_converter.py b/pyrit/converter/json_field_converter.py index 4b414bf332..99f33dcd09 100644 --- a/pyrit/converter/json_field_converter.py +++ b/pyrit/converter/json_field_converter.py @@ -62,6 +62,11 @@ def __init__(self, *, sub_converter: Converter, json_pointer: str) -> None: self._json_pointer = json_pointer self._reference_tokens = self._parse_json_pointer(json_pointer) + def _is_conversion_dispatch(self, prompt: str) -> bool: + # The wrapped converter owns the randomness, so both entry points must reach it in the same scope. + owner = next(cls for cls in type(self).__mro__ if "convert_async" in cls.__dict__) + return owner is JsonFieldConverter + def _build_identifier(self) -> ComponentIdentifier: """ Build identifier with the field pointer and the wrapped converter. diff --git a/tests/unit/converter/test_json_field_converter.py b/tests/unit/converter/test_json_field_converter.py index 50d643d3e2..9b8912d02d 100644 --- a/tests/unit/converter/test_json_field_converter.py +++ b/tests/unit/converter/test_json_field_converter.py @@ -140,7 +140,6 @@ async def convert_async(self, *, prompt: str, input_type: PromptDataType = "text ("not json", "/state", "requires a JSON document"), ('{"state": "x"', "/state", "requires a JSON document"), ('{"state": "x"} trailing', "/state", "requires a JSON document"), - ("[" * 100_000 + "]" * 100_000, "/0", "requires a JSON document"), ('{"other": "x"}', "/state", "The object at '' has no key 'state'"), ("{}", "/state", "has no key 'state'"), ('{"a": {}}', "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/a/b", "The object at '/a' has no key 'b'"), @@ -171,6 +170,16 @@ async def test_rejects_documents_the_pointer_cannot_convert(prompt: str, json_po sub_converter.convert_async.assert_not_called() +async def test_rejects_documents_too_deep_to_parse(): + converter = JsonFieldConverter(sub_converter=_UpperConverter(), json_pointer="/state") + + with ( + patch("pyrit.converter.json_field_converter.json.loads", side_effect=RecursionError("too deep")), + pytest.raises(ValueError, match="requires a JSON document: too deep"), + ): + await converter.convert_async(prompt=_REQUEST) + + async def test_reports_the_escaped_path_of_a_missing_key(): converter = JsonFieldConverter(sub_converter=_UpperConverter(), json_pointer="/a~1b/c~0d/e") @@ -321,6 +330,34 @@ async def test_wrapped_stochastic_converter_follows_the_configured_seed(): assert first.output_text != other.output_text +@pytest.mark.parametrize("seed", range(5)) +async def test_both_entry_points_give_the_same_seeded_result(seed: int): + converter = JsonFieldConverter(sub_converter=RandomCapitalLettersConverter(percentage=50.0), json_pointer="/state") + prompt = '{"state": "abcdefghijklmnopqrstuvwxyz"}' + + try: + configure_random_seed(seed=seed) + direct = await converter.convert_async(prompt=prompt) + configure_random_seed(seed=seed) + pipeline = await converter.convert_tokens_async(prompt=prompt) + finally: + configure_random_seed(seed=None) + + assert direct.output_text == pipeline.output_text + + +def test_subclass_overriding_convert_async_keeps_its_own_random_scope(): + class _Subclass(JsonFieldConverter): + async def convert_async(self, *, prompt: str, input_type: PromptDataType = "text") -> ConverterResult: + return await super().convert_async(prompt=prompt, input_type=input_type) + + native = JsonFieldConverter(sub_converter=_UpperConverter(), json_pointer="/state") + subclass = _Subclass(sub_converter=_UpperConverter(), json_pointer="/state") + + assert native._is_conversion_dispatch(_REQUEST) is True + assert subclass._is_conversion_dispatch(_REQUEST) is False + + def test_identifier_includes_pointer_and_sub_converter(): identifier = JsonFieldConverter(sub_converter=Base64Converter(), json_pointer="/state").get_identifier()