From 46689b6b2daf59c95c6169eb7902cffbc73a810b Mon Sep 17 00:00:00 2001 From: SteeveCrypto <76264891+Steeve-Crypto@users.noreply.github.com> Date: Fri, 20 Nov 2026 10:47:31 -0500 Subject: [PATCH 1/3] Fix backend unsound assignments --- pyproject.toml | 7 --- pyrit/backend/middleware/runtime.py | 5 +- pyrit/backend/routes/targets.py | 6 ++- pyrit/backend/routes/version.py | 50 +++++++++++++++++--- pyrit/backend/services/attack_service.py | 4 +- pyrit/backend/services/finding_export.py | 4 +- pyrit/backend/services/scenario_service.py | 8 +++- pyrit/backend/services/target_service.py | 2 +- tests/unit/backend/test_api_routes.py | 55 ++++++++++++++++++++++ 9 files changed, 118 insertions(+), 23 deletions(-) diff --git a/pyproject.toml b/pyproject.toml index 07edbc8d32..76e8595a6e 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -322,13 +322,6 @@ unsound-assignment = "ignore" [[tool.ty.overrides]] include = [ "pyrit/auth/browser_session_copilot_authenticator.py", - "pyrit/backend/middleware/runtime.py", - "pyrit/backend/routes/targets.py", - "pyrit/backend/routes/version.py", - "pyrit/backend/services/attack_service.py", - "pyrit/backend/services/finding_export.py", - "pyrit/backend/services/prompt_generation_service.py", - "pyrit/backend/services/scenario_service.py", "pyrit/cli/api_client.py", "pyrit/cli/pyrit_scan.py", "pyrit/common/cli_helpers.py", diff --git a/pyrit/backend/middleware/runtime.py b/pyrit/backend/middleware/runtime.py index d79d2775a1..c9ce524919 100644 --- a/pyrit/backend/middleware/runtime.py +++ b/pyrit/backend/middleware/runtime.py @@ -4,7 +4,7 @@ """ASGI-level admission that retains server work after a client disconnect.""" import asyncio -from typing import TYPE_CHECKING +from typing import TYPE_CHECKING, cast from starlette.responses import JSONResponse from starlette.types import ASGIApp, Receive, Scope, Send @@ -25,7 +25,8 @@ async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None: if scope["type"] != "http": await self.app(scope, receive, send) return - runtime: RuntimeLifecycle | None = getattr(scope["app"].state, "runtime_lifecycle", None) + # Only the app lifespan sets runtime_lifecycle, always to a RuntimeLifecycle; it is unset before startup. + runtime = cast("RuntimeLifecycle | None", getattr(scope["app"].state, "runtime_lifecycle", None)) path = scope["path"] if ( runtime is None diff --git a/pyrit/backend/routes/targets.py b/pyrit/backend/routes/targets.py index a93b221259..9342673336 100644 --- a/pyrit/backend/routes/targets.py +++ b/pyrit/backend/routes/targets.py @@ -8,6 +8,8 @@ Target types are set at app startup via initializers - you cannot add new types at runtime. """ +from typing import cast + from fastapi import APIRouter, HTTPException, Query, Request, status from fastapi.responses import JSONResponse @@ -86,8 +88,8 @@ def _target_upload_directory(request: Request) -> str | None: Returns: str | None: The configured folder, or None when the server configures none. """ - directory: str | None = getattr(request.app.state, "target_upload_directory", None) - return directory + # RuntimeLifecycle sets this from the validated server config, always as str | None. + return cast("str | None", getattr(request.app.state, "target_upload_directory", None)) def _saved_entry_owner(request: Request) -> SavedEntryOwner | None: diff --git a/pyrit/backend/routes/version.py b/pyrit/backend/routes/version.py index 360c55ecc1..ebe369ed7b 100644 --- a/pyrit/backend/routes/version.py +++ b/pyrit/backend/routes/version.py @@ -7,7 +7,7 @@ import json import logging from pathlib import Path -from typing import NotRequired, TypedDict +from typing import NotRequired, TypedDict, TypeVar, cast from fastapi import APIRouter, Request from pydantic import BaseModel @@ -19,6 +19,8 @@ router = APIRouter(prefix="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/api/version", tags=["version"]) +_T = TypeVar("_T") + class BuildInfo(TypedDict): """Optional Docker build-info keys; commit may also be explicitly null.""" @@ -38,10 +40,45 @@ def _load_build_info(build_info_path: Path) -> BuildInfo: Returns: BuildInfo: Parsed build metadata; every key may be absent. + + Raises: + ValueError: If the file is not a JSON object or a known key has the wrong type. """ with open(build_info_path) as file: - info: BuildInfo = json.load(file) - return info + data = json.load(file) + if not isinstance(data, dict): + raise ValueError(f"{build_info_path} must contain a JSON object, got {type(data).__name__}") + info: BuildInfo = {} + if "source" in data: + info["source"] = _build_info_value(data, key="source", expected=str) + if "commit" in data: + info["commit"] = None if data["commit"] is None else _build_info_value(data, key="commit", expected=str) + if "modified" in data: + info["modified"] = _build_info_value(data, key="modified", expected=bool) + if "display" in data: + info["display"] = _build_info_value(data, key="display", expected=str) + return info + + +def _build_info_value(data: dict[str, object], *, key: str, expected: type[_T]) -> _T: + """ + Return one build-info value after checking its type. + + Args: + data: The parsed build-info object. + key: The key to read. + expected: The type the value must have. + + Returns: + The value under ``key``. + + Raises: + ValueError: If the value does not have the expected type. + """ + value = data[key] + if not isinstance(value, expected): + raise ValueError(f"Build info '{key}' must be {expected.__name__}, got {type(value).__name__}") + return value class VersionResponse(BaseModel): @@ -99,9 +136,10 @@ async def get_version_async(request: Request) -> VersionResponse: except Exception as e: logger.debug(f"Could not detect database info: {e}") - # Read default labels from app state (set by pyrit_backend CLI) - default_labels: dict[str, str] | None = getattr(request.app.state, "default_labels", None) or None - default_operation: str | None = getattr(request.app.state, "default_operation", None) + # Read default labels from app state. RuntimeLifecycle publishes both from the validated + # server config, as dict[str, str] and str | None, and they are unset before startup. + default_labels = cast("dict[str, str] | None", getattr(request.app.state, "default_labels", None)) or None + default_operation = cast("str | None", getattr(request.app.state, "default_operation", None)) return VersionResponse( version=version, diff --git a/pyrit/backend/services/attack_service.py b/pyrit/backend/services/attack_service.py index 08267cd60c..ff4d8815ab 100644 --- a/pyrit/backend/services/attack_service.py +++ b/pyrit/backend/services/attack_service.py @@ -686,7 +686,7 @@ async def create_attack_async(self, *, request: CreateAttackRequest) -> CreateAt target_identifier = await self._get_save_target_async( registry_name=request.target_registry_name, binding=request.target_binding ) - copied: Sequence[MessagePiece] = [] + copied: Sequence[MessagePiece] = list[MessagePiece]() # The two branching fields form one spec; the conversation endpoint # rejects a half provided pair, and a silent fallthrough here would # create an unbranched attack while the caller believes it branched. @@ -1484,7 +1484,7 @@ async def create_related_conversation_async( attack_identifier = ar.get_attack_strategy_identifier() objective_target = attack_identifier.get_child("objective_target") if attack_identifier else None source_metadata: Conversation | None = None - all_pieces: Sequence[MessagePiece] = [] + all_pieces: Sequence[MessagePiece] = list[MessagePiece]() if request.source_conversation_id is not None and request.cutoff_index is not None: source_metadata = await self._memory.get_conversation_metadata_async( conversation_id=request.source_conversation_id diff --git a/pyrit/backend/services/finding_export.py b/pyrit/backend/services/finding_export.py index 79e38c0c8e..29947c2567 100644 --- a/pyrit/backend/services/finding_export.py +++ b/pyrit/backend/services/finding_export.py @@ -8,6 +8,7 @@ from datetime import UTC, datetime from functools import partial from io import BytesIO +from typing import cast from urllib.parse import quote, urlencode from uuid import UUID @@ -309,7 +310,8 @@ def _add_word_evidence(*, cell: _Cell, evidence: tuple[FindingReportEvidence, .. def _indented_paragraph(cell: _Cell) -> Paragraph: - paragraph: Paragraph = cell.add_paragraph() + # python-docx leaves _Cell.add_paragraph unannotated, but it always returns the new Paragraph. + paragraph = cast("Paragraph", cell.add_paragraph()) paragraph.paragraph_format.left_indent = _WORD_BULLET_TEXT_INDENT paragraph.paragraph_format.space_after = Pt(2) return paragraph diff --git a/pyrit/backend/services/scenario_service.py b/pyrit/backend/services/scenario_service.py index ed687c9bab..d103ee9109 100644 --- a/pyrit/backend/services/scenario_service.py +++ b/pyrit/backend/services/scenario_service.py @@ -11,6 +11,7 @@ from collections import OrderedDict from functools import lru_cache from time import monotonic +from typing import cast from pyrit.backend.models import ListRegisteredScenariosResponse, PaginationInfo from pyrit.backend.models.datasets import ScenarioDatasetLoadResponse @@ -343,9 +344,12 @@ async def _get_default_run_size_estimate_async(self, *, metadata: ScenarioMetada if cached is not None: return cached - tasks = getattr(self, "_estimate_tasks", None) + # Only __init__ and the fallback below set this attribute, both with this type. + tasks = cast( + "OrderedDict[_EstimateCacheKey, _EstimateTask] | None", getattr(self, "_estimate_tasks", None) + ) if tasks is None: - tasks = OrderedDict() + tasks = OrderedDict[_EstimateCacheKey, _EstimateTask]() self._estimate_tasks = tasks for completed_key in [key for key, candidate in tasks.items() if candidate.done()]: del tasks[completed_key] diff --git a/pyrit/backend/services/target_service.py b/pyrit/backend/services/target_service.py index 2d53e879c2..ce82db7cbb 100644 --- a/pyrit/backend/services/target_service.py +++ b/pyrit/backend/services/target_service.py @@ -306,7 +306,7 @@ async def get_target_async(self, *, target_registry_name: str) -> TargetInstance return None return self._build_instance_from_entry(entry) - def get_target_object(self, *, target_registry_name: str) -> Any | None: + def get_target_object(self, *, target_registry_name: str) -> PromptTarget | None: """ Get the actual target object for use in attacks. diff --git a/tests/unit/backend/test_api_routes.py b/tests/unit/backend/test_api_routes.py index f28b6cf999..2563d980a0 100644 --- a/tests/unit/backend/test_api_routes.py +++ b/tests/unit/backend/test_api_routes.py @@ -2142,6 +2142,61 @@ def test_get_version_build_info_absent_display_falls_back(self, client: TestClie assert data["modified"] is None assert data["display"] == data["version"] + def test_load_build_info_reads_known_keys(self, tmp_path: Path) -> None: + """Known keys are returned as written and extra keys from the Docker build are dropped.""" + build_info_path = tmp_path / "build_info.json" + build_info_path.write_text( + json.dumps( + {"source": "git", "version": "1.0.0", "commit": None, "modified": True, "display": "abc + local"} + ) + ) + + assert version_routes._load_build_info(build_info_path) == { + "source": "git", + "commit": None, + "modified": True, + "display": "abc + local", + } + + def test_load_build_info_rejects_non_object(self, tmp_path: Path) -> None: + build_info_path = tmp_path / "build_info.json" + build_info_path.write_text(json.dumps(["git"])) + + with pytest.raises(ValueError, match="must contain a JSON object, got list"): + version_routes._load_build_info(build_info_path) + + @pytest.mark.parametrize( + ("key", "value", "expected"), + [ + ("source", 1, "str"), + ("commit", 123, "str"), + ("modified", "true", "bool"), + ("display", None, "str"), + ], + ) + def test_load_build_info_rejects_wrong_value_type( + self, *, tmp_path: Path, key: str, value: object, expected: str + ) -> None: + build_info_path = tmp_path / "build_info.json" + build_info_path.write_text(json.dumps({key: value})) + + with pytest.raises(ValueError, match=f"Build info '{key}' must be {expected}, got {type(value).__name__}"): + version_routes._load_build_info(build_info_path) + + def test_get_version_ignores_malformed_build_info(self, *, client: TestClient, tmp_path: Path) -> None: + """A wrongly typed build-info value falls back to defaults instead of failing the response.""" + build_info_path = tmp_path / "build_info.json" + build_info_path.write_text(json.dumps({"source": "git", "commit": 123, "display": "abc"})) + + with patch("pyrit.backend.routes.version.Path", return_value=build_info_path): + response = client.get("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/api/version") + + assert response.status_code == status.HTTP_200_OK + data = response.json() + assert data["source"] is None + assert data["commit"] is None + assert data["display"] == data["version"] + class TestScoreRoutes: """Tests for score API routes.""" From 27146c2a752dba85ea5d5e28194eb1464aa54965 Mon Sep 17 00:00:00 2001 From: SteeveCrypto <76264891+Steeve-Crypto@users.noreply.github.com> Date: Sat, 21 Nov 2026 11:14:50 -0500 Subject: [PATCH 2/3] Validate operator and operation types --- pyrit/setup/configuration_loader.py | 5 ++++- tests/unit/setup/test_configuration_loader.py | 9 +++++++++ 2 files changed, 13 insertions(+), 1 deletion(-) diff --git a/pyrit/setup/configuration_loader.py b/pyrit/setup/configuration_loader.py index 3247ca375d..facf89522d 100644 --- a/pyrit/setup/configuration_loader.py +++ b/pyrit/setup/configuration_loader.py @@ -183,7 +183,7 @@ def __post_init__(self) -> None: Raises: ValueError: If concurrency or source paths are invalid. - TypeError: If a boolean configuration option has the wrong type. + TypeError: If a boolean option, operator, or operation has the wrong type. """ if type(self.max_concurrent_scenario_runs) is not int or self.max_concurrent_scenario_runs < 1: raise ValueError("max_concurrent_scenario_runs must be a positive integer.") @@ -192,6 +192,9 @@ def __post_init__(self) -> None: not isinstance(values, list) or any(not is_non_empty_string(value) for value in values) ): raise ValueError("Environment files and initialization scripts must be lists of non-empty paths.") + for name, value in (("operator", self.operator), ("operation", self.operation)): + if value is not None and not isinstance(value, str): + raise TypeError(f"{name} must be a string or None.") validate_env_akv_strict(env_akv_strict=self.env_akv_strict) if not isinstance(self.enable_live_reinitialization, bool): raise TypeError("enable_live_reinitialization must be a bool.") diff --git a/tests/unit/setup/test_configuration_loader.py b/tests/unit/setup/test_configuration_loader.py index 61849f1c9a..ffb95896c4 100644 --- a/tests/unit/setup/test_configuration_loader.py +++ b/tests/unit/setup/test_configuration_loader.py @@ -52,6 +52,15 @@ def test_default_values(self): assert config.scenario_suites_source is None assert config.silent is False + @pytest.mark.parametrize("field", ["operator", "operation"]) + def test_rejects_numeric_label_in_yaml(self, tmp_path: pathlib.Path, field: str) -> None: + """Reject numeric operator and operation values during configuration loading.""" + config_path = tmp_path / "config.yaml" + config_path.write_text(f"{field}: 123\n", encoding="utf-8") + + with pytest.raises(TypeError, match=field): + ConfigurationLoader.from_yaml_file(config_path) + def test_custom_initializers_source_loads_from_yaml(self, tmp_path: pathlib.Path) -> None: """Test loading an Azure Blob container URI for custom initializer scripts.""" config_path = tmp_path / "config.yaml" From a06f2197cfe27808f1dcaf50990a5f277319943e Mon Sep 17 00:00:00 2001 From: Roman Lutz Date: Sat, 21 Nov 2026 23:08:59 -0800 Subject: [PATCH 3/3] Parse build info with a pydantic model BuildInfo as a strict pydantic model replaces the TypedDict plus per-key isinstance checks; ValidationError is caught by the existing fallback in get_version_async. Explicit JSON nulls now validate instead of rejecting the whole file, which produces the same response values. Co-Authored-By: Claude Fable 5 --- pyrit/backend/routes/version.py | 66 +++++++-------------------- tests/unit/backend/test_api_routes.py | 50 +++++++++----------- 2 files changed, 37 insertions(+), 79 deletions(-) diff --git a/pyrit/backend/routes/version.py b/pyrit/backend/routes/version.py index ebe369ed7b..e6aae3192a 100644 --- a/pyrit/backend/routes/version.py +++ b/pyrit/backend/routes/version.py @@ -4,13 +4,12 @@ """API routes for version information.""" import asyncio -import json import logging from pathlib import Path -from typing import NotRequired, TypedDict, TypeVar, cast +from typing import cast from fastapi import APIRouter, Request -from pydantic import BaseModel +from pydantic import BaseModel, ConfigDict import pyrit from pyrit.memory import CentralMemory @@ -19,16 +18,16 @@ router = APIRouter(prefix="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/api/version", tags=["version"]) -_T = TypeVar("_T") +class BuildInfo(BaseModel): + """Docker build-info file; every key may be absent and extra keys are ignored.""" -class BuildInfo(TypedDict): - """Optional Docker build-info keys; commit may also be explicitly null.""" + model_config = ConfigDict(strict=True) - source: NotRequired[str] - commit: NotRequired[str | None] - modified: NotRequired[bool] - display: NotRequired[str] + source: str | None = None + commit: str | None = None + modified: bool | None = None + display: str | None = None def _load_build_info(build_info_path: Path) -> BuildInfo: @@ -39,46 +38,13 @@ def _load_build_info(build_info_path: Path) -> BuildInfo: build_info_path: Path to the build metadata JSON file. Returns: - BuildInfo: Parsed build metadata; every key may be absent. + BuildInfo: Parsed build metadata; absent keys are None. Raises: - ValueError: If the file is not a JSON object or a known key has the wrong type. + pydantic.ValidationError: If the file is not a JSON object or a known key has the wrong type. """ with open(build_info_path) as file: - data = json.load(file) - if not isinstance(data, dict): - raise ValueError(f"{build_info_path} must contain a JSON object, got {type(data).__name__}") - info: BuildInfo = {} - if "source" in data: - info["source"] = _build_info_value(data, key="source", expected=str) - if "commit" in data: - info["commit"] = None if data["commit"] is None else _build_info_value(data, key="commit", expected=str) - if "modified" in data: - info["modified"] = _build_info_value(data, key="modified", expected=bool) - if "display" in data: - info["display"] = _build_info_value(data, key="display", expected=str) - return info - - -def _build_info_value(data: dict[str, object], *, key: str, expected: type[_T]) -> _T: - """ - Return one build-info value after checking its type. - - Args: - data: The parsed build-info object. - key: The key to read. - expected: The type the value must have. - - Returns: - The value under ``key``. - - Raises: - ValueError: If the value does not have the expected type. - """ - value = data[key] - if not isinstance(value, expected): - raise ValueError(f"Build info '{key}' must be {expected.__name__}, got {type(value).__name__}") - return value + return BuildInfo.model_validate_json(file.read()) class VersionResponse(BaseModel): @@ -117,10 +83,10 @@ async def get_version_async(request: Request) -> VersionResponse: if await asyncio.to_thread(build_info_path.exists): try: build_info = await asyncio.to_thread(_load_build_info, build_info_path) - source = build_info.get("source") - commit = build_info.get("commit") - modified = build_info.get("modified") - display = build_info.get("display", version) + source = build_info.source + commit = build_info.commit + modified = build_info.modified + display = build_info.display or version except Exception as e: logger.warning(f"Failed to load build info: {e}") diff --git a/tests/unit/backend/test_api_routes.py b/tests/unit/backend/test_api_routes.py index 2563d980a0..8772f72d22 100644 --- a/tests/unit/backend/test_api_routes.py +++ b/tests/unit/backend/test_api_routes.py @@ -12,13 +12,13 @@ from contextlib import nullcontext from datetime import UTC, datetime from pathlib import Path -from typing import NotRequired, get_type_hints from unittest.mock import AsyncMock, MagicMock, patch from urllib.parse import urlencode import pytest from fastapi import Request, status from fastapi.testclient import TestClient +from pydantic import ValidationError from pyrit.backend.main import app from pyrit.backend.middleware.auth import AuthenticatedUser @@ -2057,7 +2057,7 @@ def test_get_version_exposes_default_operation_proposal(self, client: TestClient @pytest.mark.parametrize("commit", ["abc123", None]) def test_get_version_with_build_info(self, *, client: TestClient, commit: str | None) -> None: """Test getting version with build info from Docker.""" - build_info: version_routes.BuildInfo = { + build_info: dict[str, str | bool | None] = { "source": "git" if commit is not None else "pypi", "commit": commit, "modified": False, @@ -2110,16 +2110,10 @@ def test_get_version_build_info_load_failure(self, client: TestClient) -> None: assert data["commit"] is None def test_build_info_keys_are_not_required(self) -> None: - """The BuildInfo contract keeps absent keys distinguishable from nullable values.""" - assert get_type_hints(version_routes.BuildInfo, include_extras=True) == { - "source": NotRequired[str], - "commit": NotRequired[str | None], - "modified": NotRequired[bool], - "display": NotRequired[str], - } - assert version_routes.BuildInfo.__required_keys__ == frozenset() - assert version_routes.BuildInfo.__optional_keys__ == {"source", "commit", "modified", "display"} - assert version_routes.BuildInfo() == {} + """Every build-info key may be absent and defaults to None.""" + assert version_routes.BuildInfo() == version_routes.BuildInfo( + source=None, commit=None, modified=None, display=None + ) def test_get_version_build_info_absent_display_falls_back(self, client: TestClient) -> None: """A build-info file without `display` falls back to the package version.""" @@ -2127,7 +2121,7 @@ def test_get_version_build_info_absent_display_falls_back(self, client: TestClie with ( patch("pyrit.backend.routes.version.Path") as mock_path_class, patch("pyrit.backend.routes.version.asyncio.to_thread", new=to_thread_mock), - patch.object(version_routes, "_load_build_info", return_value={"source": "git"}), + patch.object(version_routes, "_load_build_info", return_value=version_routes.BuildInfo(source="git")), ): mock_path_instance = MagicMock() mock_path_instance.exists.return_value = True @@ -2151,36 +2145,34 @@ def test_load_build_info_reads_known_keys(self, tmp_path: Path) -> None: ) ) - assert version_routes._load_build_info(build_info_path) == { - "source": "git", - "commit": None, - "modified": True, - "display": "abc + local", - } + assert version_routes._load_build_info(build_info_path) == version_routes.BuildInfo( + source="git", + commit=None, + modified=True, + display="abc + local", + ) def test_load_build_info_rejects_non_object(self, tmp_path: Path) -> None: build_info_path = tmp_path / "build_info.json" build_info_path.write_text(json.dumps(["git"])) - with pytest.raises(ValueError, match="must contain a JSON object, got list"): + with pytest.raises(ValidationError, match="Input should be an object"): version_routes._load_build_info(build_info_path) @pytest.mark.parametrize( - ("key", "value", "expected"), + ("key", "value"), [ - ("source", 1, "str"), - ("commit", 123, "str"), - ("modified", "true", "bool"), - ("display", None, "str"), + ("source", 1), + ("commit", 123), + ("modified", "true"), + ("display", 5), ], ) - def test_load_build_info_rejects_wrong_value_type( - self, *, tmp_path: Path, key: str, value: object, expected: str - ) -> None: + def test_load_build_info_rejects_wrong_value_type(self, *, tmp_path: Path, key: str, value: object) -> None: build_info_path = tmp_path / "build_info.json" build_info_path.write_text(json.dumps({key: value})) - with pytest.raises(ValueError, match=f"Build info '{key}' must be {expected}, got {type(value).__name__}"): + with pytest.raises(ValidationError, match=key): version_routes._load_build_info(build_info_path) def test_get_version_ignores_malformed_build_info(self, *, client: TestClient, tmp_path: Path) -> None: