diff --git a/.pyrit_conf_example b/.pyrit_conf_example index 51488ee0d8..4fbad18e24 100644 --- a/.pyrit_conf_example +++ b/.pyrit_conf_example @@ -161,6 +161,21 @@ allow_custom_initializers: false # as scenario_presets_source. Defaults to ~/.pyrit/scenario_suites. # scenario_suites_source: https://account.blob.core.windows.net/container/scenario_suites +# Optional storage for saved targets, converters, scorers, and techniques, so they +# come back when the backend restarts. Each kind has its own folder under the source. +# This supports the same local directory and Azure Blob sources as +# scenario_presets_source. If any saved entry can't be restored, the backend stays +# not ready and lists the failures in its runtime status. Fix or delete the listed +# files, then apply the configuration or restart the backend. Defaults to +# ~/.pyrit/registry_recipes. +# +# ⚠️ WARNING: The backend rebuilds every saved entry in this source as an +# administrator, at startup and live reinitialization. Anyone who can write to this +# source can make the backend run a model's repository code or use its identity. +# Restrict write access to trusted administrators, and use a dedicated folder or +# blob prefix. +# registry_recipes_source: https://account.blob.core.windows.net/container/registry_recipes + # Upload Folder for API-Created Targets # ------------------------------------- # Folder that targets created through the REST API may upload local files from diff --git a/doc/getting_started/pyrit_conf.md b/doc/getting_started/pyrit_conf.md index bba64b45d4..c00c7baf78 100644 --- a/doc/getting_started/pyrit_conf.md +++ b/doc/getting_started/pyrit_conf.md @@ -194,6 +194,20 @@ Suites store ordered references to scenario presets and resolve each preset's cu A SAS query string may be included; otherwise, PyRIT uses `DefaultAzureCredential`. The default is `~/.pyrit/scenario_suites`. Local writes use the same hidden lock-file and atomic replacement behavior as scenario presets. Startup scans the configured source so malformed suite documents are reported immediately without preventing the backend from starting. +### `registry_recipes_source` + +Stores saved targets, converters, scorers, and techniques in a local directory or Azure Blob container, so they come back when the backend restarts. An Azure URI may include a blob-name prefix: + +```yaml +registry_recipes_source: https://account.blob.core.windows.net/pyrit-storage/registry-recipes +``` + +Each kind has its own folder under the source (`targets/`, `converters/`, `scorers/`, `techniques/`), with one JSON file per saved entry named after the entry. A file holds the create request the entry was made with, and restore builds the entry through the API's create for its kind; restore refuses a file that stores a value for a parameter its class marks as a credential, such as `api_key`. A SAS query string may be included; otherwise, PyRIT uses `DefaultAzureCredential`. The default is `~/.pyrit/registry_recipes`. + +A saved file doesn't record who saved it, so the backend rebuilds every entry in this source as an administrator, at startup and after a live apply. A file here can, for example, make the backend run a model's repository code, or use the server's identity on a storage container that the file names. Write access to this source is administrator authority on the backend: grant it only to principals you already trust as backend administrators, and use a dedicated directory or blob prefix that less-trusted users and services cannot write to. + +The backend restores saved entries at startup and after a live apply, once the configured initializers have registered theirs. If any saved entry can't be restored, the backend doesn't become ready (state `failed`, outcome `restore-failed`) and lists each failure with its reason in `GET /api/config/runtime`, so a scan can't quietly run without an entry it expects. Until then, only the configuration and status routes answer; the rest return 503. Fix or delete the listed files, or, when a folder couldn't be listed, check that the backend can read this source. Then apply the configuration, if `enable_live_reinitialization` is on, or restart the backend. Files whose names aren't valid entry names (up to 64 lowercase letters, digits, and underscores, starting with a letter) are skipped without blocking startup; administrators can see them under `restore_ignored` in `GET /api/config/runtime`. + ### `initialization_scripts` Local paths to custom Python scripts containing `PyRITInitializer` subclasses. Paths can be absolute or relative to the current working directory. diff --git a/frontend/e2e/fixtures/manual_send_backend.py b/frontend/e2e/fixtures/manual_send_backend.py index 0c46ed2398..8be9b44941 100644 --- a/frontend/e2e/fixtures/manual_send_backend.py +++ b/frontend/e2e/fixtures/manual_send_backend.py @@ -4,6 +4,7 @@ """Offline backend for manual-send browser tests, with no real configuration or providers.""" import os +import tempfile from collections.abc import AsyncGenerator from contextlib import asynccontextmanager from unittest.mock import AsyncMock, patch @@ -27,19 +28,22 @@ async def _initialize_offline_async(self: ConfigurationLoader, *, raise_on_initi @asynccontextmanager async def _offline_lifespan_async(application: FastAPI) -> AsyncGenerator[None, None]: - config = ConfigurationLoader(memory_db_type="in_memory", env_files=[], env_akv_ref=[]) - with ( - patch.dict(os.environ, {"PYRIT_AUTH_MODE": "local", "PYRIT_DEV_MODE": "true"}, clear=True), - patch.object( - ConfigurationFileService, - "_read_source_async", - new=AsyncMock(return_value="memory_db_type: in_memory\nenv_files: []\ninitializers: []\n"), - ), - patch.object(ConfigurationLoader, "load_with_overrides", return_value=config), - patch.object(ConfigurationLoader, "initialize_pyrit_async", new=_initialize_offline_async), - ): - async with lifespan(application): - yield + with tempfile.TemporaryDirectory() as recipes: + config = ConfigurationLoader( + memory_db_type="in_memory", env_files=[], env_akv_ref=[], registry_recipes_source=recipes + ) + with ( + patch.dict(os.environ, {"PYRIT_AUTH_MODE": "local", "PYRIT_DEV_MODE": "true"}, clear=True), + patch.object( + ConfigurationFileService, + "_read_source_async", + new=AsyncMock(return_value="memory_db_type: in_memory\nenv_files: []\ninitializers: []\n"), + ), + patch.object(ConfigurationLoader, "load_with_overrides", return_value=config), + patch.object(ConfigurationLoader, "initialize_pyrit_async", new=_initialize_offline_async), + ): + async with lifespan(application): + yield app.router.lifespan_context = _offline_lifespan_async diff --git a/frontend/src/components/Configuration/Reinitialize.test.tsx b/frontend/src/components/Configuration/Reinitialize.test.tsx index 78614257fd..4d74590ca0 100644 --- a/frontend/src/components/Configuration/Reinitialize.test.tsx +++ b/frontend/src/components/Configuration/Reinitialize.test.tsx @@ -124,6 +124,26 @@ describe('Reinitialize', () => { expect(screen.getByRole('button', { name: 'Reinitialize PyRIT' })).toBeDisabled() }) + it('should let a failed restore be retried by reinitializing', async () => { + const user = userEvent.setup() + api.getRuntimeStatus.mockResolvedValue({ + ...ready, + state: 'failed', + outcome: 'restore-failed', + message: "1 saved registry entry couldn't be restored.", + }) + render( + + + , + ) + expect(await screen.findByText(/Runtime: failed\. 1 saved registry entry/)).toBeInTheDocument() + await waitFor(() => expect(screen.getByRole('button', { name: 'Reinitialize PyRIT' })).toBeEnabled()) + await user.click(screen.getByRole('button', { name: 'Reinitialize PyRIT' })) + await user.click(within(await screen.findByRole('dialog')).getByRole('button', { name: 'Reinitialize PyRIT' })) + await waitFor(() => expect(api.reinitialize).toHaveBeenCalledWith('saved-v1')) + }) + describe('runtime status polling', () => { beforeEach(() => { jest.useFakeTimers() diff --git a/pyrit/backend/README.md b/pyrit/backend/README.md index 444cd2be87..ab3aae9ee6 100644 --- a/pyrit/backend/README.md +++ b/pyrit/backend/README.md @@ -691,8 +691,9 @@ The chat preserves failed drafts across replacement, but requires converter choi to be reviewed again rather than restoring outputs tied to the previous registry. The offline browser fixture `frontend.e2e.fixtures.manual_send_backend:app` uses the real -backend lifecycle with isolated in-memory SQLite, no environment files, and no default -providers. The recovery tests register deterministic loopback targets. For example, start +backend lifecycle with isolated in-memory SQLite, no environment files, no saved registry +entries, and no default providers. The recovery tests register deterministic loopback +targets. For example, start it with `uv run python -m uvicorn frontend.e2e.fixtures.manual_send_backend:app --host 127.0.0.1 --port 18213` (set `PYTHONUTF8=1` on Windows). In another shell, set `PYRIT_BACKEND_URL=http://127.0.0.1:18213` and `E2E_FRONTEND_PORT=31213`, then run `npx playwright test chat-recovery --project seeded --workers 1` diff --git a/pyrit/backend/services/runtime_lifecycle.py b/pyrit/backend/services/runtime_lifecycle.py index daef21f0ed..ebeecf30c8 100644 --- a/pyrit/backend/services/runtime_lifecycle.py +++ b/pyrit/backend/services/runtime_lifecycle.py @@ -7,7 +7,8 @@ import logging import os import uuid -from typing import Any +from functools import partial +from typing import TYPE_CHECKING, Any from fastapi import FastAPI @@ -15,6 +16,7 @@ from pyrit.backend.services.analytics_service import get_analytics_service from pyrit.backend.services.configuration_file_service import ConfigurationFileService from pyrit.backend.services.environment_file_service import EnvironmentFileService +from pyrit.backend.services.saved_entry_restore import build_saved_entry_async from pyrit.backend.services.scenario_run_service import get_scenario_run_service, peek_scenario_run_service from pyrit.backend.services.scenario_suite_execution_service import peek_scenario_suite_execution_service from pyrit.backend.services.service_lifecycle import ( @@ -26,10 +28,14 @@ from pyrit.common.path import CONFIGURATION_DIRECTORY_PATH from pyrit.memory import CentralMemory from pyrit.registry import InitializerRegistry, ScenarioPresetRegistry, ScenarioSuiteRegistry +from pyrit.registry.registry_recipe_restore import RegistryRecipeRestorer from pyrit.setup import ConfigurationLoader from pyrit.setup.environment_loading import resolve_environment_async from pyrit.setup.initialization import validate_reinitialization_memory +if TYPE_CHECKING: + from pyrit.models.catalog import IgnoredRecipeFile, RestoreFailure + logger = logging.getLogger(__name__) @@ -46,6 +52,8 @@ def __init__(self, *, app: FastAPI, source: ConfigurationFileService) -> None: self.version: str | None = None self.outcome = "starting" self.message = "" + self.restore_failures: list[RestoreFailure] = [] + self.restore_ignored: list[IgnoredRecipeFile] = [] self.operations: set[asyncio.Task[None]] = set() self.management_operations: set[asyncio.Task[None]] = set() self.apply_task: asyncio.Task[None] | None = None @@ -75,6 +83,8 @@ def status(self) -> dict[str, Any]: "message": self.message, "enabled": self.topology_supported, "applying": self.apply_task is not None and not self.apply_task.done(), + "restore_failures": [failure.model_dump(mode="json") for failure in self.restore_failures], + "restore_ignored": [file.model_dump(mode="json") for file in self.restore_ignored], } async def _load_async(self) -> ConfigurationLoader: @@ -119,6 +129,52 @@ def _publish(self, config: ConfigurationLoader) -> None: self.generation = str(uuid.uuid4()) self.state, self.outcome, self.message = "ready", "success", "PyRIT is ready." + async def _restore_saved_entries_async(self, config: ConfigurationLoader) -> bool: + """ + Rebuild saved registry entries after the startup scripts have registered theirs. + + A failure keeps the runtime not ready, since a scan that would have used a missing entry + could quietly fall back to a different one. Fixing or deleting the stored file, then applying + or restarting, recovers. + + Args: + config (ConfigurationLoader): The loaded configuration naming the storage source. + + Returns: + bool: Whether every saved entry was restored. + """ + restorer = RegistryRecipeRestorer(source=config.registry_recipes_source) + # Reading can wait on storage, so it runs in a worker thread. Entries are built on this loop, through + # the API's create for each kind, because a constructor such as HuggingFaceChatTarget's starts a task + # on it. A slow constructor holds the loop while it runs. + saved = await asyncio.to_thread(restorer.read) + report = await restorer.restore_async( + saved=saved, build_async=partial(build_saved_entry_async, upload_directory=config.target_upload_directory) + ) + self.restore_failures, self.restore_ignored = report.failures, report.ignored + if not report.failures: + return True + self.state, self.outcome = "failed", "restore-failed" + next_step = ( + "apply the configuration or restart the backend" + if config.enable_live_reinitialization and self.topology_supported + else "restart the backend" + ) + unread = sorted({failure.kind.value for failure in report.failures if failure.name is None}) + if unread: + self.message = ( + f"The saved {' and '.join(unread)} couldn't be read, so no saved entries were restored. " + f"Check that the backend can read registry_recipes_source, then {next_step}." + ) + else: + count = len(report.failures) + self.message = ( + f"{count} saved registry {'entry' if count == 1 else 'entries'} couldn't be restored. " + f"Fix or delete the files named in the server log or GET /api/config/runtime, then {next_step}." + ) + logger.error("PyRIT isn't ready: %s", self.message) + return False + async def startup_async(self) -> None: """Keep management alive even when parsing or initialization fails.""" self.app.state.allow_custom_initializers = False @@ -137,7 +193,8 @@ async def startup_async(self) -> None: await config.initialize_pyrit_async(raise_on_initializer_error=True) await get_scenario_run_service().reconcile_interrupted_runs_async() _, self.version = await self.source.read_with_version_async() - self._publish(config) + if await self._restore_saved_entries_async(config): + self._publish(config) except Exception: self.state, self.outcome = "restart-required", "initialization-failed" self.message = "PyRIT setup failed. Repair saved configuration, then restart the backend." @@ -158,7 +215,7 @@ def begin_apply(self, *, version: str) -> dict[str, Any]: "outcome": "unsupported", "message": ("Reinitialization requires one backend worker and one replica."), } - if self.state in ("failed", "restart-required"): + if self.state == "restart-required": return {**self.status(), "outcome": "restart-required"} if (self.apply_task and not self.apply_task.done()) or self.edit_lock.locked() or self.management_operations: return {**self.status(), "outcome": "busy"} @@ -179,7 +236,9 @@ async def _apply_async(self, *, version: str) -> None: if not config.enable_live_reinitialization: self.outcome = "unsupported" self.message = ( - "Set enable_live_reinitialization: true in the saved configuration to use live apply." + "Live apply is off. Restart the backend to restore the saved entries again." + if previous_state == "failed" + else "Set enable_live_reinitialization: true in the saved configuration to use live apply." ) return # Type compatibility is checked before contacting environment sources. @@ -219,7 +278,8 @@ async def _apply_async(self, *, version: str) -> None: await config.apply_prepared_reinitialization_async(prepared=prepared) await self._management_async(config) self.version = current_version - self._publish(config) + if await self._restore_saved_entries_async(config): + self._publish(config) except (Exception, asyncio.CancelledError, BaseExceptionGroup) as error: logger.exception( "PyRIT live apply failed phase=%s generation=%s", diff --git a/pyrit/backend/services/saved_entry_restore.py b/pyrit/backend/services/saved_entry_restore.py new file mode 100644 index 0000000000..a4ac353988 --- /dev/null +++ b/pyrit/backend/services/saved_entry_restore.py @@ -0,0 +1,86 @@ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT license. + +"""Build saved registry entries through the API's own create for each kind.""" + +from __future__ import annotations + +from typing import TYPE_CHECKING, Any + +from pydantic import ValidationError + +from pyrit.backend.models import CreateConverterRequest, CreateScorerRequest, CreateTargetRequest +from pyrit.backend.models.techniques import CreateTechniqueRequest +from pyrit.backend.services.converter_service import get_converter_service +from pyrit.backend.services.scorer_service import get_scorer_service +from pyrit.backend.services.target_service import get_target_service +from pyrit.backend.services.technique_service import get_technique_service +from pyrit.models.catalog import RegistryRecipeKind, RestoreFailureReason, TechniqueRecipe +from pyrit.registry.registry_recipe_restore import RecipeRejectedError + +if TYPE_CHECKING: + from pyrit.models.catalog import StoredRecipe + + +async def build_saved_entry_async(stored: StoredRecipe, *, upload_directory: str | None) -> None: + """ + Build one saved entry with the create the API uses for its kind, and register it under its name. + + The entry passes the same checks a create request does. Restore runs as the server, and a saved file + doesn't record who saved it, so a target is built as an administrator would build it. A target that + uploads files gets this server's upload folder, as it does through the API. + + Args: + stored (StoredRecipe): The checked recipe to build. + upload_directory (str | None): The folder this server lets targets upload files from, or None. + + Raises: + RecipeRejectedError: If the recipe doesn't make a valid create request. + """ + request = _create_request(stored) + if isinstance(request, CreateTechniqueRequest): + await get_technique_service().create_async(request) + elif isinstance(request, CreateTargetRequest): + await get_target_service().create_target_async( + request=request, upload_directory=upload_directory, is_admin=True + ) + elif isinstance(request, CreateConverterRequest): + await get_converter_service().create_converter_async(request=request) + else: + await get_scorer_service().create_scorer_async(request=request) + + +def _create_request( + stored: StoredRecipe, +) -> CreateTargetRequest | CreateConverterRequest | CreateScorerRequest | CreateTechniqueRequest: + """ + Turn a saved recipe back into the create request it was saved from. + + Returns: + CreateTargetRequest | CreateConverterRequest | CreateScorerRequest | CreateTechniqueRequest: The request. + + Raises: + RecipeRejectedError: If the recipe doesn't make a valid request, such as a technique with a reserved name. + """ + recipe = stored.recipe + fields: dict[str, Any] = {"name": stored.ref.name} + try: + if isinstance(recipe, TechniqueRecipe): + return CreateTechniqueRequest.model_validate( + fields | recipe.model_dump(exclude_unset=True, exclude={"schema_version"}) + ) + fields |= {"type": recipe.class_name, "params": recipe.params} + if stored.ref.kind is RegistryRecipeKind.TARGETS: + if recipe.auth_mode is not None: + fields["auth_mode"] = recipe.auth_mode + return CreateTargetRequest.model_validate(fields) + if stored.ref.kind is RegistryRecipeKind.CONVERTERS: + return CreateConverterRequest.model_validate(fields) + return CreateScorerRequest.model_validate(fields) + except ValidationError as error: + problems = "; ".join( + f"{'.'.join(map(str, issue['loc'])) or 'request'}: {issue['msg']}" for issue in error.errors() + ) + raise RecipeRejectedError( + reason=RestoreFailureReason.INVALID_RECIPE, message=f"Not a valid create request: {problems}" + ) from error diff --git a/pyrit/registry/registry_recipe_restore.py b/pyrit/registry/registry_recipe_restore.py index 60bce5cb14..e892c207f8 100644 --- a/pyrit/registry/registry_recipe_restore.py +++ b/pyrit/registry/registry_recipe_restore.py @@ -189,9 +189,9 @@ def _log_failures(self, *, failures: Sequence[RestoreFailure], causes: Mapping[_ summary = f"Couldn't restore {subject} ({failure.reason.value}): {failure.message}" cause = causes.get((failure.kind, failure.name)) if cause is None: - logger.error(summary) + logger.error(redact_urls(summary)) else: - logger.error(f"{summary}\n{redact_urls(''.join(traceback.format_exception(cause))).rstrip()}") + logger.error(redact_urls(f"{summary}\n{''.join(traceback.format_exception(cause)).rstrip()}")) def _plan_all( self, diff --git a/pyrit/registry/registry_recipe_storage.py b/pyrit/registry/registry_recipe_storage.py index 4a0f1e7fb7..616f58ce58 100644 --- a/pyrit/registry/registry_recipe_storage.py +++ b/pyrit/registry/registry_recipe_storage.py @@ -14,7 +14,7 @@ from pydantic import ValidationError -from pyrit.common.azure_storage import is_azure_blob_uri +from pyrit.common.azure_storage import is_azure_blob_uri, redact_urls from pyrit.models.catalog import ( ComponentRecipe, IgnoredRecipeFile, @@ -81,7 +81,8 @@ class RecipeListing: recipes: Mapping[str, StoredRecipe] = field(default_factory=lambda: MappingProxyType({})) failures: tuple[RestoreFailure, ...] = () ignored: tuple[IgnoredRecipeFile, ...] = () - # The error behind each recipe that couldn't be read, by name, for the log only. + # For the log only, by name: the error behind each recipe that couldn't be read, and every problem with each + # one that isn't a valid recipe. causes: Mapping[str, BaseException] = field(default_factory=lambda: MappingProxyType({}), compare=False, repr=False) @@ -167,7 +168,7 @@ def list_recipes(self) -> RecipeListing: ] causes = {issue.name: issue.error for issue in listing.unreadable if issue.error is not None} for name, content in listing.documents.items(): - parsed = self._parse_recipe(name=name, content=content) + parsed = self._parse_recipe(name=name, content=content, causes=causes) if isinstance(parsed, RestoreFailure): failures.append(parsed) else: @@ -187,10 +188,18 @@ def list_recipes(self) -> RecipeListing: causes=MappingProxyType(causes), ) - def _parse_recipe(self, *, name: str, content: bytes) -> StoredRecipe | RestoreFailure: + def _parse_recipe( + self, *, name: str, content: bytes, causes: dict[str, BaseException] | None = None + ) -> StoredRecipe | RestoreFailure: """ Parse one stored document, checking its schema version before anything else. + Args: + name (str): The document's name. + content (bytes): The stored document. + causes (dict[str, BaseException] | None): Where to add, by name, every problem with a document that + isn't a valid recipe, for the log. Defaults to None, which adds nothing. + Returns: StoredRecipe | RestoreFailure: The recipe, or why it can't be used. """ @@ -230,6 +239,9 @@ def _parse_recipe(self, *, name: str, content: bytes) -> StoredRecipe | RestoreF # pydantic stops at a fixed depth and reports it as a recursion error, though a JSON file can't hold a loop. if any(issue["type"] == "recursion_loop" for issue in error.errors()): return self._failure(name=name, version=version, reason=invalid, message=too_deep) + if causes is not None: + # Not the error itself: its text repeats the stored values. + causes[name] = ValueError(self._describe_validation_error(error, full=True)) return self._failure( name=name, version=version, reason=invalid, message=self._describe_validation_error(error) ) @@ -250,20 +262,29 @@ def _failure( ) @staticmethod - def _describe_validation_error(error: ValidationError) -> str: + def _describe_validation_error(error: ValidationError, *, full: bool = False) -> str: """ - Summarize a validation error, naming each field and what's wrong with it, without the stored values. + Describe a validation error, naming each field and what's wrong with it, without the stored values. - A field's location can repeat a stored key, such as an unknown one, so each part of a location - is escaped and shortened. ``_failure`` shortens the whole summary. + A field's location can repeat a stored key, such as an unknown one, so each part of a location, and each + message, is escaped and loses any URL credentials. The summary also shortens each part of a location, and + ``_failure`` shortens the whole summary. The full description, for the log, keeps every location whole and + puts each problem on its own line. + + Args: + error (ValidationError): The error from checking the recipe. + full (bool): Whether to describe every problem in full, for the log. Defaults to False. Returns: - str: The summary. + str: The description. """ problems = [] - for issue in error.errors(): - location = ".".join( - shorten_text(escape_unprintable(str(part)), limit=_MAX_LOCATION_PART_LENGTH) for part in issue["loc"] - ) - problems.append(f"{location or 'document'}: {issue['msg']}") + for issue in error.errors(include_input=False, include_url=False, include_context=False): + # Credentials go before shortening, which could cut a URL before the end of its user name and password. + parts = [redact_urls(escape_unprintable(str(part))) for part in issue["loc"]] + if not full: + parts = [shorten_text(part, limit=_MAX_LOCATION_PART_LENGTH) for part in parts] + problems.append(f"{'.'.join(parts) or 'document'}: {redact_urls(escape_unprintable(issue['msg']))}") + if full: + return "Every problem in the file:\n" + "\n".join(f" {problem}" for problem in problems) return "Not a valid saved recipe: " + "; ".join(problems) diff --git a/pyrit/setup/configuration_loader.py b/pyrit/setup/configuration_loader.py index 63839d1f1a..da6e2aff56 100644 --- a/pyrit/setup/configuration_loader.py +++ b/pyrit/setup/configuration_loader.py @@ -115,6 +115,8 @@ class ConfigurationLoader(YamlLoadable): followed by a blob prefix, used to persist scenario presets. scenario_suites_source: Local directory or Azure Blob container URI, optionally followed by a blob prefix, used to persist scenario suites. + registry_recipes_source: Local directory or Azure Blob container URI, optionally + followed by a blob prefix, used to persist saved targets, converters, scorers, and techniques. silent: Whether to suppress initialization messages. seed: Optional root seed for deterministic converter operations. operator: Name for the current operator, e.g. a team or username. @@ -170,6 +172,7 @@ class ConfigurationLoader(YamlLoadable): custom_initializers_source: str | None = None scenario_presets_source: str | None = None scenario_suites_source: str | None = None + registry_recipes_source: str | None = None target_upload_directory: str | None = None server: dict[str, Any] | None = None extensions: dict[str, Any] = field(default_factory=dict) @@ -199,6 +202,7 @@ def __post_init__(self) -> None: self._validate_custom_initializers_source() self._validate_scenario_presets_source() self._validate_scenario_suites_source() + self._validate_registry_recipes_source() self._validate_target_upload_directory() self._normalize_server() @@ -239,6 +243,15 @@ def _validate_scenario_suites_source(self) -> None: """ self._validate_document_source(name="scenario_suites_source", value=self.scenario_suites_source) + def _validate_registry_recipes_source(self) -> None: + """ + Validate the optional storage source for saved registry entries. + + Raises: + ValueError: If the source is not a non-empty string. + """ + self._validate_document_source(name="registry_recipes_source", value=self.registry_recipes_source) + @staticmethod def _validate_document_source(*, name: str, value: Any) -> None: """ diff --git a/test_support/analytics_benchmark.py b/test_support/analytics_benchmark.py index 55208ed889..f1086765aa 100644 --- a/test_support/analytics_benchmark.py +++ b/test_support/analytics_benchmark.py @@ -65,6 +65,7 @@ def benchmark_directory(tmp_path: Path) -> Iterator[Path]: "initializers": ["technique"], "initialization_scripts": [], "custom_initializers_source": str(directory / "initializers"), + "registry_recipes_source": str(directory / "registry_recipes"), "silent": True, } ), diff --git a/tests/unit/backend/conftest.py b/tests/unit/backend/conftest.py index c015f8bf0c..bcea879c42 100644 --- a/tests/unit/backend/conftest.py +++ b/tests/unit/backend/conftest.py @@ -12,11 +12,14 @@ from pyrit.analytics import AttackResultAnalytics from pyrit.analytics._execution import AnalyticsExecution -from pyrit.backend.services import get_attack_service, get_dataset_service +from pyrit.backend.services import get_attack_service, get_converter_service, get_dataset_service, get_target_service from pyrit.backend.services.analytics_service import close_analytics_service_async, get_analytics_service from pyrit.backend.services.manual_send_scheduler import get_manual_send_scheduler from pyrit.backend.services.message_send_service import get_message_send_service +from pyrit.backend.services.scorer_service import get_scorer_service +from pyrit.backend.services.technique_service import get_technique_service from pyrit.memory import SQLiteMemory +from pyrit.registry.registry_recipe_storage import RegistryRecipeStorage from test_support.fixtures import authentication_policy, compatibility_headers, compatibility_id # noqa: F401 from unit.async_utils import TEST_WATCHDOG_SECONDS @@ -48,11 +51,30 @@ def managed_media_path(*, sqlite_instance: SQLiteMemory, patch_central_database: return path.resolve() +_ISOLATED_SERVICE_FACTORIES = ( + get_attack_service, + get_message_send_service, + get_manual_send_scheduler, + get_dataset_service, + get_target_service, + get_converter_service, + get_scorer_service, + get_technique_service, +) + + @pytest.fixture(autouse=True) def isolated_manual_message_services() -> Iterator[None]: - """Keep cached service owners bound to this test's memory and event loop.""" - for factory in (get_attack_service, get_message_send_service, get_manual_send_scheduler, get_dataset_service): + """Keep cached service owners bound to this test's memory, registries, and event loop.""" + for factory in _ISOLATED_SERVICE_FACTORIES: factory.cache_clear() yield - for factory in (get_attack_service, get_message_send_service, get_manual_send_scheduler, get_dataset_service): + for factory in _ISOLATED_SERVICE_FACTORIES: factory.cache_clear() + + +@pytest.fixture(autouse=True) +def isolated_saved_registry_entries(tmp_path: Path) -> Iterator[None]: + """Keep backend startup and apply from restoring entries saved on the machine running the tests.""" + with patch.object(RegistryRecipeStorage, "_get_default_storage_dir", return_value=tmp_path / "registry_recipes"): + yield diff --git a/tests/unit/backend/test_analytics_benchmark.py b/tests/unit/backend/test_analytics_benchmark.py index 9e5b75096c..8dcbb30e59 100644 --- a/tests/unit/backend/test_analytics_benchmark.py +++ b/tests/unit/backend/test_analytics_benchmark.py @@ -4,6 +4,7 @@ """Local SQLite smoke coverage and unit tests of the integration workload's failure gates.""" import asyncio +import json import os import subprocess import sys @@ -60,6 +61,12 @@ def measurements() -> AnalyticsBenchmark: return benchmark +def test_benchmark_configuration_keeps_saved_entries_in_its_own_folder(benchmark_directory: Path) -> None: + config = json.loads((benchmark_directory / "config.yaml").read_text(encoding="utf-8")) + + assert config["registry_recipes_source"] == str(benchmark_directory / "registry_recipes") + + @pytest.mark.timeout(120) @pytest.mark.usefixtures("semantic_analytics_budgets") @pytest.mark.parametrize("elapsed_report_seconds", [0.0, 31.0], ids=["normal", "expired-report-deadline"]) diff --git a/tests/unit/backend/test_runtime_lifecycle.py b/tests/unit/backend/test_runtime_lifecycle.py index 9330f62389..94c47971ac 100644 --- a/tests/unit/backend/test_runtime_lifecycle.py +++ b/tests/unit/backend/test_runtime_lifecycle.py @@ -4,12 +4,14 @@ """Admission and fail-fast runtime replacement invariants.""" import asyncio +import json +import logging import os -from collections.abc import Generator +from collections.abc import Callable, Generator from contextlib import ExitStack from datetime import UTC, datetime from pathlib import Path -from threading import Event +from threading import Event, Thread, current_thread from unittest.mock import AsyncMock, MagicMock, call, patch import httpx @@ -22,18 +24,36 @@ from pyrit.backend.middleware.auth import require_admin from pyrit.backend.middleware.runtime import RuntimeAdmissionMiddleware from pyrit.backend.routes import configuration, health -from pyrit.backend.services import ScenarioRunService +from pyrit.backend.services import ScenarioRunService, get_converter_service, get_target_service from pyrit.backend.services.configuration_file_service import ConfigurationFileService from pyrit.backend.services.manual_send_scheduler import get_manual_send_scheduler from pyrit.backend.services.runtime_lifecycle import RuntimeLifecycle from pyrit.backend.services.scenario_run_service import _PreparedRun +from pyrit.backend.services.scorer_service import get_scorer_service +from pyrit.backend.services.technique_service import get_technique_service from pyrit.memory import CentralMemory, MemoryInterface from pyrit.models import ScenarioRunState from pyrit.models.catalog import RunScenarioRequest +from pyrit.prompt_target import OpenAIChatTarget +from pyrit.registry import AttackTechniqueRegistry, ConverterRegistry, ScorerRegistry, TargetRegistry +from pyrit.registry.registry_recipe_restore import RegistryRecipeRestorer, SavedRecipes from pyrit.scenario import Scenario from pyrit.setup import ConfigurationLoader +from pyrit.setup.initialization import reset_setup_registries from unit.async_utils import TEST_WATCHDOG_SECONDS -from unit.mocks import make_scenario_result +from unit.mocks import MockPromptTarget, make_scenario_result + +_RESTORED_REGISTRIES = (TargetRegistry, ConverterRegistry, ScorerRegistry, AttackTechniqueRegistry) + + +@pytest.fixture(autouse=True) +def fresh_registries() -> Generator[None, None, None]: + """Start each test from the registries a new process has, as a real startup or apply does.""" + for registry in _RESTORED_REGISTRIES: + registry.reset_registry_singleton() + yield + for registry in _RESTORED_REGISTRIES: + registry.reset_registry_singleton() @pytest.fixture @@ -978,3 +998,381 @@ async def close_async() -> None: finally: release.set() await asyncio.gather(shutdown, return_exceptions=True) + + +def _save_recipe(root: Path, *, kind: str, name: str, document: dict[str, object]) -> Path: + folder = root / kind + folder.mkdir(parents=True, exist_ok=True) + path = folder / f"{name}.json" + path.write_text(json.dumps(document), encoding="utf-8") + return path + + +async def _start_with_recipes_async( + runtime: RuntimeLifecycle, *, recipes: Path, initialize: Callable[..., object] | None = None +) -> None: + config = await runtime._load_async() + config.registry_recipes_source = str(recipes) + with ( + patch.object(config, "initialize_pyrit_async", AsyncMock(side_effect=initialize)), + patch.object(lifecycle_module, "get_scenario_run_service", return_value=MagicMock(spec=ScenarioRunService)), + ): + await runtime.startup_async() + + +@pytest.fixture +def startup_chat() -> Generator[OpenAIChatTarget, None, None]: + TargetRegistry.reset_registry_singleton() + ConverterRegistry.reset_registry_singleton() + yield OpenAIChatTarget( + endpoint="https://startup.openai.azure.com/openai/v1", model_name="gpt-4o", auth_mode="identity" + ) + TargetRegistry.reset_registry_singleton() + ConverterRegistry.reset_registry_singleton() + + +def _save_converter_using_startup_chat(recipes: Path) -> None: + _save_recipe( + recipes, + kind="converters", + name="formal", + document={ + "class_module": "pyrit.converter.tone_converter", + "class_name": "ToneConverter", + "params": {"converter_target": "startup_chat", "tone": "formal"}, + }, + ) + + +@pytest.mark.usefixtures("patch_central_database") +async def test_startup_restores_an_entry_that_uses_a_startup_target_async( + runtime: RuntimeLifecycle, tmp_path: Path, startup_chat: OpenAIChatTarget +) -> None: + recipes = tmp_path / "recipes" + _save_converter_using_startup_chat(recipes) + targets = TargetRegistry.get_registry_singleton() + + await _start_with_recipes_async( + runtime, recipes=recipes, initialize=lambda **_: targets.instances.register(startup_chat, name="startup_chat") + ) + + assert (runtime.state, runtime.outcome) == ("ready", "success") + converter = ConverterRegistry.get_registry_singleton().instances.get("formal") + assert converter is not None + assert converter._converter_target is startup_chat + + +class _LoopBoundTarget(MockPromptTarget): + """A target whose constructor needs the running event loop, as HuggingFaceChatTarget's does.""" + + def __init__(self) -> None: + super().__init__() + self.loop = asyncio.get_running_loop() + + +@pytest.mark.usefixtures("patch_central_database", "startup_chat") +async def test_startup_builds_restored_entries_on_the_runtime_loop_async( + runtime: RuntimeLifecycle, tmp_path: Path +) -> None: + TargetRegistry.get_registry_singleton().register_class(_LoopBoundTarget) + recipes = tmp_path / "recipes" + _save_recipe( + recipes, + kind="targets", + name="loop_bound", + document={"class_module": _LoopBoundTarget.__module__, "class_name": "_LoopBoundTarget", "params": {}}, + ) + + await _start_with_recipes_async(runtime, recipes=recipes) + + assert (runtime.state, runtime.outcome) == ("ready", "success") + target = TargetRegistry.get_registry_singleton().instances.get("loop_bound") + assert isinstance(target, _LoopBoundTarget) + assert target.loop is asyncio.get_running_loop() + + +@pytest.mark.usefixtures("patch_central_database") +async def test_startup_reads_saved_entries_off_the_runtime_loop_async( + runtime: RuntimeLifecycle, tmp_path: Path +) -> None: + read = RegistryRecipeRestorer.read + read_threads: list[Thread] = [] + + def read_noting_thread(restorer: RegistryRecipeRestorer) -> SavedRecipes: + read_threads.append(current_thread()) + return read(restorer) + + with patch.object(RegistryRecipeRestorer, "read", read_noting_thread): + await _start_with_recipes_async(runtime, recipes=tmp_path / "recipes") + + assert (runtime.state, runtime.outcome) == ("ready", "success") + assert len(read_threads) == 1 + assert read_threads[0] is not current_thread() + + +async def _forget_registry_services_async() -> None: + """Stand in for close_services_async, which drops services bound to the registries an apply replaces.""" + for factory in (get_target_service, get_converter_service, get_scorer_service, get_technique_service): + factory.cache_clear() + + +@pytest.mark.usefixtures("patch_central_database") +async def test_apply_after_a_startup_restore_restores_the_same_entries_async( + runtime: RuntimeLifecycle, tmp_path: Path, startup_chat: OpenAIChatTarget +) -> None: + recipes = tmp_path / "recipes" + _save_converter_using_startup_chat(recipes) + _save_recipe( + recipes, + kind="scorers", + name="refusal", + document={ + "class_module": "pyrit.score.true_false.self_ask_refusal_scorer", + "class_name": "SelfAskRefusalScorer", + "params": {"chat_target": "startup_chat"}, + }, + ) + + def register_startup_chat(**_: object) -> None: + TargetRegistry.get_registry_singleton().instances.register(startup_chat, name="startup_chat") + + def reinitialize(**_: object) -> None: + reset_setup_registries() + register_startup_chat() + + await _start_with_recipes_async(runtime, recipes=recipes, initialize=register_startup_chat) + assert runtime.restore_failures == [] + config = await runtime._load_async() + config.apply_prepared_reinitialization_async.side_effect = reinitialize + lifecycle_module.close_services_async.side_effect = _forget_registry_services_async + + await apply_async(runtime) + + assert (runtime.state, runtime.outcome) == ("ready", "success") + assert runtime.restore_failures == [] + converter = ConverterRegistry.get_registry_singleton().instances.get("formal") + assert converter is not None + assert converter._converter_target is startup_chat + assert ScorerRegistry.get_registry_singleton().instances.get("refusal") is not None + + +class _UnreachableTarget(MockPromptTarget): + """A target whose constructor fails with a URL that carries a SAS token.""" + + def __init__(self) -> None: + raise ValueError("can't reach https://contoso.blob.core.windows.net/c?sv=2024&sig=SYNTHETIC-SAS") + + +@pytest.mark.usefixtures("patch_central_database") +async def test_startup_logs_each_failure_once_without_url_credentials_async( + runtime: RuntimeLifecycle, tmp_path: Path, caplog: pytest.LogCaptureFixture +) -> None: + TargetRegistry.get_registry_singleton().register_class(_UnreachableTarget) + recipes = tmp_path / "recipes" + _save_recipe( + recipes, + kind="targets", + name="unreachable", + document={"class_module": _UnreachableTarget.__module__, "class_name": "_UnreachableTarget", "params": {}}, + ) + _save_recipe(recipes, kind="targets", name="broken", document={"class_module": "nowhere", "class_name": "Nope"}) + + with caplog.at_level(logging.WARNING): + await _start_with_recipes_async(runtime, recipes=recipes) + + assert (runtime.state, runtime.outcome) == ("failed", "restore-failed") + for name in ("unreachable", "broken"): + assert len([record for record in caplog.records if f"target '{name}' (" in record.getMessage()]) == 1 + assert "can't reach https://contoso.blob.core.windows.net/c" in caplog.text + assert "sig=" not in caplog.text + assert "SYNTHETIC-SAS" not in caplog.text + + +async def test_startup_says_when_a_saved_folder_couldnt_be_read_async( + runtime: RuntimeLifecycle, tmp_path: Path, caplog: pytest.LogCaptureFixture +) -> None: + recipes = tmp_path / "recipes" + recipes.mkdir() + (recipes / "targets").write_text("a file where the folder should be") + + with caplog.at_level(logging.WARNING, logger="pyrit.backend.services.runtime_lifecycle"): + await _start_with_recipes_async(runtime, recipes=recipes) + + assert (runtime.state, runtime.outcome) == ("failed", "restore-failed") + assert runtime.message == ( + "The saved targets couldn't be read, so no saved entries were restored. Check that the backend can read " + "registry_recipes_source, then apply the configuration or restart the backend." + ) + assert runtime.message in caplog.text + assert "Fix or delete" not in caplog.text + + +async def test_startup_with_an_unrestorable_entry_is_not_ready_async( + runtime: RuntimeLifecycle, tmp_path: Path, caplog: pytest.LogCaptureFixture +) -> None: + recipes = tmp_path / "recipes" + _save_recipe(recipes, kind="targets", name="broken", document={"class_module": "nowhere", "class_name": "Nope"}) + + with caplog.at_level(logging.WARNING, logger="pyrit.backend.services.runtime_lifecycle"): + await _start_with_recipes_async(runtime, recipes=recipes) + + assert (runtime.state, runtime.outcome) == ("failed", "restore-failed") + assert runtime.message.startswith("1 saved registry entry couldn't be restored. Fix or delete the files") + assert runtime.message in caplog.text + async with httpx.AsyncClient(transport=httpx.ASGITransport(app=runtime.app), base_url="http://test") as client: + health = await client.get("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/api/health") + status = await client.get("/api/config/runtime") + assert health.json()["ready"] is False + assert status.json()["version"] == runtime.version + assert runtime.version is not None + (failure,) = status.json()["restore_failures"] + assert (failure["kind"], failure["name"], failure["reason"]) == ("targets", "broken", "unknown_class") + assert failure["version"] + + +async def test_status_reports_a_recipe_whose_text_is_not_valid_unicode_async( + runtime: RuntimeLifecycle, tmp_path: Path +) -> None: + recipes = tmp_path / "recipes" + _save_recipe( + recipes, + kind="targets", + name="pool", + document={ + "class_module": "pyrit.prompt_target.round_robin_target", + "class_name": "RoundRobinTarget", + "params": {"targets": ["missing\udcff"]}, + }, + ) + + await _start_with_recipes_async(runtime, recipes=recipes) + + async with httpx.AsyncClient(transport=httpx.ASGITransport(app=runtime.app), base_url="http://test") as client: + status = await client.get("/api/config/runtime") + assert status.status_code == 200 + (failure,) = status.json()["restore_failures"] + assert (failure["name"], failure["reason"]) == ("pool", "invalid_recipe") + + +async def test_status_lists_a_file_name_that_is_not_valid_text_async(runtime: RuntimeLifecycle, tmp_path: Path) -> None: + folder = tmp_path / "recipes" / "converters" + folder.mkdir(parents=True) + try: + (folder / os.fsdecode(b"bad\xffname.json")).write_text("{}") + except (OSError, UnicodeError): + pytest.skip("This file system only allows UTF-8 file names") + + await _start_with_recipes_async(runtime, recipes=tmp_path / "recipes") + + async with httpx.AsyncClient(transport=httpx.ASGITransport(app=runtime.app), base_url="http://test") as client: + status = await client.get("/api/config/runtime") + assert status.status_code == 200 + assert [item["file_name"] for item in status.json()["restore_ignored"]] == ["bad\\udcffname.json"] + + +async def test_startup_lists_ignored_files_without_blocking_readiness_async( + runtime: RuntimeLifecycle, tmp_path: Path +) -> None: + recipes = tmp_path / "recipes" + _save_recipe(recipes, kind="converters", name="Not-A-Name", document={}) + + await _start_with_recipes_async(runtime, recipes=recipes) + + assert runtime.state == "ready" + status = runtime.status() + assert status["restore_failures"] == [] + assert [(item["kind"], item["file_name"]) for item in status["restore_ignored"]] == [ + ("converters", "Not-A-Name.json") + ] + + +async def test_fixing_the_file_and_restarting_reaches_ready_async(runtime: RuntimeLifecycle, tmp_path: Path) -> None: + recipes = tmp_path / "recipes" + broken = _save_recipe(recipes, kind="scorers", name="broken", document={"schema_version": 99}) + await _start_with_recipes_async(runtime, recipes=recipes) + assert runtime.status()["restore_failures"][0]["reason"] == "newer_schema_version" + + broken.unlink() + await _start_with_recipes_async(runtime, recipes=recipes) + + assert (runtime.state, runtime.outcome) == ("ready", "success") + assert runtime.status()["restore_failures"] == [] + + +async def test_apply_with_an_unrestorable_entry_keeps_the_new_version_async( + runtime: RuntimeLifecycle, tmp_path: Path +) -> None: + recipes = tmp_path / "recipes" + _save_recipe(recipes, kind="techniques", name="broken", document={"type": "NoSuchAttack"}) + config = await runtime._load_async() + config.registry_recipes_source = str(recipes) + + await apply_async(runtime) + + _, current_version = await runtime.source.read_with_version_async() + assert (runtime.state, runtime.outcome) == ("failed", "restore-failed") + assert runtime.version == current_version + assert runtime.status()["restore_failures"][0]["reason"] == "unknown_class" + config.apply_prepared_reinitialization_async.assert_awaited_once() + + +@pytest.mark.usefixtures("patch_central_database") +async def test_apply_from_failed_restores_again_once_the_file_is_fixed_async( + runtime: RuntimeLifecycle, tmp_path: Path, startup_chat: OpenAIChatTarget +) -> None: + recipes = tmp_path / "recipes" + _save_converter_using_startup_chat(recipes) + broken = _save_recipe( + recipes, kind="targets", name="broken", document={"class_module": "nowhere", "class_name": "Nope"} + ) + + def register_startup_chat(**_: object) -> None: + TargetRegistry.get_registry_singleton().instances.register(startup_chat, name="startup_chat") + + def reinitialize(**_: object) -> None: + reset_setup_registries() + register_startup_chat() + + await _start_with_recipes_async(runtime, recipes=recipes, initialize=register_startup_chat) + assert (runtime.state, runtime.outcome) == ("failed", "restore-failed") + assert runtime.message.endswith("then apply the configuration or restart the backend.") + broken.unlink() + config = await runtime._load_async() + config.apply_prepared_reinitialization_async.side_effect = reinitialize + lifecycle_module.close_services_async.side_effect = _forget_registry_services_async + + await apply_async(runtime) + + assert (runtime.state, runtime.outcome) == ("ready", "success") + assert runtime.restore_failures == [] + assert ConverterRegistry.get_registry_singleton().instances.get("formal") is not None + + +async def test_apply_from_failed_without_live_apply_says_to_restart_async( + runtime: RuntimeLifecycle, tmp_path: Path +) -> None: + recipes = tmp_path / "recipes" + _save_recipe(recipes, kind="targets", name="broken", document={"class_module": "nowhere", "class_name": "Nope"}) + config = await runtime._load_async() + config.enable_live_reinitialization = False + + await _start_with_recipes_async(runtime, recipes=recipes) + assert (runtime.state, runtime.outcome) == ("failed", "restore-failed") + assert runtime.message.endswith("named in the server log or GET /api/config/runtime, then restart the backend.") + + await apply_async(runtime) + + assert (runtime.state, runtime.outcome) == ("failed", "unsupported") + assert runtime.message == "Live apply is off. Restart the backend to restore the saved entries again." + config.preflight_reinitialization_async.assert_not_awaited() + lifecycle_module.close_services_async.assert_not_awaited() + + +async def test_restore_cancellation_propagates_from_startup_async(runtime: RuntimeLifecycle, tmp_path: Path) -> None: + runtime.state = "initializing" + + with patch.object(RegistryRecipeRestorer, "read", side_effect=asyncio.CancelledError): + with pytest.raises(asyncio.CancelledError): + await _start_with_recipes_async(runtime, recipes=tmp_path / "recipes") + + assert runtime.state == "initializing" diff --git a/tests/unit/backend/test_saved_entry_restore.py b/tests/unit/backend/test_saved_entry_restore.py new file mode 100644 index 0000000000..dde2721798 --- /dev/null +++ b/tests/unit/backend/test_saved_entry_restore.py @@ -0,0 +1,176 @@ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT license. + +import json +import os +import sys +from collections.abc import Iterator +from functools import partial +from pathlib import Path +from types import ModuleType +from typing import Any +from unittest.mock import patch + +import pytest + +from pyrit.backend.services.saved_entry_restore import build_saved_entry_async +from pyrit.models.catalog import RegistryRecipeKind, RegistryRestoreReport, RestoreFailureReason +from pyrit.prompt_target import HTTPXAPITarget, OpenAIChatTarget +from pyrit.registry import AttackTechniqueRegistry, ConverterRegistry, ScorerRegistry, TargetRegistry +from pyrit.registry.registry_recipe_restore import RegistryRecipeRestorer + +_IDENTITY_TARGET = { + "class_module": "pyrit.prompt_target.openai.openai_chat_target", + "class_name": "OpenAIChatTarget", + "auth_mode": "identity", + "params": {"endpoint": "https://contoso.openai.azure.com/openai/v1", "model_name": "gpt-4o"}, +} +_REGISTRIES = (TargetRegistry, ConverterRegistry, ScorerRegistry, AttackTechniqueRegistry) + + +@pytest.fixture(autouse=True) +def isolated_registries() -> Iterator[None]: + for registry in _REGISTRIES: + registry.reset_registry_singleton() + yield + for registry in _REGISTRIES: + registry.reset_registry_singleton() + + +def _save(root: Path, kind: RegistryRecipeKind, name: str, document: dict[str, Any]) -> None: + folder = root / kind.value + folder.mkdir(parents=True, exist_ok=True) + (folder / f"{name}.json").write_text(json.dumps(document)) + + +async def _restore(root: Path, *, upload_directory: str | None = None) -> RegistryRestoreReport: + build_async = partial(build_saved_entry_async, upload_directory=upload_directory) + return await RegistryRecipeRestorer(source=str(root)).restore_async(build_async=build_async) + + +@pytest.mark.usefixtures("patch_central_database") +async def test_restores_each_kind_through_its_create(tmp_path: Path) -> None: + _save(tmp_path, RegistryRecipeKind.TARGETS, "contoso_gpt4o", _IDENTITY_TARGET) + _save( + tmp_path, + RegistryRecipeKind.CONVERTERS, + "tone_formal", + { + "class_module": "pyrit.converter.tone_converter", + "class_name": "ToneConverter", + "params": {"converter_target": "contoso_gpt4o", "tone": "formal"}, + }, + ) + _save( + tmp_path, + RegistryRecipeKind.SCORERS, + "refusal", + { + "class_module": "pyrit.score.true_false.self_ask_refusal_scorer", + "class_name": "SelfAskRefusalScorer", + "params": {"chat_target": "contoso_gpt4o"}, + }, + ) + _save( + tmp_path, + RegistryRecipeKind.TECHNIQUES, + "formal_red_team", + { + "type": "RedTeamingAttack", + "params": {"max_turns": 5}, + "tags": ["custom"], + "adversarial_chat": "contoso_gpt4o", + "adversarial_system_prompt": "You are a red teaming assistant.", + "request_converters": ["tone_formal"], + }, + ) + + report = await _restore(tmp_path) + + assert report.failures == [] + target = TargetRegistry.get_registry_singleton().instances.get("contoso_gpt4o") + assert isinstance(target, OpenAIChatTarget) + assert target._auth_mode == "identity" + converter = ConverterRegistry.get_registry_singleton().instances.get("tone_formal") + assert converter is not None + assert converter._converter_target is target + assert ScorerRegistry.get_registry_singleton().instances.get("refusal") is not None + factory = AttackTechniqueRegistry.get_registry_singleton().instances.get("formal_red_team") + assert factory is not None + assert factory.technique_tags == ["custom"] + + +@pytest.mark.usefixtures("patch_central_database") +async def test_a_target_its_create_refuses_fails_only_that_entry(tmp_path: Path) -> None: + _save( + tmp_path, + RegistryRecipeKind.TARGETS, + "copilot", + { + "class_module": "pyrit.prompt_target.github_copilot_target", + "class_name": "GitHubCopilotTarget", + "params": {"model_name": "gpt-5-mini"}, + }, + ) + _save(tmp_path, RegistryRecipeKind.TARGETS, "contoso_gpt4o", _IDENTITY_TARGET) + + with patch.dict(sys.modules, {"copilot": ModuleType("copilot")}), patch.dict(os.environ, {"GITHUB_TOKEN": ""}): + report = await _restore(tmp_path) + + (failure,) = report.failures + assert (failure.name, failure.reason) == ("copilot", RestoreFailureReason.BUILD_ERROR) + assert "GitHub Copilot requires a GitHub token" in failure.message + assert [ref.name for ref in report.restored] == ["contoso_gpt4o"] + + +@pytest.mark.usefixtures("patch_central_database") +async def test_a_target_that_uploads_files_gets_this_servers_upload_folder(tmp_path: Path) -> None: + uploads = tmp_path / "uploads" + uploads.mkdir() + recipes = tmp_path / "recipes" + _save( + recipes, + RegistryRecipeKind.TARGETS, + "uploader", + { + "class_module": "pyrit.prompt_target.http_target.httpx_api_target", + "class_name": "HTTPXAPITarget", + "params": {"http_url": "https://example.test/upload"}, + }, + ) + + report = await _restore(recipes, upload_directory=str(uploads)) + + assert report.failures == [] + target = TargetRegistry.get_registry_singleton().instances.get("uploader") + assert isinstance(target, HTTPXAPITarget) + assert target.allowed_upload_directory == uploads.resolve() + + +@pytest.mark.usefixtures("patch_central_database") +async def test_a_target_that_uploads_files_fails_where_the_server_sets_no_upload_folder(tmp_path: Path) -> None: + _save( + tmp_path, + RegistryRecipeKind.TARGETS, + "uploader", + { + "class_module": "pyrit.prompt_target.http_target.httpx_api_target", + "class_name": "HTTPXAPITarget", + "params": {"http_url": "https://example.test/upload"}, + }, + ) + + (failure,) = (await _restore(tmp_path)).failures + + assert (failure.name, failure.reason) == ("uploader", RestoreFailureReason.BUILD_ERROR) + assert "target_upload_directory" in failure.message + + +async def test_a_technique_its_create_request_refuses_is_invalid(tmp_path: Path) -> None: + _save(tmp_path, RegistryRecipeKind.TECHNIQUES, "types", {"type": "RedTeamingAttack"}) + + (failure,) = (await _restore(tmp_path)).failures + + assert (failure.name, failure.reason) == ("types", RestoreFailureReason.INVALID_RECIPE) + assert failure.message.startswith("Not a valid create request: name:") + assert "types" not in AttackTechniqueRegistry.get_registry_singleton().instances.get_names() diff --git a/tests/unit/registry/test_registry_recipe_restore.py b/tests/unit/registry/test_registry_recipe_restore.py index 74cf3a5593..4eef924a28 100644 --- a/tests/unit/registry/test_registry_recipe_restore.py +++ b/tests/unit/registry/test_registry_recipe_restore.py @@ -531,6 +531,52 @@ async def test_logs_each_failure_once_with_its_traceback_and_without_url_credent assert len([record for record in caplog.records if "target 'pool' (" in record.getMessage()]) == 1 assert "SECRET" not in caplog.text + async def test_logs_every_problem_with_a_file_that_is_not_valid_in_full( + self, tmp_path: Path, caplog: pytest.LogCaptureFixture + ) -> None: + many_keys = [f"unknown_{index:03d}_{'x' * 40}" for index in range(100)] + twins = ["p" * 70 + "_alpha", "p" * 70 + "_beta"] + _save(tmp_path, RegistryRecipeKind.TARGETS, "many_keys", {**_IDENTITY_TARGET, **dict.fromkeys(many_keys, True)}) + _save(tmp_path, RegistryRecipeKind.TARGETS, "twins", {**_IDENTITY_TARGET, **dict.fromkeys(twins, True)}) + + with caplog.at_level("ERROR", logger="pyrit.registry.registry_recipe_restore"): + report = await _restore(tmp_path) + + messages = {failure.name: failure.message for failure in report.failures} + assert len(messages["many_keys"]) == MAX_FAILURE_MESSAGE_LENGTH + for name, keys in (("many_keys", many_keys), ("twins", twins)): + (record,) = [record for record in caplog.records if f"target '{name}' (" in record.getMessage()] + lines = record.getMessage().splitlines() + assert all(f" {key}: Extra inputs are not permitted" in lines for key in keys) + + async def test_logs_the_problems_of_a_file_escaped_and_without_stored_values_or_url_credentials( + self, tmp_path: Path, caplog: pytest.LogCaptureFixture + ) -> None: + url_key = "https://user:pw-token@acct.blob.core.windows.net/c/x.json?sv=2024&sig=sas-token#frag-token" + long_url_key = f"https://user:{'longpw' * 20}@host/path?sig=sas-token" + document = { + **_IDENTITY_TARGET, + "schema_version": "STORED-VALUE", + url_key: True, + long_url_key: True, + "\n\x1b[31mFAKE": True, + } + _save(tmp_path, RegistryRecipeKind.TARGETS, "unsafe", document) + + with caplog.at_level("ERROR", logger="pyrit.registry.registry_recipe_restore"): + report = await _restore(tmp_path) + + (record,) = [record for record in caplog.records if "target 'unsafe' (" in record.getMessage()] + lines = record.getMessage().splitlines() + assert " schema_version: Input should be a valid integer" in lines + assert " https://acct.blob.core.windows.net/c/x.json: Extra inputs are not permitted" in lines + assert " https://host/path: Extra inputs are not permitted" in lines + assert " \\n\\x1b[31mFAKE: Extra inputs are not permitted" in lines + assert all(line.isprintable() for line in lines) + for hidden in ("STORED-VALUE", "pw-token", "longpw", "sig=", "sas-token", "frag-token"): + assert hidden not in caplog.text + assert hidden not in report.model_dump_json() + async def test_reports_a_reference_name_that_is_not_valid_text_as_invalid(self, tmp_path: Path) -> None: _save_text( tmp_path, diff --git a/tests/unit/setup/test_configuration_loader.py b/tests/unit/setup/test_configuration_loader.py index cebcc16eda..ccabb22c18 100644 --- a/tests/unit/setup/test_configuration_loader.py +++ b/tests/unit/setup/test_configuration_loader.py @@ -87,6 +87,25 @@ def test_scenario_suites_source_rejects_invalid_value(self, invalid_value: objec with pytest.raises(ValueError, match="scenario_suites_source"): ConfigurationLoader(scenario_suites_source=invalid_value) # type: ignore[arg-type] + def test_registry_recipes_source_loads_from_yaml(self, tmp_path: pathlib.Path) -> None: + """Test loading an Azure Blob container URI for saved registry entries.""" + config_path = tmp_path / "config.yaml" + config_path.write_text( + "registry_recipes_source: https://account.blob.core.windows.net/pyrit-storage/registry-recipes\n", + encoding="utf-8", + ) + + config = ConfigurationLoader.from_yaml_file(config_path) + + assert config.registry_recipes_source == "https://account.blob.core.windows.net/pyrit-storage/registry-recipes" + assert ConfigurationLoader().registry_recipes_source is None + + @pytest.mark.parametrize("invalid_value", ["", " ", 42]) + def test_registry_recipes_source_rejects_invalid_value(self, invalid_value: object) -> None: + """Test rejecting empty or non-string sources for saved registry entries.""" + with pytest.raises(ValueError, match="registry_recipes_source"): + ConfigurationLoader(registry_recipes_source=invalid_value) # type: ignore[arg-type] + def test_target_upload_directory_loads_from_yaml(self, tmp_path: pathlib.Path) -> None: config_path = tmp_path / "config.yaml" config_path.write_text("target_upload_directory: /srv/uploads\n", encoding="utf-8")