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
7 changes: 0 additions & 7 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -333,10 +333,7 @@ include = [
"pyrit/cli/pyrit_scan.py",
"pyrit/common/cli_helpers.py",
"pyrit/common/yaml_loadable.py",
"pyrit/converter/decomposition_converter.py",
"pyrit/embedding/openai_text_embedding.py",
"pyrit/executor/attack/multi_turn/tree_of_attacks.py",
"pyrit/executor/attack/single_turn/many_shot_jailbreak.py",
"pyrit/executor/promptgen/gcg/attack/base/attack_manager.py",
"pyrit/executor/promptgen/gcg/attack/gcg/candidate_proposer.py",
"pyrit/executor/promptgen/gcg/attack/gcg/gcg_attack.py",
Expand All @@ -350,8 +347,6 @@ include = [
"pyrit/models/parameter.py",
"pyrit/models/score/observation.py",
"pyrit/models/score/scorable.py",
"pyrit/prompt_normalizer/json_retry.py",
"pyrit/prompt_normalizer/prompt_normalizer.py",
"pyrit/prompt_target/azure_blob_storage_target.py",
"pyrit/prompt_target/common/discover_target_capabilities.py",
"pyrit/prompt_target/openai/openai_error_handling.py",
Expand All @@ -361,8 +356,6 @@ include = [
"pyrit/registry/registry_recipe_restore.py",
"pyrit/registry/registry_recipe_rules.py",
"pyrit/registry/registry_recipe_save.py",
"pyrit/scenario/core/attack_technique_factory.py",
"pyrit/scenario/scenarios/foundry/assert_policy.py",
"pyrit/score/float_scale/local_violence_classifier_scorer.py",
"pyrit/score/llm_scoring.py",
"pyrit/score/observation/otel_execution_trace_source.py",
Expand Down
6 changes: 3 additions & 3 deletions pyrit/converter/decomposition_converter.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@
import re
import uuid
from collections import Counter
from typing import Any
from typing import Any, cast

from pyrit.common import REQUIRED_VALUE, apply_defaults
from pyrit.common.path import CONVERTER_SEED_PROMPT_PATH
Expand Down Expand Up @@ -73,8 +73,8 @@ def _tokens(text: str) -> list[str]:
Returns:
list[str]: The lowercase word tokens.
"""
tokens: list[str] = re.findall(r"\w+", text.lower(), flags=re.UNICODE)
return tokens
# A pattern without groups makes findall return the matched strings.
return cast("list[str]", re.findall(r"\w+", text.lower(), flags=re.UNICODE))


def _token_recall(source: list[str], *, got: list[str]) -> float:
Expand Down
2 changes: 1 addition & 1 deletion pyrit/exceptions/exception_classes.py
Original file line number Diff line number Diff line change
Expand Up @@ -428,7 +428,7 @@ def pyrit_target_retry(func: Callable[..., Any]) -> Callable[..., Any]:
)(func)


def pyrit_json_retry(func: Callable[..., Any]) -> Callable[..., Any]:
def pyrit_json_retry(func: Callable[_RetryParams, _RetryResult]) -> Callable[_RetryParams, _RetryResult]:
"""
Apply retry logic to a function.

Expand Down
11 changes: 9 additions & 2 deletions pyrit/executor/attack/multi_turn/tree_of_attacks.py
Original file line number Diff line number Diff line change
Expand Up @@ -303,8 +303,15 @@ class TAPAttackResult(AttackResult):

@property
def tree_visualization(self) -> Tree | None:
"""The tree visualization from metadata."""
tree: Tree | None = self.metadata.get("tree_visualization")
"""
The tree visualization from metadata.

Raises:
TypeError: If the stored visualization is neither a tree nor None.
"""
tree = self.metadata.get("tree_visualization")
if tree is not None and not isinstance(tree, Tree):
raise TypeError("tree_visualization must be a Tree or None")
return tree

@tree_visualization.setter
Expand Down
6 changes: 3 additions & 3 deletions pyrit/executor/attack/single_turn/many_shot_jailbreak.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@

import json
import logging
from typing import Any
from typing import Any, cast

from pyrit.common import REQUIRED_VALUE, apply_defaults
from pyrit.common.path import DATASETS_PATH, JAILBREAK_TEMPLATES_PATH
Expand Down Expand Up @@ -32,8 +32,8 @@ def load_many_shot_jailbreaking_dataset() -> list[dict[str, str]]:
list[dict[str, str]]: A list of many-shot jailbreaking examples.
"""
with open(_MANY_SHOT_EXAMPLES_PATH, encoding="utf-8") as f:
data: list[dict[str, str]] = json.load(f)
return data
# The dataset ships with the package as a list of user/assistant string pairs.
return cast("list[dict[str, str]]", json.load(f))


class ManyShotJailbreakAttack(PromptSendingAttack):
Expand Down
3 changes: 1 addition & 2 deletions pyrit/prompt_normalizer/json_retry.py
Original file line number Diff line number Diff line change
Expand Up @@ -84,5 +84,4 @@ async def _attempt_async() -> T:
on_response(response)
return parse(response)

result: T = await _attempt_async()
return result
return await _attempt_async()
7 changes: 4 additions & 3 deletions pyrit/prompt_normalizer/prompt_normalizer.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@
from contextvars import copy_context
from functools import partial
from pathlib import Path
from typing import Any, TypeVar
from typing import Any, TypeVar, cast
from uuid import uuid4

from pyrit.common.attack_result_scope import get_current_attack_result_id
Expand Down Expand Up @@ -331,15 +331,16 @@ async def send_prompt_batch_to_target_async(
"send_context",
]

responses: list[Message] = await batch_task_async(
responses = await batch_task_async(
prompt_target=target,
batch_size=batch_size,
items_to_batch=batch_items,
task_func=self.send_prompt_async,
task_arguments=batch_item_keys,
target=target,
)
return responses
# Each batch result is the Message returned by send_prompt_async.
return cast("list[Message]", responses)

async def convert_values_async(
self,
Expand Down
12 changes: 11 additions & 1 deletion pyrit/scenario/core/attack_technique_factory.py
Original file line number Diff line number Diff line change
Expand Up @@ -638,6 +638,9 @@ def can_append_request_converter(self, *, converter_type: type[Converter]) -> bo

Returns:
bool: ``True`` when the converter can be appended safely.

Raises:
TypeError: If the baked ``attack_converter_config`` is not an ``AttackConverterConfig``.
"""
if "attack_converter_config" not in self._compatibility_helper.accepted_params:
return False
Expand All @@ -646,6 +649,8 @@ def can_append_request_converter(self, *, converter_type: type[Converter]) -> bo
converter_config = self._attack_kwargs.get("attack_converter_config")
if converter_config is None:
return "text" in converter_type.SUPPORTED_INPUT_TYPES
if not isinstance(converter_config, AttackConverterConfig):
raise TypeError("attack_converter_config must be an AttackConverterConfig")

for configuration in converter_config.request_converters:
next_output_types: set[PromptDataType] = set()
Expand Down Expand Up @@ -1344,12 +1349,17 @@ def _compose_converter_config(
Returns:
AttackConverterConfig | None: The selected config with any extra request converters appended,
or None when neither a config nor extra converters are present.

Raises:
TypeError: If the selected non-None converter config is not an ``AttackConverterConfig``.
"""
base: AttackConverterConfig | None = (
base = (
attack_converter_config_override
if attack_converter_config_override is not None
else self._attack_kwargs.get("attack_converter_config")
)
if base is not None and not isinstance(base, AttackConverterConfig):
raise TypeError("attack_converter_config must be an AttackConverterConfig")

if not extra_request_converters:
return base
Expand Down
5 changes: 3 additions & 2 deletions pyrit/scenario/scenarios/foundry/assert_policy.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@
import logging
from collections import Counter
from dataclasses import replace
from typing import TYPE_CHECKING, Any, ClassVar
from typing import TYPE_CHECKING, Any, ClassVar, cast

from pyrit.common import apply_defaults
from pyrit.common.path import EXECUTOR_RED_TEAM_PATH
Expand Down Expand Up @@ -349,7 +349,8 @@ def _get_stored_system_prompt(group: AttackSeedGroup) -> str | None:

def _get_judged_system_prompt(self, group: AttackSeedGroup) -> str | None:
stored = self._get_stored_system_prompt(group)
shared: str | None = self.params.get("target_system_prompt")
# Parameter resolution coerces this declared parameter to str or None.
shared = cast("str | None", self.params.get("target_system_prompt"))
return stored if stored is not None else shared

@staticmethod
Expand Down
14 changes: 12 additions & 2 deletions tests/unit/executor/attack/multi_turn/test_tree_of_attacks.py
Original file line number Diff line number Diff line change
Expand Up @@ -2961,10 +2961,12 @@ def test_tap_scoring_config_threshold_raises_for_a_scorer_without_a_threshold():
_ = scoring_config.threshold


def test_tap_attack_result_tree_visualization_getter_returns_value():
@pytest.mark.parametrize("has_root", [False, True])
def test_tap_attack_result_tree_visualization_getter_returns_value(has_root):
"""Test that TAPAttackResult.tree_visualization returns the stored tree."""
tree = Tree()
tree.create_node("root", "root")
if has_root:
tree.create_node("root", "root")
result = TAPAttackResult(
conversation_id="conv1",
objective="test",
Expand All @@ -2982,6 +2984,14 @@ def test_tap_attack_result_tree_visualization_getter_returns_none_when_missing()
assert result.tree_visualization is None


@pytest.mark.parametrize("value", [0, "invalid"])
def test_tap_attack_result_tree_visualization_rejects_invalid_metadata(value):
result = TAPAttackResult(conversation_id="conv1", objective="test", metadata={"tree_visualization": value})

with pytest.raises(TypeError, match="tree_visualization must be a Tree or None"):
_ = result.tree_visualization


# ---------------------------------------------------------------------------
# Scenario-driven end-to-end TAP simulation tests
# ---------------------------------------------------------------------------
Expand Down
10 changes: 10 additions & 0 deletions tests/unit/scenario/core/test_attack_technique_factory.py
Original file line number Diff line number Diff line change
Expand Up @@ -313,6 +313,16 @@ def test_cannot_append_text_converter_to_image_chain(self):

assert not factory.can_append_request_converter(converter_type=TranslationConverter)

def test_can_append_request_converter_rejects_baked_value_that_is_not_a_converter_config(self):
factory = AttackTechniqueFactory(
name="test",
attack_class=PromptSendingAttack,
attack_kwargs={"attack_converter_config": {"request_converters": []}},
)

with pytest.raises(TypeError, match="attack_converter_config must be an AttackConverterConfig"):
factory.can_append_request_converter(converter_type=TranslationConverter)

def test_request_converter_composition_requires_supported_constructor(self):
class _NoConverterAttack(_StubAttack):
def __init__(self, *, objective_target, attack_scoring_config=None):
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -51,11 +51,13 @@ def _create(factory: AttackTechniqueFactory, **kwargs):
)


def test_no_override_or_extras_preserves_baked_configuration():
@pytest.mark.parametrize("has_config", [False, True])
def test_no_override_or_extras_preserves_baked_configuration(has_config):
baked = _converter_config(
request=ConverterConfiguration.from_converters(converters=[Base64Converter()]),
response=ConverterConfiguration.from_converters(converters=[ROT13Converter()]),
)
baked = baked if has_config else None
factory = AttackTechniqueFactory(
name="test",
attack_class=_ConverterAttack,
Expand Down Expand Up @@ -197,6 +199,19 @@ def get_identifier(self) -> ComponentIdentifier:
return ComponentIdentifier(class_name="_NoConverterAttack", class_module="test")


@pytest.mark.parametrize("with_extras", [False, True])
def test_baked_value_that_is_not_a_converter_config_raises(with_extras):
factory = AttackTechniqueFactory(
name="test",
attack_class=_ConverterAttack,
attack_kwargs={"attack_converter_config": {"request_converters": []}},
)
extras = ConverterConfiguration.from_converters(converters=[Base64Converter()]) if with_extras else None

with pytest.raises(TypeError, match="attack_converter_config must be an AttackConverterConfig"):
_create(factory, extra_request_converters=extras)


def test_extras_raise_when_the_attack_cannot_take_converters():
factory = AttackTechniqueFactory(name="custom", attack_class=_NoConverterAttack)
extras = ConverterConfiguration.from_converters(converters=[Base64Converter()])
Expand Down
Loading