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 @@ -324,13 +324,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",
Expand Down
5 changes: 3 additions & 2 deletions pyrit/backend/middleware/runtime.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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
Expand Down
6 changes: 4 additions & 2 deletions pyrit/backend/routes/targets.py
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down Expand Up @@ -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:
Expand Down
42 changes: 23 additions & 19 deletions pyrit/backend/routes/version.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,13 +4,12 @@
"""API routes for version information."""

import asyncio
import json
import logging
from pathlib import Path
from typing import NotRequired, TypedDict
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
Expand All @@ -20,13 +19,15 @@
router = APIRouter(prefix="/api/version", tags=["version"])


class BuildInfo(TypedDict):
"""Optional Docker build-info keys; commit may also be explicitly null."""
class BuildInfo(BaseModel):
"""Docker build-info file; every key may be absent and extra keys are ignored."""

source: NotRequired[str]
commit: NotRequired[str | None]
modified: NotRequired[bool]
display: NotRequired[str]
model_config = ConfigDict(strict=True)

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:
Expand All @@ -37,11 +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:
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:
info: BuildInfo = json.load(file)
return info
return BuildInfo.model_validate_json(file.read())


class VersionResponse(BaseModel):
Expand Down Expand Up @@ -80,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}")

Expand All @@ -99,9 +102,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))
Comment thread
Steeve-Crypto marked this conversation as resolved.
Resolved

return VersionResponse(
version=version,
Expand Down
4 changes: 2 additions & 2 deletions pyrit/backend/services/attack_service.py
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down Expand Up @@ -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
Expand Down
4 changes: 3 additions & 1 deletion pyrit/backend/services/finding_export.py
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down Expand Up @@ -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
Expand Down
8 changes: 6 additions & 2 deletions pyrit/backend/services/scenario_service.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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]
Expand Down
2 changes: 1 addition & 1 deletion pyrit/backend/services/target_service.py
Original file line number Diff line number Diff line change
Expand Up @@ -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.

Expand Down
5 changes: 4 additions & 1 deletion pyrit/setup/configuration_loader.py
Original file line number Diff line number Diff line change
Expand Up @@ -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.")
Expand All @@ -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.")
Expand Down
73 changes: 60 additions & 13 deletions tests/unit/backend/test_api_routes.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -2071,7 +2071,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,
Expand Down Expand Up @@ -2124,24 +2124,18 @@ 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."""
to_thread_mock = AsyncMock(side_effect=lambda func, *args, **kwargs: func(*args, **kwargs))
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
Expand All @@ -2156,6 +2150,59 @@ 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) == 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(ValidationError, match="Input should be an object"):
version_routes._load_build_info(build_info_path)

@pytest.mark.parametrize(
("key", "value"),
[
("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) -> None:
build_info_path = tmp_path / "build_info.json"
build_info_path.write_text(json.dumps({key: value}))

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:
"""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("/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."""
Expand Down
9 changes: 9 additions & 0 deletions tests/unit/setup/test_configuration_loader.py
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Expand Down
Loading