diff --git a/doc/getting_started/pyrit_conf.md b/doc/getting_started/pyrit_conf.md index 326a8151de..dd1a3cf4a9 100644 --- a/doc/getting_started/pyrit_conf.md +++ b/doc/getting_started/pyrit_conf.md @@ -220,7 +220,7 @@ A SAS query string may be included; otherwise, PyRIT uses `DefaultAzureCredentia ### `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. Targets created through `POST /api/targets` with `"persist": true` are saved here. An Azure URI may include a blob-name prefix: +Stores saved targets, converters, scorers, and techniques in a local directory or Azure Blob container, so they come back when the backend restarts. Targets, converters, and scorers created through `POST /api/targets`, `POST /api/converters`, and `POST /api/scorers` with `"persist": true` are saved here. An Azure URI may include a blob-name prefix: ```yaml registry_recipes_source: https://account.blob.core.windows.net/pyrit-storage/registry-recipes @@ -232,7 +232,7 @@ Each kind has its own folder under the source (`targets/`, `converters/`, `score Restore can't tell who wrote a saved file, even one that names the user 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`), 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. Administrators see each failure with its reason in `GET /api/config/runtime` and on the GUI's Configuration page; everyone else sees that an administrator has to fix saved entries. 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 and the backend runs as one worker and one replica, which live apply requires; otherwise, restart the backend. Files whose names aren't valid entry names (up to 64 lowercase letters, digits, and underscores, starting with a letter) aren't failures and don't block startup; administrators can see them under `restore_ignored` in `GET /api/config/runtime`. +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`), so a scan can't quietly run without an entry it expects. Until then, only the configuration, status and saved-entry routes answer; the rest return 503. Administrators see each failure with its reason in `GET /api/config/runtime` and on the GUI's Configuration page, where they can fix the listed files or delete them with **Delete** (`DELETE /api/saved-entries/{kind}/{name}`); everyone else sees that an administrator has to fix saved entries. 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 and the backend runs as one worker and one replica, which live apply requires; otherwise, restart the backend. Files whose names aren't valid entry names (up to 64 lowercase letters, digits, and underscores, starting with a letter) aren't failures and don't block startup; administrators can see them under `restore_ignored` in `GET /api/config/runtime`. #### Saved entry requirements diff --git a/doc/gui/0_gui.md b/doc/gui/0_gui.md index 8c1760e39e..07f9837de3 100644 --- a/doc/gui/0_gui.md +++ b/doc/gui/0_gui.md @@ -205,6 +205,18 @@ members; defaults, visibility, and the target's configuration columns remain available. Converter inputs and outputs stay visible in the table. Use the small red X to remove a converter from the live registry; confirmation is required. +**Delete** on a saved target, converter, scorer, or technique deletes its saved +file and removes it from the registry, so it doesn't come back after a restart. +Saved entries are shared, so only an administrator can delete one, as for +scenario presets. In local mode that needs `PYRIT_ALLOW_UNAUTHENTICATED_ADMIN=true`. +An entry that another saved entry +uses, or that a registered entry holds, isn't deleted until that one is deleted +or changed, and an entry isn't deleted while a run, send, or request could be +using it. If the file changed since the dialog read it, **Look again** shows the +current one. A saved entry that couldn't be restored keeps PyRIT from becoming +ready; an administrator can delete it from the list on the **Configuration** +page, then select **Reinitialize PyRIT** or restart the backend. + **Scenario presets** save a scenario configuration for reuse with a target chosen at launch. **Suites** maintain ordered collections of preset definitions. They are stored separately from live component instances. @@ -221,8 +233,7 @@ is reinitialized. Give it a registry name of lowercase letters, digits, and underscores that starts with a letter; the dialog suggests one from the target type and model. Saved targets are kept in `registry_recipes_source` (`~/.pyrit/registry_recipes` unless set in your `.pyrit_conf`). To remove a saved -target, delete its file (`targets/.json`) there, and the file of any saved -round robin that uses it, then restart the backend. If a startup initializer later +target, select **Delete** on its row in the Targets table. If a startup initializer later registers a target under a saved target's name, the saved one isn't restored and the backend isn't ready until that file is renamed or removed and the backend restarted. Before that restart, update or remove the file of each saved round @@ -239,8 +250,22 @@ A Temporary target is gone after the backend restarts or is reinitialized. The Targets table labels each target **Saved**, **From configuration** (registered by an initializer at startup), or **Temporary**. -Converters and techniques added only to the live registry must be recreated -after a backend restart or reinitialization. Use +New converters are saved the same way, wherever you add one: **New Converter** in +the Converters tab, the converter panel in chat, or **New converter** in the +technique editor. The dialog suggests a name such as `base64_converter`. A +converter type that needs an uploaded file, a converter with an uploaded file, or +one that uses a Temporary target is created as **Temporary** instead, and the +dialog says why. +**Save to registry** on a converter's changed settings, in chat or in a technique +edit, makes a Temporary copy. The Converters and Scorers tables use the same three +labels; scorers can be saved through the API. + +**New technique** saves the technique the same way. Give it a registry name of +lowercase letters, digits, and underscores that starts with a letter. A technique +that uses a Temporary converter or a Temporary adversarial target is created as +**Temporary** instead, and the dialog says why. Settings changed for a single run +in Scanner stay with that run. The Techniques table uses the same three labels. To +remove a saved technique, select **Delete** next to its name. Use [initializers](../code/setup/0_setup.md) for repeatable component setup. Use **Auto-detect capabilities** to select targets and run live checks. Results diff --git a/frontend/e2e/registry.spec.ts b/frontend/e2e/registry.spec.ts index 06aab85e9b..eb09e06fb3 100644 --- a/frontend/e2e/registry.spec.ts +++ b/frontend/e2e/registry.spec.ts @@ -73,15 +73,18 @@ test("creates and selects a runtime technique with the real backend @seeded", as await requestConverters.click(); await page.getByTestId(`converter-option-${converterName}`).click(); } + // The converter was created without saving it, so the technique can only be Temporary. + await expect(page.getByRole("dialog").getByText(`Uses temporary converter '${converterName}'`)).toBeVisible(); const create = page.waitForResponse((response) => response.url().endsWith("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/api/techniques") && response.request().method() === "POST"); - await page.getByRole("button", { name: "Add technique" }).click(); + await page.getByRole("button", { name: "Create as Temporary" }).click(); const created = await create; expect(created.status()).toBe(201); const createdTechnique = await created.json(); + expect(createdTechnique.origin).toBe("temporary"); const body = created.request().postDataJSON(); expect(body).toMatchObject({ name, type: "PromptSendingAttack", params: { max_attempts_on_failure: 0 }, - request_converters: [converterName, converterName], response_converters: [], + request_converters: [converterName, converterName], response_converters: [], persist: false, }); expect(body).not.toHaveProperty("factory_options"); expect(body).not.toHaveProperty("seed_technique"); @@ -118,7 +121,7 @@ test("creates and selects a runtime technique with the real backend @seeded", as await page.getByRole("button", { name: "New technique" }).click(); await page.getByRole("textbox", { name: "Registry name" }).fill("old_runtime_response"); await page.getByRole("combobox", { name: "Attack type", exact: true }).selectOption("PromptSendingAttack"); - await page.getByRole("button", { name: "Add technique" }).click(); + await page.getByRole("button", { name: "Save technique" }).click(); await createStarted; replacementGeneration = "registry-replacement-test"; await expect(page.getByRole("dialog")).not.toBeVisible(); @@ -142,6 +145,59 @@ test("creates and selects a runtime technique with the real backend @seeded", as expect(promptRequests).toEqual([]); }); +test("saves a technique from the New technique dialog and still lists it as Saved after a reload @seeded", async ({ page, request }) => { + const name = `saved_send_${Date.now()}`; + await page.goto("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/registry/techniques"); + await page.getByRole("button", { name: "New technique" }).click(); + const dialog = page.getByRole("dialog"); + await dialog.getByRole("textbox", { name: "Registry name" }).fill(name); + await dialog.getByRole("textbox", { name: "Description" }).fill("Saved from the browser"); + await dialog.getByRole("combobox", { name: "Attack type", exact: true }).selectOption("PromptSendingAttack"); + await expect(dialog.getByText("This technique can't be saved")).toHaveCount(0); + await dialog.getByRole("button", { name: "Save technique" }).click(); + await expect(dialog).toHaveCount(0); + + await page.getByRole("textbox", { name: "Search techniques" }).fill(name); + const row = page.getByRole("row", { name: new RegExp(name) }); + await expect(row.getByText("Saved", { exact: true })).toBeVisible(); + const saved = await request.get(`/api/techniques/${name}`, { headers: compatibilityHeaders() }); + expect(saved.ok(), await saved.text()).toBe(true); + expect((await saved.json()).origin).toBe("saved"); + + await page.reload(); + await page.getByRole("textbox", { name: "Search techniques" }).fill(name); + await expect(page.getByRole("row", { name: new RegExp(name) }).getByText("Saved", { exact: true })).toBeVisible(); +}); + +test("saves a converter from the New Converter dialog and still lists it as Saved after a reload @seeded", async ({ page, request }) => { + const name = `saved_caesar_${Date.now()}`; + await page.goto("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/registry/converters"); + await page.getByRole("button", { name: "New Converter" }).click(); + const dialog = page.getByRole("dialog"); + await dialog.getByRole("combobox", { name: "Converter type" }).click(); + await page.getByTestId("converter-type-option-CaesarConverter").click(); + await expect(dialog.getByRole("textbox", { name: "Registry name", exact: true })).toHaveValue(/^caesar_converter/); + await dialog.getByRole("textbox", { name: "Registry name", exact: true }).fill(name); + await dialog.getByRole("textbox", { name: "caesar_offset *", exact: true }).fill("5"); + await expect(dialog.getByText("This converter can't be saved")).toHaveCount(0); + await dialog.getByRole("button", { name: "Save Converter" }).click(); + await expect(dialog).toHaveCount(0); + + const row = page.getByRole("row", { name: new RegExp(name) }); + await expect(row.getByText("Saved", { exact: true })).toBeVisible(); + // A saved converter is deleted through its saved file, not removed from the live registry. + await expect(row.getByRole("button", { name: `Delete saved converter ${name}` })).toBeEnabled(); + await expect(row.getByRole("button", { name: `Remove ${name}` })).toHaveCount(0); + const saved = await request.get(`/api/converters/${name}`, { headers: compatibilityHeaders() }); + expect(saved.ok(), await saved.text()).toBe(true); + expect((await saved.json()).origin).toBe("saved"); + const removal = await request.delete(`/api/converters/${name}`, { headers: compatibilityHeaders() }); + expect(removal.status()).toBe(409); + + await page.reload(); + await expect(page.getByRole("row", { name: new RegExp(name) }).getByText("Saved", { exact: true })).toBeVisible(); +}); + test("saves a target from the New Target dialog and still lists it as Saved after a reload @seeded", async ({ page, request }) => { const name = `saved_chat_${Date.now()}`; await page.goto("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/registry/targets"); @@ -168,6 +224,38 @@ test("saves a target from the New Target dialog and still lists it as Saved afte await expect(page.getByTestId(`target-row-${name}`).getByText("Saved", { exact: true })).toBeVisible(); }); +test("deletes a saved target from the Targets table so it doesn't come back @seeded", async ({ page, request }) => { + const headers = compatibilityHeaders(); + const name = `deleted_chat_${Date.now()}`; + const created = await request.post("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/api/targets", { + headers, + data: { + name, + type: "OpenAIChatTarget", + params: { endpoint: "http://127.0.0.1:9/v1", model_name: "local-test" }, + auth_mode: "none", + persist: true, + }, + }); + expect(created.ok(), await created.text()).toBe(true); + + await page.goto("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/registry/targets"); + const row = page.getByTestId(`target-row-${name}`); + await expect(row.getByText("Saved", { exact: true })).toBeVisible(); + await row.getByRole("button", { name: `Delete saved target ${name}` }).click(); + const dialog = page.getByRole("dialog", { name: `Delete saved target '${name}'?` }); + await expect(dialog.getByText(/deleted for everyone/)).toBeVisible(); + await dialog.getByRole("button", { name: "Delete" }).click(); + await expect(dialog).toHaveCount(0); + await expect(row).toHaveCount(0); + + expect((await request.get(`/api/targets/${name}`, { headers })).status()).toBe(404); + expect((await request.get(`/api/saved-entries/targets/${name}`, { headers })).status()).toBe(404); + await page.reload(); + await expect(page.getByRole("button", { name: "New Target", exact: true })).toBeVisible(); + await expect(page.getByTestId(`target-row-${name}`)).toHaveCount(0); +}); + interface RegisteredConverter { converter_id: string; identifier: { @@ -180,6 +268,7 @@ interface RegisteredConverter { }; is_llm_based: boolean; description?: string; + origin?: "saved" | "configuration" | "temporary"; } const CONVERTER_TYPES = { @@ -219,6 +308,15 @@ const CONVERTER_TYPES = { is_llm_based: true, description: "Rewrites prompts.", }, + { + converter_type: "TemporaryOnlyConverter", + supported_input_types: ["text"], + supported_output_types: ["text"], + parameters: [], + is_llm_based: false, + description: "A converter type that can't be saved.", + not_saveable_reason: "It needs an uploaded file, which saved converters can't keep yet.", + }, ...Array.from({ length: 16 }, (_, index) => ({ converter_type: `ViewportConverter${index}`, supported_input_types: ["text"], @@ -294,6 +392,14 @@ async function installRegistryMocks(page: Page): Promise { return; } const converterId = decodeURIComponent(route.request().url().split("/").pop() ?? ""); + if (registeredConverters.some((converter) => converter.converter_id === converterId && converter.origin === "saved")) { + await route.fulfill({ + status: 409, + contentType: "application/json", + body: JSON.stringify({ detail: `Saved converter '${converterId}' can't be removed yet.` }), + }); + return; + } registeredConverters = registeredConverters.filter( (converter) => converter.converter_id !== converterId, ); @@ -325,6 +431,7 @@ async function installRegistryMocks(page: Page): Promise { }, is_llm_based: converterType?.is_llm_based ?? false, description: converterType?.description, + origin: body.persist ? "saved" : "temporary", }; registeredConverters.push(converter); await route.fulfill({ @@ -349,7 +456,7 @@ async function submitDuplicateName(page: Page): Promise<() => void> { status: 409, contentType: "application/json", body: JSON.stringify({ - detail: "Converter instance 'caesar-custom' already exists", + detail: "Converter instance 'caesar_custom' already exists", }), }); }); @@ -357,9 +464,9 @@ async function submitDuplicateName(page: Page): Promise<() => void> { await page.getByRole("button", { name: "Create First Converter" }).click(); await page.getByRole("combobox", { name: "Converter type" }).click(); await page.getByTestId("converter-type-option-CaesarConverter").click(); - await page.getByRole("textbox", { name: "Registry name", exact: true }).fill("caesar-custom"); + await page.getByRole("textbox", { name: "Registry name", exact: true }).fill("caesar_custom"); await page.getByRole("textbox", { name: "caesar_offset *", exact: true }).fill("5"); - await page.getByRole("button", { name: "Add Converter" }).click(); + await page.getByRole("button", { name: "Save Converter" }).click(); await expect(page.getByRole("button", { name: "Adding..." })).toBeVisible(); return () => releaseCreate?.(); @@ -370,7 +477,15 @@ async function createCaesarConverter(page: Page, name: string): Promise { await page.getByTestId("converter-type-option-CaesarConverter").click(); await page.getByRole("textbox", { name: "Registry name", exact: true }).fill(name); await page.getByRole("textbox", { name: "caesar_offset *", exact: true }).fill("5"); - await page.getByRole("button", { name: "Add Converter" }).click(); + await page.getByRole("button", { name: "Save Converter" }).click(); +} + +async function createTemporaryConverter(page: Page, name: string): Promise { + await page.getByRole("combobox", { name: "Converter type" }).click(); + await page.getByTestId("converter-type-option-TemporaryOnlyConverter").click(); + await page.getByRole("textbox", { name: "Registry name", exact: true }).fill(name); + await expect(page.getByRole("status")).toContainText("This converter can't be saved"); + await page.getByRole("button", { name: "Create as Temporary" }).click(); } async function submitSlowCreate(page: Page, name: string): Promise<() => void> { @@ -404,25 +519,38 @@ test.describe("Converter Registry", () => { await page.goto("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/registry/converters"); }); - test("adds and removes a named converter without an active action", async ({ page }) => { + test("adds and removes a Temporary converter without an active action", async ({ page }) => { await expect(page.getByRole("heading", { name: "Converter Registry" })).toBeVisible(); await expect(page.getByRole("region", { name: "Target defaults" })).toHaveCount(0); await page.getByRole("button", { name: "New Converter" }).click(); - await page.getByRole("combobox", { name: "Converter type" }).click(); - await page.getByTestId("converter-type-option-CaesarConverter").click(); - await page.getByRole("textbox", { name: "Registry name", exact: true }).fill("caesar-custom"); - await page.getByRole("textbox", { name: "caesar_offset *", exact: true }).fill("5"); - await page.getByRole("button", { name: "Add Converter" }).click(); + await createTemporaryConverter(page, "temporary_custom"); - await expect(page.getByText("caesar-custom")).toBeVisible(); - await page.getByRole("button", { name: "Remove caesar-custom" }).click(); + const row = page.getByRole("row", { name: /temporary_custom/ }); + await expect(row.getByText("Temporary", { exact: true })).toBeVisible(); + await page.getByRole("button", { name: "Remove temporary_custom" }).click(); await page.getByRole("button", { name: "Remove", exact: true }).click(); - await expect(page.getByText("caesar-custom")).toHaveCount(0); + await expect(page.getByText("temporary_custom")).toHaveCount(0); await expect(page.getByText("No Converters Registered")).toBeVisible(); }); + test("saves a named converter and offers to delete its saved file instead of removing it", async ({ page }) => { + await page.getByRole("button", { name: "New Converter" }).click(); + const createRequest = page.waitForRequest( + (request) => request.method() === "POST" && /\/api\/converters$/.test(request.url()), + ); + await createCaesarConverter(page, "caesar_custom"); + + expect((await createRequest).postDataJSON()).toEqual({ + name: "caesar_custom", type: "CaesarConverter", params: { caesar_offset: 5 }, persist: true, + }); + const row = page.getByRole("row", { name: /caesar_custom/ }); + await expect(row.getByText("Saved", { exact: true })).toBeVisible(); + await expect(row.getByRole("button", { name: "Delete saved converter caesar_custom" })).toBeEnabled(); + await expect(row.getByRole("button", { name: "Remove caesar_custom" })).toHaveCount(0); + }); + test("restores focus to the trigger when the add dialog is dismissed", async ({ page }) => { const trigger = page.getByRole("button", { name: "New Converter" }); await trigger.click(); @@ -439,13 +567,13 @@ test.describe("Converter Registry", () => { await page.getByRole("button", { name: "Create First Converter" }).click(); await page.getByRole("combobox", { name: "Converter type" }).click(); await page.getByTestId("converter-type-option-CaesarConverter").click(); - await page.getByRole("textbox", { name: "Registry name", exact: true }).fill("caesar-focus"); + await page.getByRole("textbox", { name: "Registry name", exact: true }).fill("caesar_focus"); await page.getByRole("textbox", { name: "caesar_offset *", exact: true }).fill("5"); - await page.getByRole("button", { name: "Add Converter" }).click(); + await page.getByRole("button", { name: "Save Converter" }).click(); // The empty-state trigger unmounts with the list it belonged to, so focus // falls back to the always-mounted header action. - await expect(page.getByText("caesar-focus")).toBeVisible(); + await expect(page.getByText("caesar_focus")).toBeVisible(); await expect(page.getByRole("button", { name: "New Converter" })).toBeFocused(); }); @@ -463,13 +591,12 @@ test.describe("Converter Registry", () => { release(); }); - test("moves focus to the error when the registry rejects the name", async ({ page }) => { + test("moves focus to the name when the registry says it is taken", async ({ page }) => { const release = await submitDuplicateName(page); release(); - const alert = page.getByRole("alert"); - await expect(alert).toContainText(/already exists/i); - await expect(alert).toBeFocused(); + await expect(page.getByRole("alert")).toContainText(/already exists/i); + await expect(page.getByRole("textbox", { name: "Registry name", exact: true })).toBeFocused(); // Escape only reaches the dialog surface while focus is still inside it. await page.keyboard.press("Escape"); @@ -478,20 +605,20 @@ test.describe("Converter Registry", () => { test("leaves the removal dialog in place when a dismissed creation succeeds", async ({ page }) => { await page.getByRole("button", { name: "Create First Converter" }).click(); - await createCaesarConverter(page, "caesar-first"); - await expect(page.getByText("caesar-first")).toBeVisible(); + await createTemporaryConverter(page, "temporary_first"); + await expect(page.getByText("temporary_first")).toBeVisible(); - const release = await submitSlowCreate(page, "caesar-late"); + const release = await submitSlowCreate(page, "caesar_late"); await page.keyboard.press("Escape"); await expect(page.getByRole("dialog")).toBeHidden(); - const removeTrigger = page.getByRole("button", { name: "Remove caesar-first" }); + const removeTrigger = page.getByRole("button", { name: "Remove temporary_first" }); await removeTrigger.click(); const removeDialog = page.getByRole("dialog"); await expect(removeDialog).toBeVisible(); release(); - await expect(page.getByText("caesar-late")).toBeVisible(); + await expect(page.getByText("caesar_late")).toBeVisible(); // Moving focus out makes Tabster mark the still-visible dialog aria-hidden, // and Escape then stops dismissing it, so the late response has to leave @@ -516,7 +643,7 @@ test.describe("Converter Registry", () => { // The request settles either way; only its failure is dropped, so the // reopened dialog keeps the empty form the user opened. - await expect(dialog.getByRole("button", { name: "Add Converter" })).toBeEnabled(); + await expect(dialog.getByRole("button", { name: "Save Converter" })).toBeEnabled(); await expect(page.getByRole("alert")).toHaveCount(0); await expect(dialog.getByRole("textbox", { name: "Registry name", exact: true })).toHaveValue(""); }); diff --git a/frontend/playwright.config.ts b/frontend/playwright.config.ts index 547d6b29e3..4fb3557588 100644 --- a/frontend/playwright.config.ts +++ b/frontend/playwright.config.ts @@ -140,7 +140,8 @@ export default defineConfig({ `cd .. && uv run --no-sync python -m pyrit.backend.pyrit_backend ` + `--auth-mode local --host 127.0.0.1 --port ${E2E_BACKEND_PORT} --log-level warning ` + `--config-file "${SEEDED_BACKEND_CONFIG_FILE}"`, - env: { PYRIT_DEV_MODE: "true" }, + // Deleting a saved entry takes an administrator, as on a trusted local development server. + env: { PYRIT_DEV_MODE: "true", PYRIT_ALLOW_UNAUTHENTICATED_ADMIN: "true" }, url: `${E2E_BACKEND_URL}/api/health`, reuseExistingServer: false, timeout: 120_000, diff --git a/frontend/src/components/Config/CreateTargetDialog.tsx b/frontend/src/components/Config/CreateTargetDialog.tsx index d64a61235f..4bb70f6e0f 100644 --- a/frontend/src/components/Config/CreateTargetDialog.tsx +++ b/frontend/src/components/Config/CreateTargetDialog.tsx @@ -47,7 +47,7 @@ import { targetType as getTargetType, targetUnderlyingModelName, } from '@/utils/targetIdentity' -import { TARGET_ORIGIN_LABELS } from '@/utils/targetOrigin' +import { ORIGIN_LABELS } from '@/utils/registryOrigin' import { useCreateTargetDialogStyles } from './CreateTargetDialog.styles' import { canConfigureTargetType, @@ -1061,7 +1061,7 @@ export default function CreateTargetDialog({ open, onClose, onCreated, existingT ))} @@ -1084,7 +1084,7 @@ export default function CreateTargetDialog({ open, onClose, onCreated, existingT ) const selectedTargetLabel = `${target?.target_registry_name ?? sel.registryName}${ target && targetModelName(target) ? ` (${targetModelName(target)})` : '' - }${target?.origin === 'temporary' ? ` · ${TARGET_ORIGIN_LABELS.temporary}` : ''}` + }${target?.origin === 'temporary' ? ` · ${ORIGIN_LABELS.temporary}` : ''}` const weightParse = parseWeight(sel.weightInput) const weightError = weightParse.ok ? null : weightParse.error return ( diff --git a/frontend/src/components/Config/TargetConfig.test.tsx b/frontend/src/components/Config/TargetConfig.test.tsx index 50b115b0a8..401616da22 100644 --- a/frontend/src/components/Config/TargetConfig.test.tsx +++ b/frontend/src/components/Config/TargetConfig.test.tsx @@ -6,7 +6,7 @@ import { useTargetCapabilityDetection } from "@/hooks/useTargetCapabilityDetecti import { makeTarget } from "@/test-utils/targetFixtures"; import TargetConfigView from "./TargetConfig"; import { advanceAutoRefresh, installAutoRefreshTimers } from "@/test-utils/autoRefresh"; -import { targetsApi } from "../../services/api"; +import { savedEntriesApi, targetsApi } from "../../services/api"; import type { TargetInstance, TargetListResponse } from "../../types"; installAutoRefreshTimers(); @@ -16,6 +16,10 @@ jest.mock("../../services/api", () => ({ createTarget: jest.fn(), detectCapabilities: jest.fn(), }, + savedEntriesApi: { + get: jest.fn(), + delete: jest.fn(), + }, })); let mockRuntimeGeneration = "generation-1"; @@ -59,6 +63,7 @@ jest.mock("./CreateTargetDialog", () => { }); const mockedTargetsApi = targetsApi as jest.Mocked; +const mockedSavedEntriesApi = savedEntriesApi as jest.Mocked; const TestWrapper: React.FC<{ children: React.ReactNode }> = ({ children, @@ -404,6 +409,31 @@ describe("TargetConfig", () => { expect(onSetDefaultAdversarialTarget).toHaveBeenCalledWith(sampleTargets[0]); }); + it("should move focus to New Target after a saved target is deleted", async () => { + const user = userEvent.setup(); + const saved = makeTarget({ target_registry_name: "saved_chat", target_type: "OpenAIChatTarget", origin: "saved" }); + mockedTargetsApi.listTargets + .mockResolvedValueOnce({ items: [saved, ...sampleTargets], pagination: { limit: 200, has_more: false } }) + .mockResolvedValue({ items: sampleTargets, pagination: { limit: 200, has_more: false } }); + mockedSavedEntriesApi.get.mockResolvedValue({ + kind: "targets", name: "saved_chat", version: "v1", problem: null, + can_change: true, + }); + mockedSavedEntriesApi.delete.mockResolvedValue(); + + render( + + + + ); + await user.click(await screen.findByRole("button", { name: "Delete saved target saved_chat" })); + const dialog = await screen.findByRole("dialog", { name: "Delete saved target 'saved_chat'?" }); + await user.click(await within(dialog).findByRole("button", { name: "Delete" })); + + await waitFor(() => expect(screen.queryByText("saved_chat")).not.toBeInTheDocument()); + expect(screen.getByRole("button", { name: "New Target" })).toHaveFocus(); + }); + it("should show the adversarial default without an objective default control", async () => { mockedTargetsApi.listTargets.mockResolvedValue({ items: sampleTargets, diff --git a/frontend/src/components/Config/TargetConfig.tsx b/frontend/src/components/Config/TargetConfig.tsx index 8f7ba7f4a5..3f02c88627 100644 --- a/frontend/src/components/Config/TargetConfig.tsx +++ b/frontend/src/components/Config/TargetConfig.tsx @@ -7,6 +7,7 @@ import { MessageBar, MessageBarBody, Spinner, + useRestoreFocusTarget, } from '@fluentui/react-components' import { AddRegular } from '@fluentui/react-icons' import ContextualHelpLabel from '@/components/ContextualHelpLabel' @@ -62,6 +63,9 @@ export default function TargetConfig({ useEffect(() => { detectionRef.current = detection }, [detection]) const pending = useRef(false) const [refetchCount, setRefetchCount] = useState(0) + const restoreFocusTarget = useRestoreFocusTarget() + const newTargetButton = useRef(null) + const [focusRestore, setFocusRestore] = useState(0) // Retry fetching targets a few times with backoff. The Vite dev proxy // returns 502 while the backend is still starting, so a single failed @@ -110,6 +114,16 @@ export default function TargetConfig({ }, []) useAutoRefresh(() => { if (!pending.current) fetchTargets() }, ready && !loading && !detecting) + useEffect(() => { + if (focusRestore) newTargetButton.current?.focus() + }, [focusRestore]) + + const handleTargetDeleted = useCallback(() => { + // The deleted target's row is about to unmount, so focus goes to New Target. + setFocusRestore((current) => current + 1) + fetchTargets() + }, [fetchTargets]) + const handleTargetCreated = useCallback(() => { setDialogOpen(false) fetchTargets() @@ -130,6 +144,8 @@ export default function TargetConfig({
+ {target.origin === 'saved' && onTargetDeleted && ( + + )} } @@ -642,7 +654,7 @@ export default function TargetTable({ nameContent={ (target.origin || isDefaultAdversarial(target)) && (
- {target.origin && } + {target.origin && } {isDefaultAdversarial(target) && ( Adversarial diff --git a/frontend/src/components/Configuration/Reinitialize.test.tsx b/frontend/src/components/Configuration/Reinitialize.test.tsx index a40635f3fc..96a140e5ff 100644 --- a/frontend/src/components/Configuration/Reinitialize.test.tsx +++ b/frontend/src/components/Configuration/Reinitialize.test.tsx @@ -4,7 +4,7 @@ import { FluentProvider, webLightTheme } from '@fluentui/react-components' import { act, cleanup, render, screen, waitFor, within } from '@testing-library/react' import userEvent from '@testing-library/user-event' -import { configurationApi } from '@/services/api' +import { configurationApi, savedEntriesApi } from '@/services/api' import type { RuntimeStatus } from '@/types' import Reinitialize from './Reinitialize' @@ -14,6 +14,7 @@ jest.mock('@/services/api', () => ({ getRuntimeStatus: jest.fn(), reinitialize: jest.fn(), }, + savedEntriesApi: { get: jest.fn(), delete: jest.fn() }, })) function TestWrapper({ children }: { children: ReactNode }) { @@ -192,6 +193,57 @@ describe('Reinitialize', () => { expect(region).toHaveAttribute('tabindex', '0') }) + it('should let an administrator delete a saved entry that could not be restored', async () => { + const user = userEvent.setup() + const ghost = { + kind: 'targets' as const, + name: 'ghost', + reason: 'unknown_class', + message: "'Nope' is not a registered target class.", + version: 'v1', + dependency: null, + } + const folder = { + kind: 'converters' as const, + name: null, + reason: 'unreadable_storage', + message: "The saved converters couldn't be listed: permission denied", + version: null, + dependency: null, + } + api.getRuntimeStatus.mockResolvedValue({ + ...ready, + state: 'failed', + outcome: 'restore-failed', + message: "2 saved registry entries couldn't be restored.", + restore_failures: [ghost, folder], + }) + jest.mocked(savedEntriesApi.get).mockResolvedValue({ + kind: 'targets', name: 'ghost', version: 'v1', problem: 'unknown_class', + can_change: true, + }) + jest.mocked(savedEntriesApi.delete).mockResolvedValue() + render( + + + , + ) + + const region = await screen.findByRole('region', { name: "Saved entries that couldn't be restored" }) + // A folder that couldn't be read isn't one saved entry, so it has nothing to delete. + expect(within(region).getAllByRole('button').map((button) => button.getAttribute('aria-label'))).toEqual([ + 'Delete saved target ghost', + ]) + await user.click(within(region).getByRole('button', { name: 'Delete saved target ghost' })) + const dialog = await screen.findByRole('dialog', { name: "Delete saved target 'ghost'?" }) + await within(dialog).findByText(/deleted for everyone/) + api.getRuntimeStatus.mockResolvedValue({ ...ready, state: 'failed', restore_failures: [folder] }) + await user.click(within(dialog).getByRole('button', { name: 'Delete' })) + + expect(savedEntriesApi.delete).toHaveBeenCalledWith('targets', 'ghost', 'v1') + await waitFor(() => expect(within(region).queryByText(/Target ghost/)).not.toBeInTheDocument()) + }) + it('should show no list when every saved entry was restored', async () => { api.getRuntimeStatus.mockResolvedValue({ ...ready, restore_failures: [] }) render( diff --git a/frontend/src/components/Configuration/RestoreFailures.styles.ts b/frontend/src/components/Configuration/RestoreFailures.styles.ts index cacf3e052f..c1c46f704b 100644 --- a/frontend/src/components/Configuration/RestoreFailures.styles.ts +++ b/frontend/src/components/Configuration/RestoreFailures.styles.ts @@ -1,4 +1,4 @@ -import { makeStyles } from '@fluentui/react-components' +import { makeStyles, tokens } from '@fluentui/react-components' export const useRestoreFailuresStyles = makeStyles({ // The page doesn't scroll past the editor, so a long list scrolls on its own. It fills its column, and a long @@ -12,4 +12,7 @@ export const useRestoreFailuresStyles = makeStyles({ overflowWrap: 'anywhere', overflowY: 'auto', }, + delete: { + marginLeft: tokens.spacingHorizontalS, + }, }) diff --git a/frontend/src/components/Configuration/RestoreFailures.tsx b/frontend/src/components/Configuration/RestoreFailures.tsx index 7cf08c6b4b..38f759dc41 100644 --- a/frontend/src/components/Configuration/RestoreFailures.tsx +++ b/frontend/src/components/Configuration/RestoreFailures.tsx @@ -1,3 +1,4 @@ +import DeleteSavedEntryButton from '@/components/Registry/DeleteSavedEntryButton' import type { RegistryRecipeKind, RestoreFailure } from '@/types' import { useRestoreFailuresStyles } from './RestoreFailures.styles' @@ -34,7 +35,18 @@ export default function RestoreFailures({ failures }: RestoreFailuresProps) { >
    {failures.map((failure) => ( -
  • {describeFailure(failure)}
  • +
  • + {describeFailure(failure)} + {failure.name !== null && ( + {}} + /> + )} +
  • ))}
diff --git a/frontend/src/components/Converters/SaveConverterDialog.test.tsx b/frontend/src/components/Converters/SaveConverterDialog.test.tsx index 0e8ea02fd0..5e18733c2b 100644 --- a/frontend/src/components/Converters/SaveConverterDialog.test.tsx +++ b/frontend/src/components/Converters/SaveConverterDialog.test.tsx @@ -28,6 +28,15 @@ describe('SaveConverterDialog', () => { jest.mocked(convertersApi.createConverter).mockResolvedValue(saved) }) + it('should say the copy is Temporary, since a copy cannot be saved yet', () => { + render(tree()) + + expect( + screen.getByText(/The new converter is Temporary: it's gone after the backend restarts or is reinitialized\./), + ).toBeInTheDocument() + expect(screen.queryByText(/available until the backend restarts/)).not.toBeInTheDocument() + }) + it('should require a name before creating a registry entry', async () => { const user = userEvent.setup() render(tree()) diff --git a/frontend/src/components/Converters/SaveConverterDialog.tsx b/frontend/src/components/Converters/SaveConverterDialog.tsx index d6c58dca7b..5b926b3e12 100644 --- a/frontend/src/components/Converters/SaveConverterDialog.tsx +++ b/frontend/src/components/Converters/SaveConverterDialog.tsx @@ -71,7 +71,7 @@ export default function SaveConverterDialog({ void save() }}> Save these settings under a new name. The original converter stays unchanged. - Saved converters are available until the backend restarts. + The new converter is Temporary: it's gone after the backend restarts or is reinitialized. {error && {error} } diff --git a/frontend/src/components/Registry/ConverterRegistry.test.tsx b/frontend/src/components/Registry/ConverterRegistry.test.tsx index 5727550202..2f56d90fac 100644 --- a/frontend/src/components/Registry/ConverterRegistry.test.tsx +++ b/frontend/src/components/Registry/ConverterRegistry.test.tsx @@ -2,7 +2,7 @@ import { act, render, screen, waitFor, within } from '@testing-library/react' import userEvent from '@testing-library/user-event' import { FluentProvider, webLightTheme } from '@fluentui/react-components' -import { convertersApi } from '@/services/api' +import { convertersApi, savedEntriesApi } from '@/services/api' import ConverterRegistry from './ConverterRegistry' import { advanceAutoRefresh, installAutoRefreshTimers } from '@/test-utils/autoRefresh' @@ -14,6 +14,10 @@ jest.mock('@/services/api', () => ({ listConverters: jest.fn(), deleteConverter: jest.fn(), }, + savedEntriesApi: { + get: jest.fn(), + delete: jest.fn(), + }, })) // Holds the onCreated of the render that "started" a slow create, the way an @@ -133,6 +137,53 @@ describe('ConverterRegistry', () => { expect(screen.queryByRole('button', { name: /set active/i })).not.toBeInTheDocument() }) + it('labels each converter with where it comes from', async () => { + mockedConvertersApi.listConverters.mockResolvedValue({ + items: [ + { ...converter, converter_id: 'saved_base64', origin: 'saved' }, + { ...converter, converter_id: 'startup_base64', origin: 'configuration' }, + { ...converter, converter_id: 'launch_base64', origin: 'temporary' }, + { ...converter, converter_id: 'unlabeled_base64' }, + ], + }) + renderRegistry() + + const table = await screen.findByRole('table', { name: 'Converter instances' }) + const row = (name: string) => within(table).getByRole('row', { name: new RegExp(name) }) + expect(within(row('saved_base64')).getByText('Saved')).toBeInTheDocument() + expect(within(row('startup_base64')).getByText('From configuration')).toBeInTheDocument() + expect(within(row('launch_base64')).getByText('Temporary')).toBeInTheDocument() + expect(within(row('unlabeled_base64')).queryByText(/Saved|From configuration|Temporary/)).not.toBeInTheDocument() + }) + + it('deletes a saved converter through its saved file and loads the list again', async () => { + const user = userEvent.setup() + mockedConvertersApi.listConverters.mockResolvedValue({ + items: [ + { ...converter, converter_id: 'saved_base64', origin: 'saved' }, + { ...converter, converter_id: 'launch_base64', origin: 'temporary' }, + ], + }) + jest.mocked(savedEntriesApi.get).mockResolvedValue({ + kind: 'converters', name: 'saved_base64', version: 'v1', problem: null, can_change: true, + }) + jest.mocked(savedEntriesApi.delete).mockResolvedValue() + renderRegistry() + + expect(await screen.findByRole('button', { name: 'Remove launch_base64' })).toBeInTheDocument() + expect(screen.queryByRole('button', { name: 'Remove saved_base64' })).not.toBeInTheDocument() + await user.click(screen.getByRole('button', { name: 'Delete saved converter saved_base64' })) + const dialog = await screen.findByRole('dialog', { name: "Delete saved converter 'saved_base64'?" }) + await within(dialog).findByText(/deleted for everyone/) + const calls = mockedConvertersApi.listConverters.mock.calls.length + await user.click(within(dialog).getByRole('button', { name: 'Delete' })) + + expect(savedEntriesApi.delete).toHaveBeenCalledWith('converters', 'saved_base64', 'v1') + expect(mockedConvertersApi.deleteConverter).not.toHaveBeenCalled() + await waitFor(() => expect(mockedConvertersApi.listConverters.mock.calls.length).toBeGreaterThan(calls)) + await waitFor(() => expect(screen.getByRole('button', { name: 'New Converter' })).toHaveFocus()) + }) + it('filters by name, type, and output without changing the registered instances', async () => { const audio = { ...converter, converter_id: 'speech', diff --git a/frontend/src/components/Registry/ConverterRegistry.tsx b/frontend/src/components/Registry/ConverterRegistry.tsx index 175f11442b..5e07a345e2 100644 --- a/frontend/src/components/Registry/ConverterRegistry.tsx +++ b/frontend/src/components/Registry/ConverterRegistry.tsx @@ -36,6 +36,8 @@ import { toApiError } from '@/services/errors' import type { ConverterInstance } from '@/types' import CreateConverterDialog from './CreateConverterDialog' +import DeleteSavedEntryButton from './DeleteSavedEntryButton' +import OriginBadge from './OriginBadge' import { useConverterRegistryPageStyles } from './ConverterRegistry.styles' import RegistryIdentityRow from './RegistryIdentityRow' import { useConverterRegistryStyles } from './Registry.styles' @@ -339,7 +341,7 @@ export default function ConverterRegistry() { - The registry name used to select this configured converter. + The registry name used to select this configured converter. Saved converters come back after the backend restarts or is reinitialized, converters from configuration come back because the server registers them again, and Temporary converters are gone. The converter class that performs the transformation. Content types this converter accepts. Content types this converter can produce. @@ -350,7 +352,8 @@ export default function ConverterRegistry() { {visible.map((converter: ConverterInstance) => ( toggleDetails(converter.converter_id)}> + onToggle={() => toggleDetails(converter.converter_id)} + nameContent={converter.origin && }>
{converter.identifier.class_name} @@ -364,15 +367,29 @@ export default function ConverterRegistry() { - diff --git a/frontend/src/components/Registry/DeleteSavedEntryButton.styles.ts b/frontend/src/components/Registry/DeleteSavedEntryButton.styles.ts new file mode 100644 index 0000000000..6ffa75d100 --- /dev/null +++ b/frontend/src/components/Registry/DeleteSavedEntryButton.styles.ts @@ -0,0 +1,10 @@ +import { makeStyles, tokens } from '@fluentui/react-components' + +export const useDeleteSavedEntryStyles = makeStyles({ + content: { + display: 'flex', + flexDirection: 'column', + gap: tokens.spacingVerticalS, + overflowWrap: 'anywhere', + }, +}) diff --git a/frontend/src/components/Registry/DeleteSavedEntryButton.test.tsx b/frontend/src/components/Registry/DeleteSavedEntryButton.test.tsx new file mode 100644 index 0000000000..c379eed358 --- /dev/null +++ b/frontend/src/components/Registry/DeleteSavedEntryButton.test.tsx @@ -0,0 +1,122 @@ +import { FluentProvider, webLightTheme } from '@fluentui/react-components' +import { render, screen, waitFor, within } from '@testing-library/react' +import userEvent from '@testing-library/user-event' +import { AxiosError, AxiosHeaders } from 'axios' + +import { savedEntriesApi } from '@/services/api' +import type { SavedEntry } from '@/types' + +import DeleteSavedEntryButton from './DeleteSavedEntryButton' + +jest.mock('@/services/api', () => ({ + savedEntriesApi: { get: jest.fn(), delete: jest.fn() }, +})) + +const mockedApi = savedEntriesApi as jest.Mocked + +const ENTRY: SavedEntry = { + kind: 'converters', + name: 'cat_replace', + version: 'v1', + problem: null, + can_change: true, +} + +function apiError(status: number, detail: string): AxiosError { + const headers = new AxiosHeaders() + return new AxiosError('Request failed', 'ERR_BAD_REQUEST', { headers }, null, { + status, statusText: '', headers: {}, config: { headers }, data: { detail }, + }) +} + +async function openDialog(onDeleted = jest.fn()) { + const user = userEvent.setup() + render( + + + , + ) + await user.click(screen.getByRole('button', { name: 'Delete saved converter cat_replace' })) + const dialog = await screen.findByRole('dialog', { name: "Delete saved converter 'cat_replace'?" }) + return { user, dialog, onDeleted } +} + +describe('DeleteSavedEntryButton', () => { + beforeEach(() => { jest.clearAllMocks() }) + + it('deletes the version it showed', async () => { + mockedApi.get.mockResolvedValue(ENTRY) + mockedApi.delete.mockResolvedValue() + const { user, dialog, onDeleted } = await openDialog() + + expect(await within(dialog).findByText(/deleted for everyone and doesn't come back after the backend restarts/)) + .toBeInTheDocument() + await user.click(within(dialog).getByRole('button', { name: 'Delete' })) + + expect(mockedApi.delete).toHaveBeenCalledWith('converters', 'cat_replace', 'v1') + await waitFor(() => expect(onDeleted).toHaveBeenCalledTimes(1)) + expect(screen.queryByRole('dialog')).not.toBeInTheDocument() + }) + + it("says that only an administrator can delete it when the person asking isn't one", async () => { + mockedApi.get.mockResolvedValue({ ...ENTRY, can_change: false }) + const { dialog } = await openDialog() + + expect(await within(dialog).findByText('Only an administrator can delete it.')).toBeInTheDocument() + expect(within(dialog).getByRole('button', { name: 'Delete' })).toBeDisabled() + }) + + it("deletes a file that can't be read without a version", async () => { + mockedApi.get.mockResolvedValue({ ...ENTRY, version: null, problem: 'unreadable_recipe' }) + mockedApi.delete.mockResolvedValue() + const { user, dialog } = await openDialog() + + expect(await within(dialog).findByText("Its saved file can't be used, so it's deleted as it is.")).toBeInTheDocument() + await user.click(within(dialog).getByRole('button', { name: 'Delete' })) + + expect(mockedApi.delete).toHaveBeenCalledWith('converters', 'cat_replace', null) + }) + + it('shows why a delete was refused and keeps the dialog open', async () => { + mockedApi.get.mockResolvedValue(ENTRY) + const detail = "Saved converter 'cat_replace' is used by saved technique 'formal_send'. Delete or change it first." + mockedApi.delete.mockRejectedValue(apiError(409, detail)) + const { user, dialog, onDeleted } = await openDialog() + await within(dialog).findByText(/deleted for everyone/) + + await user.click(within(dialog).getByRole('button', { name: 'Delete' })) + + expect(await within(dialog).findByRole('alert')).toHaveTextContent(detail) + expect(onDeleted).not.toHaveBeenCalled() + expect(within(dialog).queryByRole('button', { name: 'Look again' })).not.toBeInTheDocument() + expect(within(dialog).getByRole('button', { name: 'Delete' })).toBeEnabled() + }) + + it('looks at a file again after it changed, and deletes its new version', async () => { + mockedApi.get.mockResolvedValueOnce(ENTRY).mockResolvedValueOnce({ ...ENTRY, version: 'v2' }) + mockedApi.delete + .mockRejectedValueOnce(apiError(409, "Saved converter 'cat_replace' changed since it was read. Look at it again before deleting it.")) + .mockResolvedValueOnce() + const { user, dialog, onDeleted } = await openDialog() + await within(dialog).findByText(/deleted for everyone/) + + await user.click(within(dialog).getByRole('button', { name: 'Delete' })) + const lookAgain = await within(dialog).findByRole('button', { name: 'Look again' }) + // The version it showed is stale, so it can't be deleted until it's looked at again. + expect(within(dialog).getByRole('button', { name: 'Delete' })).toBeDisabled() + await user.click(lookAgain) + await waitFor(() => expect(within(dialog).getByRole('button', { name: 'Delete' })).toBeEnabled()) + await user.click(within(dialog).getByRole('button', { name: 'Delete' })) + + expect(mockedApi.delete).toHaveBeenLastCalledWith('converters', 'cat_replace', 'v2') + await waitFor(() => expect(onDeleted).toHaveBeenCalledTimes(1)) + }) + + it("can't delete what it couldn't look up", async () => { + mockedApi.get.mockRejectedValue(apiError(404, "No saved converter is named 'cat_replace'.")) + const { dialog } = await openDialog() + + expect(await within(dialog).findByRole('alert')).toHaveTextContent("No saved converter is named 'cat_replace'.") + expect(within(dialog).getByRole('button', { name: 'Delete' })).toBeDisabled() + }) +}) diff --git a/frontend/src/components/Registry/DeleteSavedEntryButton.tsx b/frontend/src/components/Registry/DeleteSavedEntryButton.tsx new file mode 100644 index 0000000000..176af51f48 --- /dev/null +++ b/frontend/src/components/Registry/DeleteSavedEntryButton.tsx @@ -0,0 +1,164 @@ +import { useEffect, useState } from 'react' + +import { + Button, + Dialog, + DialogActions, + DialogBody, + DialogContent, + DialogSurface, + DialogTitle, + MessageBar, + MessageBarBody, + Spinner, + Text, +} from '@fluentui/react-components' +import { DeleteRegular } from '@fluentui/react-icons' + +import { savedEntriesApi } from '@/services/api' +import { toApiError } from '@/services/errors' +import type { RegistryRecipeKind, SavedEntry } from '@/types' + +import { useDeleteSavedEntryStyles } from './DeleteSavedEntryButton.styles' + +const SINGULAR: Record = { + targets: 'target', + converters: 'converter', + scorers: 'scorer', + techniques: 'technique', +} + +interface DeleteSavedEntryDialogProps { + kind: RegistryRecipeKind + name: string + onClose: () => void + onDeleted: () => void +} + +function DeleteSavedEntryDialog({ kind, name, onClose, onDeleted }: DeleteSavedEntryDialogProps) { + const styles = useDeleteSavedEntryStyles() + const singular = SINGULAR[kind] + const [entry, setEntry] = useState(null) + const [loadError, setLoadError] = useState(null) + const [deleteError, setDeleteError] = useState(null) + // A file that changed since it was read can be looked at again, which also offers its new version. + const [changed, setChanged] = useState(false) + const [deleting, setDeleting] = useState(false) + const [reads, setReads] = useState(0) + + useEffect(() => { + let cancelled = false + savedEntriesApi.get(kind, name) + .then((loaded) => { if (!cancelled) setEntry(loaded) }) + .catch((error: unknown) => { if (!cancelled) setLoadError(toApiError(error).detail) }) + return () => { cancelled = true } + }, [kind, name, reads]) + + const readAgain = () => { + setEntry(null) + setLoadError(null) + setDeleteError(null) + setChanged(false) + setReads((count) => count + 1) + } + + const remove = async () => { + if (!entry) return + setDeleting(true) + setDeleteError(null) + try { + await savedEntriesApi.delete(kind, name, entry.version) + onDeleted() + } catch (error) { + const apiError = toApiError(error) + setDeleteError(apiError.detail) + setChanged(apiError.status === 409 && apiError.detail.includes('changed since it was read')) + } finally { + setDeleting(false) + } + } + + + return ( + { if (!data.open && !deleting) onClose() }}> + + + {`Delete saved ${singular} '${name}'?`} + + {!entry && !loadError && } + {loadError && ( +
+ {loadError} +
+ )} + {entry && ( + <> + It's deleted for everyone and doesn't come back after the backend restarts. + {entry.problem && Its saved file can't be used, so it's deleted as it is.} + {!entry.can_change && Only an administrator can delete it.} + + )} + {deleteError && ( +
+ {deleteError} +
+ )} +
+ + {changed && } + + + +
+
+
+ ) +} + +interface DeleteSavedEntryButtonProps { + kind: RegistryRecipeKind + name: string + /** Called once the saved file is deleted, so the list can be loaded again. */ + onDeleted: () => void + /** Show only the icon, for a row's actions column. */ + iconOnly?: boolean + className?: string +} + +/** A button that deletes a saved entry's file, after a dialog that says whether you may. */ +export default function DeleteSavedEntryButton({ + kind, name, onDeleted, iconOnly = false, className, +}: DeleteSavedEntryButtonProps) { + const [open, setOpen] = useState(false) + return ( + <> + + {open && ( + setOpen(false)} + onDeleted={() => { + setOpen(false) + onDeleted() + }} + /> + )} + + ) +} diff --git a/frontend/src/components/Registry/OriginBadge.tsx b/frontend/src/components/Registry/OriginBadge.tsx new file mode 100644 index 0000000000..725110e276 --- /dev/null +++ b/frontend/src/components/Registry/OriginBadge.tsx @@ -0,0 +1,23 @@ +import { Badge, type BadgeProps } from '@fluentui/react-components' + +import type { RegistryEntryOrigin } from '@/types' +import { ORIGIN_LABELS } from '@/utils/registryOrigin' + +const ORIGIN_BADGE_COLORS: Record = { + saved: 'success', + configuration: 'informative', + temporary: 'warning', +} + +interface OriginBadgeProps { + readonly origin: RegistryEntryOrigin +} + +/** Shows whether a registry entry comes back after a restart: Saved, From configuration, or Temporary. */ +export default function OriginBadge({ origin }: OriginBadgeProps) { + return ( + + {ORIGIN_LABELS[origin]} + + ) +} diff --git a/frontend/src/components/Registry/Registry.styles.ts b/frontend/src/components/Registry/Registry.styles.ts index 0ba06cef85..52a363c3c1 100644 --- a/frontend/src/components/Registry/Registry.styles.ts +++ b/frontend/src/components/Registry/Registry.styles.ts @@ -110,6 +110,18 @@ export const useCreateConverterDialogStyles = makeStyles({ maxHeight: '70vh', overflowY: 'auto', }, + // DialogBody is a grid with the actions in its third row; while the warning shows, it takes that row and the + // actions move below it. + temporaryWarning: { + gridRowStart: 3, + gridRowEnd: 3, + gridColumnStart: 1, + gridColumnEnd: 4, + }, + actionsBelowWarning: { + gridRowStart: 4, + gridRowEnd: 4, + }, form: { display: 'flex', flexDirection: 'column', diff --git a/frontend/src/components/Registry/ScorerRegistry.test.tsx b/frontend/src/components/Registry/ScorerRegistry.test.tsx index 054832fc4f..79d70f8e0f 100644 --- a/frontend/src/components/Registry/ScorerRegistry.test.tsx +++ b/frontend/src/components/Registry/ScorerRegistry.test.tsx @@ -1,8 +1,9 @@ -import { render, screen, within } from '@testing-library/react' +import { render, screen, waitFor, within } from '@testing-library/react' import userEvent from '@testing-library/user-event' import { FluentProvider, webLightTheme } from '@fluentui/react-components' import { UserPreferencesProvider } from '@/hooks/useUserPreferences' +import { savedEntriesApi } from '@/services/api' import { readUserPreferences } from '@/utils/userPreferences' import type { ScorerInstance } from '@/types' @@ -62,6 +63,51 @@ describe('ScorerRegistry', () => { expect(readUserPreferences('alice').chatScorer).toBeUndefined() }) + it('labels each scorer with where it comes from', async () => { + const labeled: ScorerInstance[] = [ + { ...scorers[0], scorer_registry_name: 'saved_judge', origin: 'saved' }, + { ...scorers[0], scorer_registry_name: 'startup_judge', origin: 'configuration' }, + { ...scorers[0], scorer_registry_name: 'launch_judge', origin: 'temporary' }, + ] + render( + + ) + + const row = (name: string) => screen.getByRole('row', { name: new RegExp(name) }) + expect(within(row('saved_judge')).getByText('Saved')).toBeInTheDocument() + expect(within(row('startup_judge')).getByText('From configuration')).toBeInTheDocument() + expect(within(row('launch_judge')).getByText('Temporary')).toBeInTheDocument() + // Only a saved scorer has a file to delete. + expect(screen.getAllByRole('button', { name: /^Delete saved scorer/ }).map((button) => button.getAttribute('aria-label'))) + .toEqual(['Delete saved scorer saved_judge']) + }) + + it('moves focus to the page heading after a saved scorer is deleted', async () => { + const user = userEvent.setup() + jest.spyOn(savedEntriesApi, 'get').mockResolvedValue({ + kind: 'scorers', name: 'saved_judge', version: 'v1', problem: null, + can_change: true, + }) + const deleteEntry = jest.spyOn(savedEntriesApi, 'delete').mockResolvedValue() + const onRefresh = jest.fn() + const saved: ScorerInstance[] = [{ ...scorers[0], scorer_registry_name: 'saved_judge', origin: 'saved' }] + const tree = (items: ScorerInstance[]) => + + + const { rerender } = render(tree(saved)) + + await user.click(screen.getByRole('button', { name: 'Delete saved scorer saved_judge' })) + const dialog = await screen.findByRole('dialog', { name: "Delete saved scorer 'saved_judge'?" }) + await user.click(await within(dialog).findByRole('button', { name: 'Delete' })) + await waitFor(() => expect(onRefresh).toHaveBeenCalledTimes(1)) + // The refreshed list no longer has the scorer, so its table unmounts. + rerender(tree([])) + + expect(deleteEntry).toHaveBeenCalledWith('scorers', 'saved_judge', 'v1') + await waitFor(() => expect(screen.getByRole('heading', { name: 'Scorer Registry' })).toHaveFocus()) + jest.restoreAllMocks() + }) + it('shows nested types, canonical identity JSON, primary metrics, and average time', async () => { const user = userEvent.setup() const evaluated: ScorerInstance = { diff --git a/frontend/src/components/Registry/ScorerRegistry.tsx b/frontend/src/components/Registry/ScorerRegistry.tsx index 1bb6e06548..3a6404e2ee 100644 --- a/frontend/src/components/Registry/ScorerRegistry.tsx +++ b/frontend/src/components/Registry/ScorerRegistry.tsx @@ -1,4 +1,4 @@ -import { Fragment, useState } from 'react' +import { Fragment, useEffect, useRef, useState } from 'react' import { Divider, mergeClasses, Table, TableBody, TableCell, TableHeader, TableHeaderCell, TableRow, Text, Tooltip } from '@fluentui/react-components' @@ -11,6 +11,8 @@ import { formatScorerComparisonMetric, scorerComparisonValue, scorerEvidenceLabel, scorerMetricDescription, scorerMetricLabel, } from '@/utils/scorerPresentation' +import OriginBadge from './OriginBadge' +import DeleteSavedEntryButton from './DeleteSavedEntryButton' import { useConverterRegistryStyles } from './Registry.styles' import RegistryIdentityRow from './RegistryIdentityRow' import { useScorerRegistryStyles } from './ScorerRegistry.styles' @@ -32,6 +34,7 @@ interface ScorerTableSection { interface ScorerTableProps extends ScorerTableSection { scorers: ScorerInstance[] + onDeleted: () => void } interface ScorerTableSort { @@ -68,7 +71,7 @@ function MetricCell({ name, value }: { name: string; value: unknown }) { ) } -function ScorerTable({ title, family, metrics, scorers }: ScorerTableProps) { +function ScorerTable({ title, family, metrics, scorers, onDeleted }: ScorerTableProps) { const styles = useConverterRegistryStyles() const scorerStyles = useScorerRegistryStyles() const [expanded, setExpanded] = useState>(new Set()) @@ -136,7 +139,13 @@ function ScorerTable({ title, family, metrics, scorers }: ScorerTableProps) { toggleDetails(scorer.scorer_registry_name)}> + onToggle={() => toggleDetails(scorer.scorer_registry_name)} + nameContent={<> + {scorer.origin && } + {scorer.origin === 'saved' && ( + + )} + }> {(scorer.display_type ?? scorer.identifier.class_name).split('(').map((part: string, index: number) => ( @@ -163,11 +172,21 @@ export default function ScorerRegistry({ scorers, loading, error, onRefresh }: S const scorerStyles = useScorerRegistryStyles() const { preferences, updatePreferences } = useUserPreferences() useAutoRefresh(onRefresh, !loading) + const heading = useRef(null) + const [focusRestore, setFocusRestore] = useState(0) + useEffect(() => { + if (focusRestore) heading.current?.focus() + }, [focusRestore]) + const handleDeleted = () => { + // The deleted scorer's row, or its whole table, is about to unmount, so focus goes to the page heading. + setFocusRestore((current) => current + 1) + onRefresh() + } return (
- + Components that evaluate evidence and return a score or verdict. The attack decides what to do with that result. @@ -185,7 +204,8 @@ export default function ScorerRegistry({ scorers, loading, error, onRefresh }: S {TABLE_SECTIONS.map(({ family, title, metrics }: ScorerTableSection) => { const items = scorers.filter((scorer: ScorerInstance) => scorerFamily(scorer) === family) return items.length > 0 - ? : null + ? : null })} {!loading && !error && scorers.length === 0 && No scorers are registered. Configure scorers through an initializer.}
diff --git a/frontend/src/components/Registry/TechniqueRegistry.test.tsx b/frontend/src/components/Registry/TechniqueRegistry.test.tsx index 2cac194ca6..7c2bd267f4 100644 --- a/frontend/src/components/Registry/TechniqueRegistry.test.tsx +++ b/frontend/src/components/Registry/TechniqueRegistry.test.tsx @@ -31,6 +31,10 @@ function technique(name: string, attackType = 'PromptSendingAttack', tags = ['ba creation_statement: `AttackTechniqueFactory(\n name="${name}",\n attack_class=${attackType},\n)` } } +function axiosError(status: number, data: Record): Error { + return Object.assign(new Error('Request failed'), { isAxiosError: true, response: { status, data } }) +} + function techniquePage(items: TechniqueInstance[]): TechniqueListResponse { return { items, pagination: { limit: 200, has_more: false } } } @@ -198,12 +202,12 @@ describe('TechniqueRegistry', () => { await user.keyboard('{ArrowUp}') await user.click(screen.getByRole('combobox', { name: 'Response converters' })) await user.click(screen.getByTestId('converter-option-rot13')) - await user.click(screen.getByRole('button', { name: 'Add technique' })) + await user.click(screen.getByRole('button', { name: 'Save technique' })) await waitFor(() => expect(techniques.createTechnique).toHaveBeenCalledTimes(1)) const request = techniques.createTechnique.mock.calls[0][0] expect(request).toMatchObject({ name: 'created', description: 'Custom settings', tags: ['mine', 'basic'], type: 'PromptSendingAttack', params: { max_attempts_on_failure: 0, settings: { type: 'basic', parameters: { enabled: false, limit: 0 } }, - }, request_converters: ['b64', 'rot13', 'b64'], response_converters: ['rot13'] }) + }, request_converters: ['b64', 'rot13', 'b64'], response_converters: ['rot13'], persist: true }) expect(request.params).not.toHaveProperty('objective_target') expect(request.params).not.toHaveProperty('prompt_normalizer') await waitFor(() => expect(screen.getByRole('button', { name: 'New technique' })).toHaveFocus()) @@ -220,7 +224,7 @@ describe('TechniqueRegistry', () => { await user.type(screen.getByRole('textbox', { name: 'Adversarial system prompt' }), 'system') await user.type(screen.getByRole('textbox', { name: 'Adversarial seed prompt' }), 'seed') await user.type(screen.getByRole('textbox', { name: 'Adversarial per-turn prompt' }), 'turn') - await user.click(screen.getByRole('button', { name: 'Add technique' })) + await user.click(screen.getByRole('button', { name: 'Save technique' })) await waitFor(() => expect(techniques.createTechnique).toHaveBeenCalled()) expect(techniques.createTechnique.mock.calls[0][0]).toMatchObject({ adversarial_chat: 'local', adversarial_system_prompt: 'system', adversarial_seed_prompt: 'seed', adversarial_prompt_template: 'turn', @@ -245,10 +249,10 @@ describe('TechniqueRegistry', () => { render(tree()) const user = await openCreate() expect(screen.queryByRole('option', { name: 'ComplexAttack' })).not.toBeInTheDocument() - expect(screen.getByRole('button', { name: 'Add technique' })).toBeDisabled() + expect(screen.getByRole('button', { name: 'Save technique' })).toBeDisabled() await user.selectOptions(screen.getByRole('combobox', { name: 'Attack type' }), 'PromptSendingAttack') await user.type(screen.getByRole('textbox', { name: 'Registry name' }), 'all') - await user.click(screen.getByRole('button', { name: 'Add technique' })) + await user.click(screen.getByRole('button', { name: 'Save technique' })) await screen.findByText(/Do not use all, default, or types\./) expect(techniques.createTechnique).toHaveBeenCalledTimes(1) }) @@ -277,7 +281,7 @@ describe('TechniqueRegistry', () => { expect(screen.queryByLabelText('child')).not.toBeInTheDocument() await user.type(screen.getByRole('spinbutton', { name: 'limit' }), '0') await user.type(screen.getByRole('textbox', { name: 'Registry name' }), 'basic_settings') - await user.click(screen.getByRole('button', { name: 'Add technique' })) + await user.click(screen.getByRole('button', { name: 'Save technique' })) await waitFor(() => expect(techniques.createTechnique).toHaveBeenCalledTimes(1)) expect(techniques.createTechnique.mock.calls[0][0].params).toEqual({ settings: { type: 'basic', parameters: { limit: 0 } }, @@ -331,7 +335,7 @@ describe('TechniqueRegistry', () => { const user = await openCreate() await user.type(screen.getByRole('textbox', { name: 'Registry name' }), 'first') await user.selectOptions(screen.getByRole('combobox', { name: 'Attack type' }), 'PromptSendingAttack') - await user.click(screen.getByRole('button', { name: 'Add technique' })) + await user.click(screen.getByRole('button', { name: 'Save technique' })) await screen.findByText('Name already exists') await user.click(screen.getByRole('button', { name: 'Cancel' })) await waitFor(() => expect(screen.getByRole('button', { name: 'New technique' })).toHaveFocus()) @@ -344,7 +348,7 @@ describe('TechniqueRegistry', () => { const user = await openCreate() await user.type(screen.getByRole('textbox', { name: 'Registry name' }), 'later') await user.selectOptions(screen.getByRole('combobox', { name: 'Attack type' }), 'PromptSendingAttack') - await user.click(screen.getByRole('button', { name: 'Add technique' })) + await user.click(screen.getByRole('button', { name: 'Save technique' })) await user.click(screen.getByRole('button', { name: 'Cancel' })) await act(async () => { completeCreate?.(technique('later')) }) expect(techniques.listTechniques).toHaveBeenCalledTimes(1) @@ -366,7 +370,7 @@ describe('TechniqueRegistry', () => { const user = await openCreate() await user.type(screen.getByRole('textbox', { name: 'Registry name' }), 'previous_runtime') await user.selectOptions(screen.getByRole('combobox', { name: 'Attack type' }), 'PromptSendingAttack') - await user.click(screen.getByRole('button', { name: 'Add technique' })) + await user.click(screen.getByRole('button', { name: 'Save technique' })) mockRuntime = { generation: 2, ready: true } rerender(tree()) await waitFor(() => expect(screen.getByText('New technique', { selector: 'button' })).toHaveFocus()) @@ -378,4 +382,151 @@ describe('TechniqueRegistry', () => { expect(techniques.listTechniques).toHaveBeenCalledTimes(2) expect(screen.queryByText('previous_runtime description')).not.toBeInTheDocument() }) + + it('labels each technique by where it comes from', async () => { + techniques.listTechniques.mockResolvedValue(techniquePage([ + { ...technique('saved_one'), origin: 'saved' }, + { ...technique('startup_one'), origin: 'configuration' }, + { ...technique('temporary_one'), origin: 'temporary' }, + ])) + render(tree()) + const table = await screen.findByRole('table', { name: 'Registered techniques' }) + const row = (name: string) => within(table).getByText(name).closest('tr') as HTMLElement + + expect(within(row('saved_one')).getByText('Saved')).toBeInTheDocument() + expect(within(row('startup_one')).getByText('From configuration')).toBeInTheDocument() + expect(within(row('temporary_one')).getByText('Temporary')).toBeInTheDocument() + // Only a saved technique has a file to delete. + expect(within(table).getAllByRole('button', { name: /^Delete saved technique/ }).map((button) => button.getAttribute('aria-label'))) + .toEqual(['Delete saved technique saved_one']) + }) + + it('creates a Temporary technique when a converter it uses is Temporary', async () => { + converters.listConverters.mockResolvedValue({ items: [ + { converter_id: 'b64', origin: 'configuration', + identifier: { class_name: 'Base64Converter', class_module: 'pyrit.converter', hash: 'b64', pyrit_version: '1' } }, + { converter_id: 'rot13', origin: 'temporary', + identifier: { class_name: 'ROT13Converter', class_module: 'pyrit.converter', hash: 'rot13', pyrit_version: '1' } }, + ] }) + render(tree()) + const user = await openCreate() + await user.type(screen.getByRole('textbox', { name: 'Registry name' }), 'encoded') + await user.selectOptions(screen.getByRole('combobox', { name: 'Attack type' }), 'PromptSendingAttack') + await user.click(screen.getByRole('combobox', { name: 'Request converters' })) + await user.click(screen.getByTestId('converter-option-b64')) + expect(screen.getByRole('button', { name: 'Save technique' })).toBeEnabled() + await user.click(screen.getByRole('combobox', { name: 'Request converters' })) + await user.click(screen.getByTestId('converter-option-rot13')) + + expect(screen.getByText("This technique can't be saved")).toBeInTheDocument() + expect(screen.getByText(/Uses temporary converter 'rot13', which won't exist after a restart\. A Temporary technique is gone after the backend restarts or is reinitialized\./)).toBeInTheDocument() + await user.click(screen.getByRole('button', { name: 'Create as Temporary' })) + await waitFor(() => expect(techniques.createTechnique).toHaveBeenCalledTimes(1)) + expect(techniques.createTechnique.mock.calls[0][0]).toMatchObject({ + name: 'encoded', request_converters: ['b64', 'rot13'], persist: false, + }) + }) + + it('creates a Temporary technique when its adversarial target is Temporary', async () => { + targets.listTargets.mockResolvedValue({ + items: [makeTarget({ target_registry_name: 'local', origin: 'temporary' })], pagination: { limit: 200, has_more: false }, + }) + render(tree()) + const user = await openCreate() + await user.type(screen.getByRole('textbox', { name: 'Registry name' }), 'adversarial') + await user.selectOptions(screen.getByRole('combobox', { name: 'Attack type' }), 'RedTeamingAttack') + await user.selectOptions(screen.getByRole('combobox', { name: 'Adversarial target' }), 'local') + + expect(screen.getByText(/Uses temporary target 'local', which won't exist after a restart\./)).toBeInTheDocument() + await user.click(screen.getByRole('button', { name: 'Create as Temporary' })) + await waitFor(() => expect(techniques.createTechnique).toHaveBeenCalledTimes(1)) + expect(techniques.createTechnique.mock.calls[0][0]).toMatchObject({ adversarial_chat: 'local', persist: false }) + }) + + it('offers a Temporary technique when the server refuses to save it, until a value changes', async () => { + techniques.createTechnique.mockRejectedValueOnce(axiosError(400, { + type: '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/errors/not-saveable', + detail: 'Refused. It can still be created without saving it.', + not_saveable_reason: 'Refused.', + })) + render(tree()) + const user = await openCreate() + await user.type(screen.getByRole('textbox', { name: 'Registry name' }), 'refused') + await user.selectOptions(screen.getByRole('combobox', { name: 'Attack type' }), 'PromptSendingAttack') + await user.click(screen.getByRole('button', { name: 'Save technique' })) + + // The cause and the Temporary note, each once. + expect(await screen.findByRole('status')).toHaveTextContent( + 'Refused. A Temporary technique is gone after the backend restarts or is reinitialized.', + ) + expect(screen.queryByText(/It can still be created without saving it/)).not.toBeInTheDocument() + expect(techniques.createTechnique.mock.calls[0][0]).toMatchObject({ persist: true }) + await user.type(screen.getByRole('spinbutton', { name: 'max_attempts_on_failure' }), '1') + expect(screen.queryByText(/Refused\./)).not.toBeInTheDocument() + await user.click(screen.getByRole('button', { name: 'Save technique' })) + await waitFor(() => expect(techniques.createTechnique).toHaveBeenCalledTimes(2)) + expect(techniques.createTechnique.mock.calls[1][0]).toMatchObject({ + name: 'refused', params: { max_attempts_on_failure: 1 }, persist: true, + }) + }) + + it('creates the refused technique as Temporary when asked', async () => { + techniques.createTechnique.mockRejectedValueOnce( + axiosError(400, { type: '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/errors/not-saveable', detail: 'Refused. It can still be created without saving it.' }), + ) + render(tree()) + const user = await openCreate() + await user.type(screen.getByRole('textbox', { name: 'Registry name' }), 'refused') + await user.selectOptions(screen.getByRole('combobox', { name: 'Attack type' }), 'PromptSendingAttack') + await user.click(screen.getByRole('button', { name: 'Save technique' })) + await user.click(await screen.findByRole('button', { name: 'Create as Temporary' })) + + await waitFor(() => expect(techniques.createTechnique).toHaveBeenCalledTimes(2)) + expect(techniques.createTechnique.mock.calls[1][0]).toMatchObject({ name: 'refused', persist: false }) + }) + + it('shows a taken name on the name field and needs a lowercase name to save', async () => { + techniques.createTechnique.mockRejectedValueOnce( + axiosError(409, { detail: "Technique 'first' already exists (names are case-insensitive)" }), + ) + render(tree()) + const user = await openCreate() + const name = screen.getByRole('textbox', { name: 'Registry name' }) + await user.type(name, 'First') + await user.selectOptions(screen.getByRole('combobox', { name: 'Attack type' }), 'PromptSendingAttack') + + expect(screen.getByText('Use lowercase letters, digits and underscores, starting with a letter (max 64 characters).')).toBeInTheDocument() + expect(screen.getByRole('button', { name: 'Save technique' })).toBeDisabled() + await user.clear(name) + await user.type(name, 'first') + await user.click(screen.getByRole('button', { name: 'Save technique' })) + expect(await screen.findByText("Technique 'first' already exists (names are case-insensitive)")).toBeInTheDocument() + expect(screen.getByRole('button', { name: 'Save technique' })).toBeDisabled() + await user.type(name, '_2') + expect(screen.queryByText("Technique 'first' already exists (names are case-insensitive)")).not.toBeInTheDocument() + expect(screen.getByRole('button', { name: 'Save technique' })).toBeEnabled() + }) + + it('lets a taken tag be changed and saved again', async () => { + techniques.createTechnique.mockRejectedValueOnce( + axiosError(409, { detail: "Tag 'first' conflicts with technique 'first'" }), + ) + render(tree()) + const user = await openCreate() + await user.type(screen.getByRole('textbox', { name: 'Registry name' }), 'fresh') + const tags = screen.getByRole('textbox', { name: 'Tags' }) + await user.type(tags, 'first') + await user.selectOptions(screen.getByRole('combobox', { name: 'Attack type' }), 'PromptSendingAttack') + await user.click(screen.getByRole('button', { name: 'Save technique' })) + expect(await screen.findByText("Tag 'first' conflicts with technique 'first'")).toBeInTheDocument() + expect(screen.getByRole('button', { name: 'Save technique' })).toBeDisabled() + + await user.clear(tags) + await user.type(tags, 'single_turn') + expect(screen.queryByText("Tag 'first' conflicts with technique 'first'")).not.toBeInTheDocument() + await user.click(screen.getByRole('button', { name: 'Save technique' })) + + await waitFor(() => expect(techniques.createTechnique).toHaveBeenCalledTimes(2)) + expect(techniques.createTechnique.mock.calls[1][0]).toMatchObject({ name: 'fresh', tags: ['single_turn'] }) + }) }) diff --git a/frontend/src/components/Registry/TechniqueRegistry.tsx b/frontend/src/components/Registry/TechniqueRegistry.tsx index 099844b08f..aad0207049 100644 --- a/frontend/src/components/Registry/TechniqueRegistry.tsx +++ b/frontend/src/components/Registry/TechniqueRegistry.tsx @@ -16,6 +16,8 @@ import type { TechniqueInstance } from '@/types' import { fetchAllPages } from '@/utils/fetchAllPages' import CreateTechniqueDialog from './CreateTechniqueDialog' +import OriginBadge from './OriginBadge' +import DeleteSavedEntryButton from './DeleteSavedEntryButton' import RegistryIdentityRow from './RegistryIdentityRow' import { useTechniqueRegistryStyles } from './TechniqueRegistry.styles' @@ -153,7 +155,16 @@ function TechniqueRegistryPage({ ready, runtimeKey }: TechniqueRegistryPageProps {visible.map((item) => ( toggleDetails(item.name)}> + expanded={expanded.has(item.name)} onToggle={() => toggleDetails(item.name)} + nameContent={<> + {item.origin && } + {item.origin === 'saved' && ( + { + setFocusRestore((current) => current + 1) + void load() + }} /> + )} + }> {item.description ?? 'No description'} {item.attack_type}
{item.tags.map((tag) => {tag})}
diff --git a/frontend/src/components/Techniques/TechniqueEditor.styles.ts b/frontend/src/components/Techniques/TechniqueEditor.styles.ts index 1c006c3d83..5146e72277 100644 --- a/frontend/src/components/Techniques/TechniqueEditor.styles.ts +++ b/frontend/src/components/Techniques/TechniqueEditor.styles.ts @@ -10,6 +10,10 @@ export const useTechniqueEditorStyles = makeStyles({ }, }, content: { minWidth: 0, overflowY: 'auto', maxHeight: '65vh' }, + // DialogBody is a grid with the actions in its third row; while the warning shows, it takes that row and the + // actions move below it. + temporaryWarning: { gridRowStart: 3, gridRowEnd: 3, gridColumnStart: 1, gridColumnEnd: 4 }, + actionsBelowWarning: { gridRowStart: 4, gridRowEnd: 4 }, form: { display: 'flex', flexDirection: 'column', width: '100%', minWidth: 0, maxWidth: '100%', gap: tokens.spacingVerticalL, diff --git a/frontend/src/components/Techniques/TechniqueEditor.test.tsx b/frontend/src/components/Techniques/TechniqueEditor.test.tsx index b16635b6fc..5987a8c1ba 100644 --- a/frontend/src/components/Techniques/TechniqueEditor.test.tsx +++ b/frontend/src/components/Techniques/TechniqueEditor.test.tsx @@ -182,7 +182,7 @@ describe('TechniqueEditor', () => { await user.click(screen.getByRole('option', { name: /^New converter/ })) await user.click(await screen.findByRole('combobox', { name: /Converter Type/i })) await user.click(screen.getByRole('option', { name: /Base64Converter/ })) - await user.click(screen.getByRole('button', { name: 'Add Converter' })) + await user.click(screen.getByRole('button', { name: 'Save Converter' })) await waitFor(() => expect(convertersApi.createConverter).toHaveBeenCalledTimes(1)) await user.click(within(screen.getByRole('dialog', { name: 'Add Converter' })).getByRole('button', { name: 'Cancel' })) await user.click(await screen.findByRole('button', { name: 'Remove converter base64, Request converters stage 1' })) @@ -261,7 +261,7 @@ describe('TechniqueEditor', () => { await user.click(screen.getByRole('option', { name: /CaesarConverter/ })) await user.type(screen.getByRole('textbox', { name: /Registry Name/i }), 'new_caesar') await user.type(screen.getByLabelText(/caesar_offset/i), '3') - await user.click(screen.getByRole('button', { name: 'Add Converter' })) + await user.click(screen.getByRole('button', { name: 'Save Converter' })) await screen.findByText('new_caesar') await user.click(await screen.findByRole('button', { name: 'Apply to run' })) await waitFor(() => expect(techniques.validateEdit).toHaveBeenCalled()) diff --git a/frontend/src/components/Techniques/TechniqueEditor.tsx b/frontend/src/components/Techniques/TechniqueEditor.tsx index e37d384032..2e0fdfba46 100644 --- a/frontend/src/components/Techniques/TechniqueEditor.tsx +++ b/frontend/src/components/Techniques/TechniqueEditor.tsx @@ -2,7 +2,7 @@ import { type Dispatch, type SetStateAction, useEffect, useRef, useState } from import { Button, Dialog, DialogActions, DialogBody, DialogContent, DialogSurface, DialogTitle, - Input, MessageBar, MessageBarBody, Select, Spinner, Text, Textarea, + Input, MessageBar, MessageBarBody, MessageBarTitle, Select, Spinner, Text, Textarea, } from '@fluentui/react-components' import ContextualHelpLabel from '@/components/ContextualHelpLabel' @@ -15,8 +15,9 @@ import { buildParametersFromForm, getInitialFormValues, nonNullableTypeName, type ParameterFormValue, } from '@/components/Parameters/parameterForm' import { convertersApi, techniquesApi } from '@/services/api' -import { toApiError } from '@/services/errors' +import { isNotSaveableError, notSaveableReason, toApiError } from '@/services/errors' import { listRegisteredTargets } from '@/services/targetRegistry' +import { validateRegistryName } from '@/utils/registryName' import type { CreateTechniqueRequest, Parameter, RegistryReferenceOption, TechniqueTypeEntry, TechniqueConfiguration, TechniqueChanges, TechniqueEditResponse, SimulationChanges, @@ -27,6 +28,7 @@ import { useTechniqueEditorStyles } from './TechniqueEditor.styles' const SCALAR_TYPES = new Set(['str', 'int', 'float', 'bool', 'list[str]', 'list[int]', 'list[float]', 'list[bool]']) const VALIDATION_DELAY_MS = 300 +const TEMPORARY_TECHNIQUE_NOTE = 'A Temporary technique is gone after the backend restarts or is reinitialized.' function canConfigure(parameter: Parameter, allowStructured = true): boolean { if (parameter.reference_type) return false @@ -86,6 +88,7 @@ export default function TechniqueEditor({ const configuration = initial ?? original const [types, setTypes] = useState([]) const [targetOptions, setTargetOptions] = useState([]) + const [temporaryTargets, setTemporaryTargets] = useState>(new Set()) const [converters, setConverters] = useState([]) const converterOptions = converters.map((entry) => ({ name: entry.converter_id, type: entry.identifier.class_name })) const [selectedType, setSelectedType] = useState(configuration?.attack_type ?? '') @@ -111,6 +114,8 @@ export default function TechniqueEditor({ const [submitError, setSubmitError] = useState(false) const [revision, setRevision] = useState(0) const [validating, setValidating] = useState(false) + const [saveRefusal, setSaveRefusal] = useState<{ formKey: string, reason: string } | null>(null) + const [nameConflict, setNameConflict] = useState<{ name: string, tags: string, detail: string } | null>(null) function update(setter: Dispatch>, value: Value): void { if (autoApply) { @@ -149,6 +154,8 @@ export default function TechniqueEditor({ setTypes(original ? metadata.items : metadata.items.filter((entry) => getAttackParameters(entry).every((parameter) => !parameter.required || canConfigure(parameter)))) setTargetOptions(targets.map((entry) => ({ name: entry.target_registry_name, type: entry.identifier.class_name }))) + setTemporaryTargets(new Set(targets.filter((entry) => entry.origin === 'temporary') + .map((entry) => entry.target_registry_name))) setConverters(converters.items) } catch (err) { if (!ignore) setError(toApiError(err).detail) @@ -167,6 +174,25 @@ export default function TechniqueEditor({ const parameters = original ? original.parameters : guiParameters(getAttackParameters(selected)) const editable = (field: string): boolean => !original || original.editable_fields.includes(field) + // A new technique is saved unless it uses a Temporary entry, which won't exist after a restart. + const chosenConverters = selected?.supports_converters + ? [...requestConverters, ...responseConverters].filter((entry): entry is string => typeof entry === 'string') + : [] + const temporaryConverter = chosenConverters.find((entry) => + converters.find((converter) => converter.converter_id === entry)?.origin === 'temporary') + const predictedTemporaryReason = temporaryConverter + ? `Uses temporary converter '${temporaryConverter}', which won't exist after a restart.` + : selected?.supports_adversarial && temporaryTargets.has(adversarialTarget) + ? `Uses temporary target '${adversarialTarget}', which won't exist after a restart.` + : null + // A refused save only applies to the values it was refused for, so any edit lets the user try saving again. + const formKey = JSON.stringify([selectedType, values, requestConverters, responseConverters, adversarialTarget]) + const refusedReason = saveRefusal?.formKey === formKey ? saveRefusal.reason : null + const temporaryReason = editing ? null : predictedTemporaryReason ?? refusedReason + const nameConflictDetail = nameConflict?.name === name && nameConflict.tags === tags ? nameConflict.detail : null + const nameMessage = editing ? null + : nameConflictDetail ?? (temporaryReason === null && name ? validateRegistryName(name) : null) + const editChanges = (): TechniqueChanges => { if (!original) throw new Error('A source technique is required for editing.') const originalValues = editorValues(original) @@ -272,11 +298,21 @@ export default function TechniqueEditor({ }) if (active.current) onApplied?.(response) } else { - await techniquesApi.createTechnique(request) + await techniquesApi.createTechnique({ ...request, persist: temporaryReason === null }) if (active.current) onCreated?.() } } catch (err) { - if (active.current) fail(toApiError(err).detail) + if (active.current) { + const apiError = toApiError(err) + if (!original && temporaryReason === null && isNotSaveableError(apiError)) { + setSaveRefusal({ formKey, reason: notSaveableReason(apiError) ?? apiError.detail }) + } else if (!original && apiError.status === 409 && apiError.type === undefined) { + // A taken name or tag is a 409 without a problem type, so changing either lets the user try again. + setNameConflict({ name, tags, detail: apiError.detail }) + } else { + fail(apiError.detail) + } + } } finally { if (active.current) setSubmitting(false) } @@ -295,8 +331,10 @@ export default function TechniqueEditor({ {!loading && types.length === 0 && } {!loading && types.length > 0 && ( <> - {!editing && + {!editing && setName(data.value)} /> } {editing @@ -404,10 +442,24 @@ export default function TechniqueEditor({ {content} - + {/* Outside the scrolling form, so it shows next to the button it explains without moving the fields. */} + {!editing && temporaryReason && ( + + + This technique can't be saved + {temporaryReason} {TEMPORARY_TECHNIQUE_NOTE} + + + )} + - + diff --git a/frontend/src/hooks/useRuntime.test.tsx b/frontend/src/hooks/useRuntime.test.tsx index 1ce9ba7379..9e7927c72d 100644 --- a/frontend/src/hooks/useRuntime.test.tsx +++ b/frontend/src/hooks/useRuntime.test.tsx @@ -69,8 +69,8 @@ describe('RuntimeBanner', () => { expect(await screen.findByText(new RegExp( "Some saved entries couldn't be restored, so new runs and sends are unavailable\\. An administrator has to " - + 'view the failures in Configuration, fix or delete the files in registry_recipes_source, then reinitialize ' - + 'PyRIT or restart the backend\\. Drafts are preserved\\.', + + 'delete them in Configuration or fix their files in registry_recipes_source, then reinitialize PyRIT or ' + + 'restart the backend\\. Drafts are preserved\\.', ))).toBeInTheDocument() expect(screen.queryByRole('region')).not.toBeInTheDocument() expect(screen.queryByRole('button')).not.toBeInTheDocument() @@ -104,4 +104,20 @@ describe('RuntimeBanner', () => { await waitFor(() => expect(screen.queryByText(/PyRIT runtime/)).not.toBeInTheDocument()) expect(screen.queryByText(/couldn't be restored/)).not.toBeInTheDocument() }) + + it('should say to reinitialize or restart once every entry that failed to restore is deleted', async () => { + jest.mocked(runtimeApi.getReadiness).mockResolvedValue({ + ready: false, + state: 'failed', + generation: 'first', + restore_failures: 0, + }) + + renderBanner() + + expect(await screen.findByText( + /PyRIT isn't ready.*An administrator can reinitialize PyRIT or restart the backend\./, + )).toBeInTheDocument() + expect(screen.queryByText(/couldn't be restored/)).not.toBeInTheDocument() + }) }) diff --git a/frontend/src/hooks/useRuntime.tsx b/frontend/src/hooks/useRuntime.tsx index 485ca25e03..894d629007 100644 --- a/frontend/src/hooks/useRuntime.tsx +++ b/frontend/src/hooks/useRuntime.tsx @@ -48,8 +48,19 @@ export function RuntimeBanner() { Some saved entries couldn't be restored, so new runs and sends are unavailable. An administrator has to - view the failures in Configuration, fix or delete the files in registry_recipes_source, then reinitialize - PyRIT or restart the backend. Drafts are preserved. + delete them in Configuration or fix their files in registry_recipes_source, then reinitialize PyRIT or + restart the backend. Drafts are preserved. + + + ) + } + if (runtime.state === 'failed') { + // Deleting every entry that couldn't be restored leaves the runtime failed until it restores again. + return ( + + + PyRIT isn't ready, so new runs and sends are unavailable. Drafts are preserved. An administrator can + reinitialize PyRIT or restart the backend. ) diff --git a/frontend/src/services/api.ts b/frontend/src/services/api.ts index 518791baa9..57b3019ced 100644 --- a/frontend/src/services/api.ts +++ b/frontend/src/services/api.ts @@ -401,6 +401,16 @@ export const runtimeApi = { }, } +export const savedEntriesApi = { + get: async (kind: RegistryRecipeKind, name: string): Promise => { + return (await apiClient.get(`/saved-entries/${kind}/${encodeURIComponent(name)}`)).data + }, + delete: async (kind: RegistryRecipeKind, name: string, expectedVersion: string | null): Promise => { + const params = expectedVersion === null ? {} : { expected_version: expectedVersion } + await apiClient.delete(`/saved-entries/${kind}/${encodeURIComponent(name)}`, { params }) + }, +} + export const targetsApi = { detectCapabilities: async (target: TargetInstance): Promise => { const response = await apiClient.post( @@ -1079,4 +1089,9 @@ export const datasetsApi = { }, } -import type { RuntimeReadiness, RuntimeStatus } from '@/types' +import type { + RegistryRecipeKind, + RuntimeReadiness, + RuntimeStatus, + SavedEntry, +} from '@/types' diff --git a/frontend/src/test-utils/targetFixtures.ts b/frontend/src/test-utils/targetFixtures.ts index 09287dc189..08a789ae8b 100644 --- a/frontend/src/test-utils/targetFixtures.ts +++ b/frontend/src/test-utils/targetFixtures.ts @@ -1,4 +1,4 @@ -import type { TargetCapabilities, TargetIdentifier, TargetInstance, TargetOrigin } from '../types' +import type { RegistryEntryOrigin, TargetCapabilities, TargetIdentifier, TargetInstance } from '../types' /** * Flat description of a target for tests, mirroring the old pre-slimming @@ -22,7 +22,7 @@ export interface FlatTargetInput { supports_history_replay?: boolean target_specific_params?: Record | null inner_targets?: FlatTargetInput[] | null - origin?: TargetOrigin | null + origin?: RegistryEntryOrigin | null private?: boolean allow_credential_updates?: boolean credentials_rejected?: boolean | null diff --git a/frontend/src/types/index.ts b/frontend/src/types/index.ts index 4c53405097..f4d6461093 100644 --- a/frontend/src/types/index.ts +++ b/frontend/src/types/index.ts @@ -465,6 +465,8 @@ export interface ScorerInstance { evaluation_identifier?: ComponentIdentifier | null metrics?: ScorerEvaluationMetrics | null chat_scoring_disabled_reason?: string | null + /** Saved, from the server's configuration, or Temporary. */ + origin?: RegistryEntryOrigin | null } export type ScorerEvaluationMetrics = Record @@ -515,13 +517,13 @@ export interface TargetIdentifier { [key: string]: unknown } -/** Where a registered target comes from, and so whether it is still there after a restart. */ -export type TargetOrigin = 'saved' | 'configuration' | 'temporary' +/** Where a registered target, converter, or scorer comes from, and so whether it is still there after a restart. */ +export type RegistryEntryOrigin = 'saved' | 'configuration' | 'temporary' export interface TargetInstance { target_registry_name: string /** Saved, from the server's configuration, or Temporary. Absent for inner targets. */ - origin?: TargetOrigin | null + origin?: RegistryEntryOrigin | null binding?: TargetBinding /** Typed identity: class name, endpoint, model name, generation params, content hash. */ identifier: TargetIdentifier @@ -638,6 +640,8 @@ export interface ConverterInstance { identifier: ConverterIdentifier is_llm_based?: boolean description?: string | null + /** Saved, from the server's configuration, or Temporary. */ + origin?: RegistryEntryOrigin | null } export interface ConverterListResponse { @@ -650,9 +654,12 @@ export type CreateConverterRequest = { } & ({ params?: Record source?: never + /** Save the converter so it comes back after a restart; a copy made with `source` can't be saved yet. */ + persist?: boolean } | { source: SourceInstanceSpec params?: never + persist?: never }) export interface SourceInstanceSpec { @@ -693,6 +700,8 @@ export interface TechniqueInstance { identifier: ComponentIdentifier /** Supplied factory creation inputs, with live component credentials omitted. */ creation_statement: string + /** Whether the technique comes back after a restart. */ + origin?: RegistryEntryOrigin | null } export interface TechniqueTypeEntry { @@ -714,6 +723,8 @@ export interface TechniqueTypeResponse { export interface CreateTechniqueRequest { name: string + /** Save the technique so it comes back after the backend restarts or is reinitialized. */ + persist?: boolean description?: string tags: string[] type: string @@ -816,6 +827,8 @@ export interface ConverterTypeEntry { parameters: Parameter[] is_llm_based: boolean description?: string | null + /** Why a converter of this type can't be saved, or null when it can be. */ + not_saveable_reason?: string | null } export interface ConverterTypeListResponse { @@ -2606,6 +2619,18 @@ export interface SavedEntryRef { name: string } +/** A saved entry's file, as GET /api/saved-entries/{kind}/{name} describes it. */ +export interface SavedEntry { + kind: RegistryRecipeKind + name: string + /** The file's version, sent back when deleting it; null when the file can't be read. */ + version: string | null + /** Why the file can't be used, when it can't be read or isn't a valid entry. */ + problem: string | null + /** Whether the person asking may change or delete it, which takes an administrator. */ + can_change: boolean +} + /** A saved entry, or a whole folder of them when `name` is null, that couldn't be restored. */ export interface RestoreFailure { kind: RegistryRecipeKind diff --git a/frontend/src/utils/registryOrigin.ts b/frontend/src/utils/registryOrigin.ts new file mode 100644 index 0000000000..630948cf07 --- /dev/null +++ b/frontend/src/utils/registryOrigin.ts @@ -0,0 +1,8 @@ +import type { RegistryEntryOrigin } from '@/types' + +/** What each registry entry origin is called in the GUI. */ +export const ORIGIN_LABELS: Record = { + saved: 'Saved', + configuration: 'From configuration', + temporary: 'Temporary', +} diff --git a/frontend/src/utils/targetOrigin.ts b/frontend/src/utils/targetOrigin.ts deleted file mode 100644 index 7919b984e9..0000000000 --- a/frontend/src/utils/targetOrigin.ts +++ /dev/null @@ -1,8 +0,0 @@ -import type { TargetOrigin } from '@/types' - -/** What each target origin is called in the GUI. */ -export const TARGET_ORIGIN_LABELS: Record = { - saved: 'Saved', - configuration: 'From configuration', - temporary: 'Temporary', -} diff --git a/pyrit/backend/README.md b/pyrit/backend/README.md index 7f9fddc9fa..58a62ce527 100644 --- a/pyrit/backend/README.md +++ b/pyrit/backend/README.md @@ -199,6 +199,62 @@ PUT /api/targets/my-claude/credentials - Like other targets created through the API, private targets are gone after the backend restarts or reinitializes. +### Converters and scorers + +- `GET /api/converters/types` - List the converter types that can be created, with their parameters, and why a + type can't be saved at all (`not_saveable_reason`) +- `POST /api/converters` - Create a converter +- `DELETE /api/converters/{converter_id}` - Remove a converter +- `POST /api/scorers` - Create a scorer + +A created converter or scorer is Temporary unless the request sets `"persist": true`, which works as it does for +targets: it needs `register` left on and a name of lowercase letters, digits, and underscores (otherwise **422**), the +entry is saved under `registry_recipes_source` with the signed-in user recorded, and it's restored at every start. A +request receives **400** with `"type": "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/errors/not-saveable"`, and can be sent again without `persist`, if the entry +would save a key, use a +Temporary target, converter, or scorer, be of a type that only a scan's launch scripts added, or, for a converter, need +or keep an uploaded file. A saved converter or scorer can use this server's keys and Azure identity, as the ones from +the configuration do. A target left out of the +request and filled from the configured defaults is saved by name, so it must be registered and not Temporary. A +converter copy made with `source` can't be saved yet, and a private converter or scorer can't be saved (**422**). A +taken name receives **409**, and storage that can't +be written receives **503**. Each listed converter's and scorer's `origin` is `saved`, `configuration`, or +`temporary`, as for targets. `DELETE /api/converters/{id}` +refuses a saved converter (**409**); delete it with `DELETE /api/saved-entries/converters/{id}` instead. + +### Saved entries + +Saved targets, converters, scorers, and techniques are addressed by their saved files, where `kind` is `targets`, +`converters`, `scorers`, or `techniques`. These routes answer while the runtime isn't ready, so an entry that keeps it +from starting can be deleted. + +- `GET /api/saved-entries/{kind}/{name}` - The file's `version`, why it can't be used if it can't (`problem`), + whether the caller may change or delete it (`can_change`), and, for an administrator, what it saves (`recipe`). + **404** when no saved file has the name, including a name only a startup entry has. +- `PUT /api/saved-entries/{kind}/{name}` - Change a saved entry: send back the `recipe` GET returned, changed, as + `{"expected_version": "", "recipe": {...}}`. A target changes its `params` and `auth_mode`, and a converter + or scorer its `params`; a technique changes anything its create request takes except its name, attack type, and + `persist`. Its name, class or attack type, and who saved it stay the same, and it stays saved (**422** otherwise). + The entry is rebuilt through the API that creates one, so the same checks and codes apply, such as the typed **400** + for settings that can't be saved. The running entry is replaced; registered entries that hold it keep its old + settings until the next apply or restart, and the response lists them in `still_using_old`. An entry that wasn't + restored is only saved (`running` is false); apply the configuration or restart the backend to restore it. Who may + change it, and the **403**, **404**, **409** for a changed file, and **503** codes, are as for DELETE. A file that + can't be read or isn't a valid entry can't be changed (**409**); delete it and save it again. +- `DELETE /api/saved-entries/{kind}/{name}?expected_version=` - Delete the file and remove the entry it + restored, so it doesn't come back after a restart; a startup entry with the same name stays. Saved entries are + shared, so only an administrator can delete one, as for scenario presets (**403** otherwise; in local mode that + needs `PYRIT_ALLOW_UNAUTHENTICATED_ADMIN=true`). The person who saved it, kept in its file, is attribution only. + `expected_version` is required (**422**) unless the file can't be read. **409** when the file changed since that + version, another saved entry names this one (they're listed), a registered entry of any origin holds it (they're + listed, except another user's private entry, which is counted without its name; a Temporary one is gone after the + next restart or configuration apply), or a request, run, + send, or estimate is in progress. **503** when storage can't be read or written, or while the runtime is starting. + Deleting an entry that couldn't be restored takes it off `restore_failures` in `GET /api/config/runtime`; apply the + configuration or restart the backend to finish recovering. Saving and deleting take turns, and a save checks again + that the entries it names still come back after a restart (**409** otherwise). A save whose entry then can't be + registered deletes its file again, unless another writer has replaced the file since. + ### Dataset creation, batch mutation, and deletion `POST /api/datasets` creates a named dataset synchronously from multipart form data. @@ -697,7 +753,7 @@ IDs remain available through the single-node and saved-conversation APIs. | `GET /api/techniques` | A page of active registered technique factories | | `GET /api/techniques/types` | Attack-class parameters and supported converter/adversarial controls | | `GET /api/techniques/{name}` | Safe settings for one factory; 404 if not registered | -| `POST /api/techniques` | Validate and register a basic runtime technique; 201 on success | +| `POST /api/techniques` | Validate and register a basic runtime technique, saving it with `persist`; 201 on success | The list accepts `limit` (default 50, range 1-200) and `cursor` (the last returned registry name). Results use registry-name order. Follow `pagination.next_cursor` @@ -725,6 +781,16 @@ Constrained list inputs are resolved to their declared enum or literal values. Deferred Python validation uses the same configured-default rules as decorated constructors; the factory retains omitted arguments and explicit `None` values. +A created technique is Temporary unless the request sets `"persist": true`. A technique to save needs a name of +lowercase letters, digits, and underscores that starts with a letter (otherwise **422**). Its request, without the +name, is saved under `registry_recipes_source` with the signed-in user recorded, and it's rebuilt with the same call +at every start. A request receives **400** with `"type": "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/errors/not-saveable"`, and can be sent again without +`persist`, if its attack type was added by a scan's launch scripts, or a converter or the adversarial target it names +is Temporary. A name or tag that clashes with a +registered technique receives **409**, and storage that can't be written receives **503**. Each listed technique's +`origin` is `saved`, `configuration` (registered by a startup script), or `temporary`, as for targets. Settings +changed for a single run aren't saved. + The basic GUI supports scalar inputs and one level of declared structured settings. It hides nested structured settings that the shared resolver cannot construct. diff --git a/pyrit/backend/main.py b/pyrit/backend/main.py index b097200d47..c8a6f27162 100644 --- a/pyrit/backend/main.py +++ b/pyrit/backend/main.py @@ -41,6 +41,7 @@ message_sends, operations, prompt_generations, + saved_entries, scenario_presets, scenario_suites, scenarios, @@ -153,6 +154,7 @@ async def lifespan(app: FastAPI) -> AsyncGenerator[None, None]: app.include_router(initializers.router, prefix="/api", tags=["initializers"]) app.include_router(labels.router, prefix="/api", tags=["labels"]) app.include_router(health.router, prefix="/api", tags=["health"]) +app.include_router(saved_entries.router, prefix="/api", tags=["saved-entries"]) app.include_router(auth.router, prefix="/api", tags=["auth"]) app.include_router(media.router, prefix="/api", tags=["media"]) app.include_router(scores.router, prefix="/api", tags=["scores"]) diff --git a/pyrit/backend/mappers/converter_mappers.py b/pyrit/backend/mappers/converter_mappers.py index b1c11b2d7d..f34ac06a78 100644 --- a/pyrit/backend/mappers/converter_mappers.py +++ b/pyrit/backend/mappers/converter_mappers.py @@ -13,6 +13,7 @@ from pyrit.backend.models import ConverterInstance from pyrit.converter import Converter from pyrit.models import ConverterIdentifier +from pyrit.models.catalog import RegistryEntryOrigin def converter_object_to_instance( @@ -21,6 +22,7 @@ def converter_object_to_instance( converter_obj: Converter, is_llm_based: bool, description: str | None, + origin: RegistryEntryOrigin | None = None, ) -> ConverterInstance: """ Build a ConverterInstance DTO from a registry converter object. @@ -34,6 +36,8 @@ def converter_object_to_instance( converter_obj (Converter): The domain Converter object from the registry. is_llm_based (bool): Whether the converter class requires an LLM target. description (str | None): The converter class description. + origin (RegistryEntryOrigin | None): Where the registered converter comes from, or None when it isn't + registered. Returns: ConverterInstance DTO wrapping the converter's identifier. @@ -43,4 +47,5 @@ def converter_object_to_instance( identifier=ConverterIdentifier.from_component_identifier(converter_obj.get_identifier()), is_llm_based=is_llm_based, description=description, + origin=origin, ) diff --git a/pyrit/backend/mappers/technique_mappers.py b/pyrit/backend/mappers/technique_mappers.py index 6fa6f4b9ce..cc19383ea5 100644 --- a/pyrit/backend/mappers/technique_mappers.py +++ b/pyrit/backend/mappers/technique_mappers.py @@ -10,6 +10,7 @@ from pyrit.backend.models.techniques import TechniqueConfiguration, TechniqueInstance from pyrit.models import Identifiable, SeedPrompt +from pyrit.models.catalog import RegistryEntryOrigin from pyrit.models.technique_edit import TechniqueSettings from pyrit.registry import AttackRegistry, AttackTechniqueRegistry from pyrit.registry.resolution import project_parameter_value @@ -84,10 +85,18 @@ def _format_creation_calls(factory: AttackTechniqueFactory) -> str: return ".".join(calls) -def technique_to_instance(*, name: str, factory: AttackTechniqueFactory) -> TechniqueInstance: +def technique_to_instance( + *, name: str, factory: AttackTechniqueFactory, origin: RegistryEntryOrigin | None = None +) -> TechniqueInstance: """ Map a real factory without constructing an attack or resolving default targets. + Args: + name (str): The technique's registry name. + factory (AttackTechniqueFactory): The registered factory. + origin (RegistryEntryOrigin | None): Where the technique comes from, or None when it isn't known. + Defaults to None. + Returns: TechniqueInstance: Catalog metadata and the supplied factory creation inputs. """ @@ -100,6 +109,7 @@ def technique_to_instance(*, name: str, factory: AttackTechniqueFactory) -> Tech uses_default_adversarial_target=factory.uses_default_adversarial_target, identifier=factory.get_identifier(), creation_statement=_format_creation_calls(factory), + origin=origin, ) diff --git a/pyrit/backend/middleware/runtime.py b/pyrit/backend/middleware/runtime.py index d79d2775a1..f527d25dee 100644 --- a/pyrit/backend/middleware/runtime.py +++ b/pyrit/backend/middleware/runtime.py @@ -9,6 +9,8 @@ from starlette.responses import JSONResponse from starlette.types import ASGIApp, Receive, Scope, Send +from pyrit.backend.services.runtime_lifecycle import current_operation + if TYPE_CHECKING: from pyrit.backend.services.runtime_lifecycle import RuntimeLifecycle @@ -42,14 +44,16 @@ async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None: ): await self.app(scope, receive, send) return - management = path == "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/api/config" or path.startswith(("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/api/config/", "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/api/initializers")) + management = path == "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/api/config" or path.startswith( + ("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/api/config/", "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/api/initializers", "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/api/saved-entries/") + ) apply_route = path.startswith("/api/config/runtime") write = management and scope["method"] not in ("GET", "HEAD", "OPTIONS") and not apply_route if ( runtime.is_stopping or (write and (runtime.edit_lock.locked() or (runtime.apply_task and not runtime.apply_task.done()))) or (path.startswith("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/api/initializers") and runtime.edit_lock.locked()) - or (path.startswith("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/api/initializers") and runtime.state == "initializing") + or (path.startswith(("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/api/initializers", "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/api/saved-entries/")) and runtime.state == "initializing") or (not management and runtime.state != "ready") ): await JSONResponse( @@ -62,6 +66,7 @@ async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None: return async def execute_async() -> None: + current_operation.set(task) try: if write: async with runtime.edit_lock: diff --git a/pyrit/backend/models/converters.py b/pyrit/backend/models/converters.py index 4dc080549d..0962ac66a8 100644 --- a/pyrit/backend/models/converters.py +++ b/pyrit/backend/models/converters.py @@ -18,7 +18,8 @@ IdentifierStr, RegistrationRequest, ) -from pyrit.models import ConverterIdentifier, Parameter, PromptDataType +from pyrit.models import ConverterIdentifier, Parameter, PromptDataType, validate_registry_name +from pyrit.models.catalog import RegistryEntryOrigin from pyrit.models.component_spec import SourceInstanceSpec __all__ = [ @@ -53,6 +54,13 @@ class ConverterTypeEntry(BaseModel): ) is_llm_based: bool = Field(False, description="Whether this converter requires an LLM target") description: str | None = Field(None, description="Short description of the converter from its docstring") + not_saveable_reason: str | None = Field( + None, + description=( + "Why a converter of this type can't be saved, or None when it can be. The values a converter is given " + "are checked when it's saved" + ), + ) class ConverterTypeResponse(BaseModel): @@ -83,6 +91,13 @@ class ConverterInstance(BaseModel): parameters: list[Parameter] = Field( default_factory=list, description="Editable inputs with source-specific defaults" ) + origin: RegistryEntryOrigin | None = Field( + None, + description=( + "Where the converter comes from: 'saved' (restored at every start), 'configuration' (the server's " + "startup scripts), or 'temporary' (gone after a restart or reinitialization)" + ), + ) class ConverterInstanceListResponse(BaseModel): @@ -100,6 +115,14 @@ class CreateConverterRequest(RegistrationRequest): pattern=REGISTRY_INSTANCE_NAME_PATTERN, description="Unique registry name for the converter instance", ) + persist: bool = Field( + False, + description=( + "Save the converter so it comes back after the backend restarts or is reinitialized (true), or keep it " + "only until then (false). A saved converter needs a name of lowercase letters, digits, and underscores, " + "can't hold a key or use an uploaded file, and can't be a copy made with source or private." + ), + ) source: SourceInstanceSpec | None = None type: IdentifierStr = Field(..., description="Converter type (e.g., 'Base64Converter')") params: dict[IdentifierStr, Any] = Field( @@ -123,6 +146,22 @@ def _validate_registration(self) -> "CreateConverterRequest": raise ValueError("Use source.params for reconstruction overrides") return self + @model_validator(mode="after") + def _validate_persist(self) -> "CreateConverterRequest": + if not self.persist: + return self + if not self.register_instance: + raise ValueError("persist requires register=true") + if self.name is None: + raise ValueError("persist requires a name") + validate_registry_name(self.name) + if self.source is not None: + raise ValueError("persist can't be used with source: a copy of a converter can't be saved yet") + # A saved converter is restored with no caller, so it would come back shared. + if self.private: + raise ValueError("A private converter can't be saved; leave out persist or private") + return self + class UnregisteredConverter(BaseModel): """A constructed descriptor, without a registry ID.""" diff --git a/pyrit/backend/models/saved_entries.py b/pyrit/backend/models/saved_entries.py new file mode 100644 index 0000000000..0e34c8e878 --- /dev/null +++ b/pyrit/backend/models/saved_entries.py @@ -0,0 +1,76 @@ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT license. + +"""Request and response models for a saved registry entry's file.""" + +from typing import Any + +from pydantic import BaseModel, ConfigDict, Field + +from pyrit.models.catalog import RegistryRecipeKind, RestoreFailureReason + + +class SavedEntryResponse(BaseModel): + """A saved target, converter, scorer, or technique, as its file describes it.""" + + kind: RegistryRecipeKind = Field(..., description="The kind of entry: targets, converters, scorers, or techniques") + name: str = Field(..., description="The entry's name") + version: str | None = Field( + None, + description=( + "The file's version, to send back as expected_version when deleting it; null when the file can't be read" + ), + ) + problem: RestoreFailureReason | None = Field( + None, description="Why the file can't be used, when it can't be read or isn't a valid entry" + ) + recipe: dict[str, Any] | None = Field( + None, + description=( + "What the file saves, without who saved it, for a caller who may change it; null for anyone else and " + "when the file can't be used. Send it back changed to edit the entry." + ), + ) + can_change: bool = Field( + ..., + description=( + "Whether the caller may change or delete it, which takes an administrator. In local mode that needs " + "PYRIT_ALLOW_UNAUTHENTICATED_ADMIN=true" + ), + ) + + +class UpdateSavedEntryRequest(BaseModel): + """New settings for a saved entry, which keeps its name, its class or attack type, and who saved it.""" + + model_config = ConfigDict(extra="forbid") + + expected_version: str = Field( + ..., + min_length=1, + max_length=128, + description="The version GET returned, so a file that changed since then isn't overwritten", + ) + recipe: dict[str, Any] = Field( + ..., + description=( + "The recipe GET returned, changed. A target, converter, or scorer changes its params; a technique changes " + "anything its create request takes except its name, attack type, and persist." + ), + ) + + +class SavedEntryUpdateResponse(SavedEntryResponse): + """A saved entry after an edit.""" + + running: bool = Field( + ..., + description=( + "Whether the entry was running before the edit. False when it hadn't been restored; the edit registers " + "it once its new settings work." + ), + ) + still_using_old: list[str] = Field( + default_factory=list, + description="Registered entries that hold the entry and keep its old settings until the next apply or restart", + ) diff --git a/pyrit/backend/models/scorers.py b/pyrit/backend/models/scorers.py index e79d6d7c54..51ec126d9d 100644 --- a/pyrit/backend/models/scorers.py +++ b/pyrit/backend/models/scorers.py @@ -12,7 +12,7 @@ PaginationInfo, RegistrationRequest, ) -from pyrit.models import JSONValue, Parameter, ScorerIdentifier +from pyrit.models import JSONValue, Parameter, ScorerIdentifier, validate_registry_name from pyrit.models.catalog import ScorerInstance @@ -45,6 +45,14 @@ class CreateScorerRequest(RegistrationRequest): name: str | None = Field( None, min_length=1, pattern=REGISTRY_INSTANCE_NAME_PATTERN, description="Unique registry name" ) + persist: bool = Field( + False, + description=( + "Save the scorer so it comes back after the backend restarts or is reinitialized (true), or keep it " + "only until then (false). A saved scorer needs a name of lowercase letters, digits, and underscores, " + "and can't hold a key or be private." + ), + ) type: IdentifierStr = Field(..., description="Scorer class name") params: dict[IdentifierStr, JSONValue] = Field( default_factory=dict, max_length=MAX_ITEMS, description="Scorer constructor parameters" @@ -63,6 +71,20 @@ def _validate_registration(self) -> "CreateScorerRequest": raise ValueError("name is required when register=true") return self + @model_validator(mode="after") + def _validate_persist(self) -> "CreateScorerRequest": + if not self.persist: + return self + if not self.register_instance: + raise ValueError("persist requires register=true") + if self.name is None: + raise ValueError("persist requires a name") + validate_registry_name(self.name) + # A saved scorer is restored with no caller, so it would come back shared. + if self.private: + raise ValueError("A private scorer can't be saved; leave out persist or private") + return self + class UnregisteredScorer(BaseModel): """A scorer descriptor without a registry key.""" diff --git a/pyrit/backend/models/techniques.py b/pyrit/backend/models/techniques.py index ddad8e6207..510826b7aa 100644 --- a/pyrit/backend/models/techniques.py +++ b/pyrit/backend/models/techniques.py @@ -5,10 +5,11 @@ from typing import Annotated -from pydantic import BaseModel, ConfigDict, Field, JsonValue, field_validator +from pydantic import BaseModel, ConfigDict, Field, JsonValue, field_validator, model_validator from pyrit.backend.models.common import IdentifierStr, PaginationInfo, TextStr -from pyrit.models import ComponentIdentifier, Parameter +from pyrit.models import ComponentIdentifier, Parameter, validate_registry_name +from pyrit.models.catalog import RegistryEntryOrigin from pyrit.models.request_limits import MAX_ITEMS from pyrit.models.technique_edit import TechniqueOverride, TechniqueSettings @@ -26,6 +27,13 @@ class TechniqueInstance(BaseModel): uses_default_adversarial_target: bool identifier: ComponentIdentifier creation_statement: str + origin: RegistryEntryOrigin | None = Field( + None, + description=( + "Where the technique comes from: 'saved' (restored at every start), 'configuration' (the server's " + "startup scripts), or 'temporary' (gone after a restart or reinitialization)" + ), + ) class TechniqueListResponse(BaseModel): @@ -79,6 +87,14 @@ class CreateTechniqueRequest(BaseModel): model_config = ConfigDict(extra="forbid", strict=True, allow_inf_nan=False) name: TechniqueSelector + persist: bool = Field( + False, + description=( + "Save the technique so it comes back after the backend restarts or is reinitialized (true), or keep " + "it only until then (false). A saved technique needs a name of lowercase letters, digits, and " + "underscores, and can only use saved converters and targets or ones from the server's configuration." + ), + ) type: str = Field(min_length=1, max_length=256) params: dict[IdentifierStr, JsonValue] = Field(default_factory=dict, max_length=MAX_ITEMS) description: TextStr | None = None @@ -112,3 +128,12 @@ def _validate_tags(cls, value: list[str]) -> list[str]: if {"all", "default"} & {tag.casefold() for tag in value}: raise ValueError("all and default are reserved selectors") return value + + @model_validator(mode="after") + def _validate_persist(self) -> "CreateTechniqueRequest": + if self.persist: + validate_registry_name(self.name) + # A saved technique is restored with no caller, so it would come back shared. + if self.private: + raise ValueError("A private technique can't be saved; leave out persist or private") + return self diff --git a/pyrit/backend/routes/common.py b/pyrit/backend/routes/common.py index 7462c5185a..d1e6b0fef7 100644 --- a/pyrit/backend/routes/common.py +++ b/pyrit/backend/routes/common.py @@ -3,7 +3,16 @@ """Shared route helpers.""" -from pyrit.backend.models.common import validate_label_filter +from fastapi import Request, status +from fastapi.responses import JSONResponse + +from pyrit.backend.middleware.auth import AuthenticatedUser +from pyrit.backend.models.common import NotSaveableProblemDetail, validate_label_filter +from pyrit.models.catalog import SavedEntryOwner +from pyrit.registry import NotSaveableError + +# Problem type for an entry that can't be saved as asked but can still be created without saving it. +NOT_SAVEABLE_PROBLEM_TYPE = "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/errors/not-saveable" def parse_label_query_params(label_params: list[str] | None) -> dict[str, list[str]] | None: @@ -21,3 +30,42 @@ def parse_label_query_params(label_params: list[str] | None) -> dict[str, list[s key, _, value = validate_label_filter(param).partition(":") labels.setdefault(key.strip(), []).append(value.strip()) return labels or None + + +def saved_entry_owner_from_request(request: Request) -> SavedEntryOwner | None: + """ + Return the signed-in user to record on a saved entry. + + Args: + request: The incoming FastAPI request. + + Returns: + SavedEntryOwner | None: The user's object ID and name, or None when sign-in is off. + """ + user = getattr(request.state, "user", None) + if not isinstance(user, AuthenticatedUser): + return None + return SavedEntryOwner(oid=user.oid, name=user.name or user.email) + + +def not_saveable_response(*, error: NotSaveableError, request: Request) -> JSONResponse: + """ + Build the problem response for an entry that can't be saved as asked. + + Args: + error: Why the entry can't be saved. + request: The incoming FastAPI request. + + Returns: + JSONResponse: A 400 problem response of type ``NOT_SAVEABLE_PROBLEM_TYPE``, with the cause alone in + ``not_saveable_reason``. + """ + problem = NotSaveableProblemDetail( + type=NOT_SAVEABLE_PROBLEM_TYPE, + title="Can't be saved", + status=status.HTTP_400_BAD_REQUEST, + detail=str(error), + not_saveable_reason=error.cause, + instance=str(request.url.path), + ) + return JSONResponse(status_code=status.HTTP_400_BAD_REQUEST, content=problem.model_dump(exclude_none=True)) diff --git a/pyrit/backend/routes/converters.py b/pyrit/backend/routes/converters.py index ec78f06b52..546fcc93b9 100644 --- a/pyrit/backend/routes/converters.py +++ b/pyrit/backend/routes/converters.py @@ -8,7 +8,8 @@ Converter types are set at app startup - you cannot add new types at runtime. """ -from fastapi import APIRouter, HTTPException, status +from fastapi import APIRouter, HTTPException, Request, status +from fastapi.responses import JSONResponse from pyrit.backend.models import ( ConverterInstance, @@ -19,11 +20,19 @@ CreateConverterRequest, ProblemDetail, ) -from pyrit.backend.models.common import IdentifierStr +from pyrit.backend.models.common import IdentifierStr, NotSaveableProblemDetail from pyrit.backend.models.converters import ( UnregisteredConverter, ) +from pyrit.backend.routes.common import ( + NOT_SAVEABLE_PROBLEM_TYPE, + not_saveable_response, + saved_entry_owner_from_request, +) from pyrit.backend.services import get_converter_service +from pyrit.backend.services.saved_entries import SavedEntryRemovalError +from pyrit.registry import NotSaveableError, SavedEntryConflictError, SavedEntryStorageError +from pyrit.registry.instance_registry import RegistryNameTakenError router = APIRouter(prefix="/converters", tags=["converters"]) @@ -65,12 +74,25 @@ async def list_converter_types() -> ConverterTypeResponse: # pyrit-async-suffix response_model=ConverterInstance | UnregisteredConverter, status_code=status.HTTP_201_CREATED, responses={ - 400: {"model": ProblemDetail, "description": "Invalid converter type or parameters"}, + 400: { + "model": NotSaveableProblemDetail, + "description": ( + f"Invalid converter type or parameters, or (type {NOT_SAVEABLE_PROBLEM_TYPE}) a converter that " + "can't be saved as asked but can be created without saving it" + ), + }, + 409: { + "model": ProblemDetail, + "description": "A registered converter has the name, or, for a converter to save, a saved converter has it", + }, + 503: {"model": ProblemDetail, "description": "Saved converters can't be written right now"}, }, ) async def create_converter( - request: CreateConverterRequest, -) -> ConverterInstance | UnregisteredConverter: # pyrit-async-suffix-exempt + *, + body: CreateConverterRequest, + request: Request, +) -> ConverterInstance | UnregisteredConverter | JSONResponse: # pyrit-async-suffix-exempt """ Create a new converter instance. @@ -78,12 +100,24 @@ async def create_converter( Supports nested converters via converter_id references in params. Returns: - ConverterInstance | UnregisteredConverter: A named instance or an unregistered descriptor. + ConverterInstance | UnregisteredConverter | JSONResponse: A named instance or an unregistered descriptor, + or the problem response for a converter that can't be saved as asked. """ service = get_converter_service() try: - return await service.create_converter_async(request=request) + return await service.create_converter_async( + request=body, + owner=saved_entry_owner_from_request(request) if body.persist else None, + recipes_source=getattr(request.app.state, "registry_recipes_source", None), + ) + except NotSaveableError as e: + return not_saveable_response(error=e, request=request) + except (SavedEntryConflictError, RegistryNameTakenError) as e: + # RegistryNameTakenError is a ValueError, and a taken name is a 409 whether or not the converter is saved. + raise HTTPException(status_code=status.HTTP_409_CONFLICT, detail=str(e)) from e + except SavedEntryStorageError as e: + raise HTTPException(status_code=status.HTTP_503_SERVICE_UNAVAILABLE, detail=str(e)) from e except PermissionError as e: raise HTTPException(status_code=status.HTTP_403_FORBIDDEN, detail=str(e)) from e except ValueError as e: @@ -129,12 +163,17 @@ async def get_converter(converter_id: IdentifierStr) -> ConverterInstance: # py status_code=status.HTTP_204_NO_CONTENT, responses={ 404: {"model": ProblemDetail, "description": "Converter not found"}, + 409: {"model": ProblemDetail, "description": "The converter is saved, so it can't be removed yet"}, }, ) async def delete_converter(converter_id: IdentifierStr) -> None: # pyrit-async-suffix-exempt """Delete a converter instance by registry name.""" service = get_converter_service() - if not await service.delete_converter_async(converter_id=converter_id): + try: + removed = await service.delete_converter_async(converter_id=converter_id) + except SavedEntryRemovalError as e: + raise HTTPException(status_code=status.HTTP_409_CONFLICT, detail=str(e)) from e + if not removed: raise HTTPException( status_code=status.HTTP_404_NOT_FOUND, detail=f"Converter '{converter_id}' not found", diff --git a/pyrit/backend/routes/saved_entries.py b/pyrit/backend/routes/saved_entries.py new file mode 100644 index 0000000000..4f706ef234 --- /dev/null +++ b/pyrit/backend/routes/saved_entries.py @@ -0,0 +1,190 @@ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT license. + +""" +Saved targets, converters, scorers, and techniques, addressed by their stored files. + +These routes answer while the runtime isn't ready, so an entry that keeps it from starting can be deleted. +""" + +from typing import Annotated + +from fastapi import APIRouter, HTTPException, Path, Query, Request, status +from fastapi.responses import JSONResponse + +from pyrit.backend.middleware.auth import has_admin_access +from pyrit.backend.models import ProblemDetail +from pyrit.backend.models.common import NotSaveableProblemDetail +from pyrit.backend.models.saved_entries import SavedEntryResponse, SavedEntryUpdateResponse, UpdateSavedEntryRequest +from pyrit.backend.routes.common import NOT_SAVEABLE_PROBLEM_TYPE, not_saveable_response +from pyrit.backend.services.saved_entry_service import ( + SavedEntryForbiddenError, + SavedEntryInUseError, + SavedEntryNotFoundError, + SavedEntryRequestError, + SavedEntryService, + SavedEntryVersionRequiredError, +) +from pyrit.models import REGISTRY_NAME_PATTERN +from pyrit.models.catalog import RegistryRecipeKind +from pyrit.registry import NotSaveableError, SavedEntryConflictError, SavedEntryStorageError + +router = APIRouter(prefix="/saved-entries", tags=["saved-entries"]) + +SavedEntryName = Annotated[str, Path(pattern=REGISTRY_NAME_PATTERN, description="The saved entry's name")] + + +def _recipes_source(request: Request) -> str | None: + source = getattr(request.app.state, "registry_recipes_source", None) + return source if isinstance(source, str) else None + + +@router.get( + "/{kind}/{name}", + response_model=SavedEntryResponse, + responses={ + 404: {"model": ProblemDetail, "description": "No saved entry of the kind has the name"}, + 503: {"model": ProblemDetail, "description": "Saved entries can't be read right now"}, + }, +) +async def get_saved_entry( # pyrit-async-suffix-exempt + *, kind: RegistryRecipeKind, name: SavedEntryName, request: Request +) -> SavedEntryResponse: + """ + Get a saved entry's file version, and whether the caller may delete it. + + Returns: + SavedEntryResponse: The file's description. + + Raises: + HTTPException: 404 if no saved entry of the kind has the name, 503 if storage can't be read. + """ + try: + return await SavedEntryService().get_saved_entry_async( + kind=kind, name=name, recipes_source=_recipes_source(request), is_admin=has_admin_access(request) + ) + except SavedEntryNotFoundError as e: + raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=str(e)) from e + except SavedEntryStorageError as e: + raise HTTPException(status_code=status.HTTP_503_SERVICE_UNAVAILABLE, detail=str(e)) from e + + +@router.delete( + "/{kind}/{name}", + status_code=status.HTTP_204_NO_CONTENT, + responses={ + 403: {"model": ProblemDetail, "description": "Only an administrator can delete it"}, + 404: {"model": ProblemDetail, "description": "No saved entry of the kind has the name"}, + 409: { + "model": ProblemDetail, + "description": "It changed since it was read, something uses it, or work that could use it is in progress", + }, + 422: {"model": ProblemDetail, "description": "expected_version is missing"}, + 503: {"model": ProblemDetail, "description": "Saved entries can't be read or written right now"}, + }, +) +async def delete_saved_entry( # pyrit-async-suffix-exempt + *, + kind: RegistryRecipeKind, + name: SavedEntryName, + request: Request, + expected_version: Annotated[ + str | None, + Query( + max_length=128, + description="The version GET returned, so a file that changed since then isn't deleted. " + "Only a file that can't be read is deleted without one.", + ), + ] = None, +) -> None: + """ + Delete a saved entry's file and remove the entry it restored, so it doesn't come back after a restart. + + Raises: + HTTPException: 403, 404, 409, 422, or 503, with the reason. + """ + try: + await SavedEntryService().delete_saved_entry_async( + kind=kind, + name=name, + expected_version=expected_version, + recipes_source=_recipes_source(request), + is_admin=has_admin_access(request), + runtime=getattr(request.app.state, "runtime_lifecycle", None), + ) + except SavedEntryNotFoundError as e: + raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=str(e)) from e + except SavedEntryForbiddenError as e: + raise HTTPException(status_code=status.HTTP_403_FORBIDDEN, detail=str(e)) from e + except SavedEntryVersionRequiredError as e: + raise HTTPException(status_code=status.HTTP_422_UNPROCESSABLE_CONTENT, detail=str(e)) from e + except SavedEntryInUseError as e: + raise HTTPException(status_code=status.HTTP_409_CONFLICT, detail=str(e)) from e + except SavedEntryStorageError as e: + raise HTTPException(status_code=status.HTTP_503_SERVICE_UNAVAILABLE, detail=str(e)) from e + + +@router.put( + "/{kind}/{name}", + response_model=SavedEntryUpdateResponse, + responses={ + 400: { + "model": NotSaveableProblemDetail, + "description": f"Invalid settings, or (type {NOT_SAVEABLE_PROBLEM_TYPE}) settings that can't be saved", + }, + 403: { + "model": ProblemDetail, + "description": "Only an administrator can change it", + }, + 404: {"model": ProblemDetail, "description": "No saved entry of the kind has the name"}, + 409: { + "model": ProblemDetail, + "description": "It changed since it was read, can't be read, or the new settings conflict with another " + "entry", + }, + 422: {"model": ProblemDetail, "description": "The recipe changes the class or attack type, or isn't valid"}, + 503: {"model": ProblemDetail, "description": "Saved entries can't be read or written right now"}, + }, +) +async def update_saved_entry( # pyrit-async-suffix-exempt + *, kind: RegistryRecipeKind, name: SavedEntryName, body: UpdateSavedEntryRequest, request: Request +) -> SavedEntryUpdateResponse | JSONResponse: + """ + Change a saved entry's settings: send back the recipe GET returned, changed, with its version. + + The entry is rebuilt through the API that creates one, so the same checks apply. Its name, its class or attack + type, and who saved it stay the same. + + Returns: + SavedEntryUpdateResponse | JSONResponse: The saved file after the edit, or a not-saveable problem response. + + Raises: + HTTPException: 400, 403, 404, 409, 422, or 503, with the reason. + """ + try: + return await SavedEntryService().update_saved_entry_async( + kind=kind, + name=name, + request=body, + recipes_source=_recipes_source(request), + is_admin=has_admin_access(request), + runtime=getattr(request.app.state, "runtime_lifecycle", None), + ) + except SavedEntryNotFoundError as e: + raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=str(e)) from e + except SavedEntryForbiddenError as e: + raise HTTPException(status_code=status.HTTP_403_FORBIDDEN, detail=str(e)) from e + except SavedEntryInUseError as e: + raise HTTPException(status_code=status.HTTP_409_CONFLICT, detail=str(e)) from e + except SavedEntryRequestError as e: + raise HTTPException(status_code=status.HTTP_422_UNPROCESSABLE_CONTENT, detail=str(e)) from e + except NotSaveableError as e: + return not_saveable_response(error=e, request=request) + except SavedEntryConflictError as e: + raise HTTPException(status_code=status.HTTP_409_CONFLICT, detail=str(e)) from e + except SavedEntryStorageError as e: + raise HTTPException(status_code=status.HTTP_503_SERVICE_UNAVAILABLE, detail=str(e)) from e + except PermissionError as e: + raise HTTPException(status_code=status.HTTP_403_FORBIDDEN, detail=str(e)) from e + except ValueError as e: + raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail=str(e)) from e diff --git a/pyrit/backend/routes/scorers.py b/pyrit/backend/routes/scorers.py index 3ad570b13f..0c15c97830 100644 --- a/pyrit/backend/routes/scorers.py +++ b/pyrit/backend/routes/scorers.py @@ -3,7 +3,8 @@ """REST endpoints for scorer types and named scorer instances.""" -from fastapi import APIRouter, HTTPException, Query, status +from fastapi import APIRouter, HTTPException, Query, Request, status +from fastapi.responses import JSONResponse from pyrit.backend.models import ( CreateScorerRequest, @@ -11,12 +12,18 @@ ScorerListResponse, ScorerTypeResponse, ) -from pyrit.backend.models.common import CursorStr, IdentifierStr +from pyrit.backend.models.common import CursorStr, IdentifierStr, NotSaveableProblemDetail from pyrit.backend.models.scorers import ( UnregisteredScorer, ) +from pyrit.backend.routes.common import ( + NOT_SAVEABLE_PROBLEM_TYPE, + not_saveable_response, + saved_entry_owner_from_request, +) from pyrit.backend.services.scorer_service import get_scorer_service from pyrit.models.catalog import ScorerInstance +from pyrit.registry import NotSaveableError, SavedEntryConflictError, SavedEntryStorageError router = APIRouter(prefix="/scorers", tags=["scorers"]) @@ -50,19 +57,42 @@ async def list_scorers( "", response_model=ScorerInstance | UnregisteredScorer, status_code=status.HTTP_201_CREATED, - responses={400: {"model": ProblemDetail, "description": "Invalid scorer type, parameters, or name"}}, + responses={ + 400: { + "model": NotSaveableProblemDetail, + "description": ( + f"Invalid scorer type, parameters, or name, or (type {NOT_SAVEABLE_PROBLEM_TYPE}) a scorer that " + "can't be saved as asked but can be created without saving it" + ), + }, + 409: {"model": ProblemDetail, "description": "A scorer to save has the name of a registered or saved scorer"}, + 503: {"model": ProblemDetail, "description": "Saved scorers can't be written right now"}, + }, ) async def create_scorer( - request: CreateScorerRequest, -) -> ScorerInstance | UnregisteredScorer: # pyrit-async-suffix-exempt + *, + body: CreateScorerRequest, + request: Request, +) -> ScorerInstance | UnregisteredScorer | JSONResponse: # pyrit-async-suffix-exempt """ Construct a scorer through ScorerRegistry, with optional registration. Returns: - ScorerInstance | UnregisteredScorer: A named instance or an unregistered descriptor. + ScorerInstance | UnregisteredScorer | JSONResponse: A named instance or an unregistered descriptor, or the + problem response for a scorer that can't be saved as asked. """ try: - return await get_scorer_service().create_scorer_async(request=request) + return await get_scorer_service().create_scorer_async( + request=body, + owner=saved_entry_owner_from_request(request) if body.persist else None, + recipes_source=getattr(request.app.state, "registry_recipes_source", None), + ) + except NotSaveableError as exc: + return not_saveable_response(error=exc, request=request) + except SavedEntryConflictError as exc: + raise HTTPException(status_code=status.HTTP_409_CONFLICT, detail=str(exc)) from exc + except SavedEntryStorageError as exc: + raise HTTPException(status_code=status.HTTP_503_SERVICE_UNAVAILABLE, detail=str(exc)) from exc except PermissionError as exc: raise HTTPException(status_code=status.HTTP_403_FORBIDDEN, detail=str(exc)) from exc except ValueError as exc: diff --git a/pyrit/backend/routes/targets.py b/pyrit/backend/routes/targets.py index a93b221259..bfe869755b 100644 --- a/pyrit/backend/routes/targets.py +++ b/pyrit/backend/routes/targets.py @@ -11,7 +11,7 @@ from fastapi import APIRouter, HTTPException, Query, Request, status from fastapi.responses import JSONResponse -from pyrit.backend.middleware.auth import AuthenticatedUser, has_admin_access +from pyrit.backend.middleware.auth import has_admin_access from pyrit.backend.models import ( CreateTargetRequest, ProblemDetail, @@ -25,18 +25,20 @@ TargetTypeResponse, UnregisteredTarget, ) +from pyrit.backend.routes.common import ( + NOT_SAVEABLE_PROBLEM_TYPE, + not_saveable_response, + saved_entry_owner_from_request, +) from pyrit.backend.services import get_target_service from pyrit.backend.services.target_service import CredentialUpdateConflictError -from pyrit.models.catalog import SavedEntryOwner, TargetInstance +from pyrit.models.catalog import TargetInstance from pyrit.prompt_target.common.discover_target_capabilities import CapabilityDiscoveryError from pyrit.registry import NotSaveableError, SavedEntryConflictError, SavedEntryStorageError from pyrit.registry.instance_registry import RegistryNameTakenError router = APIRouter(prefix="/targets", tags=["targets"]) -# Problem type for a target that can't be saved as asked but can still be created without saving it. -NOT_SAVEABLE_PROBLEM_TYPE = "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/errors/not-saveable" - @router.post( "/{target_registry_name}/detect-capabilities", @@ -90,22 +92,6 @@ def _target_upload_directory(request: Request) -> str | None: return directory -def _saved_entry_owner(request: Request) -> SavedEntryOwner | None: - """ - Return the signed-in user to record on a saved target. - - Args: - request: The incoming FastAPI request. - - Returns: - SavedEntryOwner | None: The user's object ID and name, or None when sign-in is off. - """ - user = getattr(request.state, "user", None) - if not isinstance(user, AuthenticatedUser): - return None - return SavedEntryOwner(oid=user.oid, name=user.name or user.email) - - @router.get( "", response_model=TargetListResponse, @@ -237,19 +223,11 @@ async def create_target( request=body, upload_directory=_target_upload_directory(request), is_admin=has_admin_access(request), - owner=_saved_entry_owner(request) if body.persist else None, + owner=saved_entry_owner_from_request(request) if body.persist else None, recipes_source=getattr(request.app.state, "registry_recipes_source", None), ) except NotSaveableError as e: - problem = NotSaveableProblemDetail( - type=NOT_SAVEABLE_PROBLEM_TYPE, - title="Can't be saved", - status=status.HTTP_400_BAD_REQUEST, - detail=str(e), - not_saveable_reason=e.cause, - instance=str(request.url.path), - ) - return JSONResponse(status_code=status.HTTP_400_BAD_REQUEST, content=problem.model_dump(exclude_none=True)) + return not_saveable_response(error=e, request=request) except (SavedEntryConflictError, RegistryNameTakenError) as e: # RegistryNameTakenError is a ValueError, and a taken name is a 409 whether or not the target is saved. raise HTTPException(status_code=status.HTTP_409_CONFLICT, detail=str(e)) from e diff --git a/pyrit/backend/routes/techniques.py b/pyrit/backend/routes/techniques.py index 82b86c1d48..88cb21fa67 100644 --- a/pyrit/backend/routes/techniques.py +++ b/pyrit/backend/routes/techniques.py @@ -5,7 +5,8 @@ import asyncio -from fastapi import APIRouter, HTTPException, Query, status +from fastapi import APIRouter, HTTPException, Query, Request, status +from fastapi.responses import JSONResponse from pyrit.backend.models import ProblemDetail from pyrit.backend.models.common import CursorStr, IdentifierStr @@ -17,9 +18,11 @@ TechniqueListResponse, TechniqueTypeResponse, ) +from pyrit.backend.routes.common import NOT_SAVEABLE_PROBLEM_TYPE, not_saveable_response, saved_entry_owner_from_request from pyrit.backend.services.technique_edit_service import TechniqueEditService from pyrit.backend.services.technique_service import get_technique_service from pyrit.models.technique_edit import TechniqueOverride +from pyrit.registry import NotSaveableError, SavedEntryConflictError, SavedEntryStorageError router = APIRouter(prefix="/techniques", tags=["techniques"]) @@ -95,17 +98,44 @@ async def validate_technique_edit_async(name: IdentifierStr, request: TechniqueO @router.post( - "", response_model=TechniqueInstance, status_code=status.HTTP_201_CREATED, responses={400: {"model": ProblemDetail}} + "", + response_model=TechniqueInstance, + status_code=status.HTTP_201_CREATED, + responses={ + 400: { + "model": ProblemDetail, + "description": ( + f"Invalid technique, or (type {NOT_SAVEABLE_PROBLEM_TYPE}) a technique that can't be saved as asked " + "but can be created without saving it" + ), + }, + 409: { + "model": ProblemDetail, + "description": "A technique to save has the name or a tag of a registered technique", + }, + 503: {"model": ProblemDetail, "description": "Saved techniques can't be written right now"}, + }, ) -async def create_technique_async(request: CreateTechniqueRequest) -> TechniqueInstance: +async def create_technique_async(*, body: CreateTechniqueRequest, request: Request) -> TechniqueInstance | JSONResponse: """ Create a runtime factory; execution inputs remain deferred. Returns: - TechniqueInstance: The admitted factory. + TechniqueInstance | JSONResponse: The admitted factory, or the problem response for a technique that can't + be saved as asked. """ try: - return await get_technique_service().create_async(request) + return await get_technique_service().create_async( + request=body, + owner=saved_entry_owner_from_request(request) if body.persist else None, + recipes_source=getattr(request.app.state, "registry_recipes_source", None), + ) + except NotSaveableError as exc: + return not_saveable_response(error=exc, request=request) + except SavedEntryConflictError as exc: + raise HTTPException(status_code=status.HTTP_409_CONFLICT, detail=str(exc)) from exc + except SavedEntryStorageError as exc: + raise HTTPException(status_code=status.HTTP_503_SERVICE_UNAVAILABLE, detail=str(exc)) from exc except PermissionError as exc: raise HTTPException(status_code=status.HTTP_403_FORBIDDEN, detail=str(exc)) from exc except (ValueError, TypeError) as exc: diff --git a/pyrit/backend/services/converter_service.py b/pyrit/backend/services/converter_service.py index ab471fa63d..7bcf3a669c 100644 --- a/pyrit/backend/services/converter_service.py +++ b/pyrit/backend/services/converter_service.py @@ -49,11 +49,23 @@ results_container_url, validate_blob_media_url, ) +from pyrit.backend.services.saved_entries import SavedEntryRemovalError, save_then_register_locked_async from pyrit.common.azure_storage import is_azure_blob_uri from pyrit.memory import data_serializer_factory from pyrit.models import ConverterIdentifier, MessagePiece, Parameter, PromptDataType +from pyrit.models.catalog import ComponentRecipe, RegistryEntryOrigin, RegistryRecipeKind, SavedEntryOwner from pyrit.prompt_normalizer import ConverterConfiguration, PromptNormalizer -from pyrit.registry import ConverterRegistry, creator_metadata, record_private_references +from pyrit.registry import ( + ConverterRegistry, + NotSaveableError, + SavedEntryConflictError, + SavedEntryReplacement, + creator_metadata, + get_class_saveability, + prepare_saved_params_async, + record_private_references, +) +from pyrit.registry.instance_registry import RegistryNameTakenError, registry_entry_origin from pyrit.registry.registry import Reconstructable _OWNED_ARTIFACT_PATHS_KEY = "owned_artifact_paths" @@ -76,7 +88,9 @@ def __init__(self) -> None: self._artifact_lock = asyncio.Lock() self._provenance_key = secrets.token_bytes(32) - def _build_instance_from_object(self, *, converter_id: str, converter_obj: Any) -> ConverterInstance: + def _build_instance_from_object( + self, *, converter_id: str, converter_obj: Any, origin: RegistryEntryOrigin | None = None + ) -> ConverterInstance: """ Build a ConverterInstance from a registry object. @@ -92,6 +106,7 @@ def _build_instance_from_object(self, *, converter_id: str, converter_obj: Any) converter_obj=converter_obj, is_llm_based=metadata.is_llm_based if metadata else False, description=description, + origin=origin, ) if isinstance(converter_obj, Reconstructable): try: @@ -137,7 +152,9 @@ async def list_converters_async(self) -> ConverterInstanceListResponse: ConverterInstanceListResponse containing all registered converters. """ items = [ - self._build_instance_from_object(converter_id=entry.name, converter_obj=entry.instance) + self._build_instance_from_object( + converter_id=entry.name, converter_obj=entry.instance, origin=registry_entry_origin(entry.metadata) + ) for entry in self._registry.instances.get_all_instances() ] return ConverterInstanceListResponse(items=items) @@ -149,6 +166,7 @@ async def list_converter_types_async(self) -> ConverterTypeResponse: Returns every converter that external callers can build, with only the parameters they may supply, each described in the form callers send it; converters that need a Python object for a required parameter are left out. + Each says why a converter of its type can't be saved, if it can't. Deciding which entries to surface to a user is a presentation concern owned by the caller (e.g. the frontend), not this service. @@ -165,6 +183,7 @@ async def list_converter_types_async(self) -> ConverterTypeResponse: ], is_llm_based=metadata.is_llm_based, description=metadata.class_description or None, + not_saveable_reason=self._get_not_saveable_reason(converter_type=metadata.class_name), ) for metadata in self._registry.get_all_registered_class_metadata() if all(parameter.is_external_input for parameter in metadata.parameters if parameter.required) @@ -172,6 +191,16 @@ async def list_converter_types_async(self) -> ConverterTypeResponse: return ConverterTypeResponse(items=items) + def _get_not_saveable_reason(self, *, converter_type: str) -> str | None: + """ + Return why a converter of a type can't be saved, whatever its values, or None when it can be. + + Returns: + str | None: The reason, or None when a converter of the type can be saved. + """ + _, reason = get_class_saveability(registry=self._registry, type_name=converter_type) + return reason or self._required_upload_refusal(converter_type=converter_type) + async def get_converter_async(self, *, converter_id: str) -> ConverterInstance | None: """ Get a converter instance by ID. @@ -179,10 +208,12 @@ async def get_converter_async(self, *, converter_id: str) -> ConverterInstance | Returns: ConverterInstance if found, None otherwise. """ - obj = self._registry.instances.get(converter_id) - if obj is None: + entry = self._registry.instances.get_entry(converter_id) + if entry is None: return None - return self._build_instance_from_object(converter_id=converter_id, converter_obj=obj) + return self._build_instance_from_object( + converter_id=converter_id, converter_obj=entry.instance, origin=registry_entry_origin(entry.metadata) + ) def get_converter_object(self, *, converter_id: str) -> Any | None: """ @@ -199,11 +230,19 @@ async def delete_converter_async(self, *, converter_id: str) -> bool: Returns: bool: True when an instance was removed, otherwise False. + + Raises: + SavedEntryRemovalError: If the converter is saved, so it would come back from its saved file. """ async with self._artifact_lock: entry = self._registry.instances.get_entry(converter_id) if entry is None: return False + if registry_entry_origin(entry.metadata) is RegistryEntryOrigin.SAVED: + raise SavedEntryRemovalError( + f"Saved converter '{converter_id}' comes back from its saved file at every start, so delete it " + f"with DELETE /api/saved-entries/converters/{converter_id} instead." + ) owned_paths = self._get_owned_artifact_paths(entry.metadata) # Other callers' private converters can share these files too. @@ -218,7 +257,12 @@ async def delete_converter_async(self, *, converter_id: str) -> bool: return self._registry.instances.unregister(converter_id, expected_entry=entry) is not None async def create_converter_async( - self, *, request: CreateConverterRequest + self, + *, + request: CreateConverterRequest, + owner: SavedEntryOwner | None = None, + recipes_source: str | None = None, + replacing: SavedEntryReplacement | None = None, ) -> ConverterInstance | UnregisteredConverter: """ Create a new converter instance from API request. @@ -226,10 +270,15 @@ async def create_converter_async( Instantiates the converter with the given type and params and builds the response before registering it, so a request that fails at any step leaves no registered converter and removes its uploaded files. A converter built from - the caller's private target or converter is private to the caller too. + the caller's private target or converter is private to the caller too. With + ``persist``, the converter is saved so it is restored at every start; otherwise + it is Temporary. Args: request: The create converter request with type and params. + owner: The signed-in user, recorded on a saved converter, or None when sign-in is off. + recipes_source: Where saved entries are stored, or None for the default folder. + replacing: The saved converter an edit rebuilds, whose recipe is overwritten instead of created, or None. Returns: ConverterInstance with the new converter's details. @@ -237,16 +286,30 @@ async def create_converter_async( Raises: ValueError: If the converter type is not found or the registry name is unavailable. + NotSaveableError: If a converter to save would hold a credential or use an uploaded file, or + names a Temporary entry. + SavedEntryConflictError: If a converter to save has the name of a registered or saved converter. + SavedEntryStorageError: If a converter to save can't be written to storage. """ if request.private and not request.register_instance: raise ValueError("A private converter must be registered; set register=true.") with record_private_references() as private_references: return await self._create_converter_recording_private_references_async( - request=request, private_references=private_references + request=request, + private_references=private_references, + owner=owner, + recipes_source=recipes_source, + replacing=replacing, ) async def _create_converter_recording_private_references_async( - self, *, request: CreateConverterRequest, private_references: dict[str, str] + self, + *, + request: CreateConverterRequest, + private_references: dict[str, str], + owner: SavedEntryOwner | None, + recipes_source: str | None, + replacing: SavedEntryReplacement | None, ) -> ConverterInstance | UnregisteredConverter: """ Create a converter while the private entries it uses are recorded in ``private_references``. @@ -259,6 +322,15 @@ async def _create_converter_recording_private_references_async( """ if request.type not in self._registry: raise ValueError(f"Converter type '{request.type}' not found") + if request.persist and request.name is not None: + return await self._save_converter_async( + name=request.name, + request=request, + private_references=private_references, + owner=owner, + recipes_source=recipes_source, + replacing=replacing, + ) if request.register_instance: if request.name is None: raise ValueError("name is required when register=true") @@ -310,7 +382,9 @@ async def _create_converter_recording_private_references_async( ) if request.name is None: raise ValueError("name is required when register=true") - converter = self._build_instance_from_object(converter_id=request.name, converter_obj=converter_obj) + converter = self._build_instance_from_object( + converter_id=request.name, converter_obj=converter_obj, origin=RegistryEntryOrigin.TEMPORARY + ) # Do not inherit files while deletion is already removing them. async with self._artifact_lock: inherited_paths: list[Path] = [] @@ -345,6 +419,68 @@ async def _create_converter_recording_private_references_async( return converter + async def _save_converter_async( + self, + *, + name: str, + request: CreateConverterRequest, + private_references: dict[str, str], + owner: SavedEntryOwner | None, + recipes_source: str | None, + replacing: SavedEntryReplacement | None = None, + ) -> ConverterInstance: + """ + Build the requested converter, save its recipe, then register it as a saved entry. + + It is built as restore builds it, with no file parameters, and the recipe names the class by + the registry name the request used, which restore looks up. + + Returns: + ConverterInstance: The saved converter. + + Raises: + NotSaveableError: If the converter would hold a credential or use an uploaded file, or names a + Temporary entry. + SavedEntryConflictError: If a saved or registered converter already has the name. + SavedEntryStorageError: If the recipe can't be written, or can't be deleted after registering failed. + """ + refusal = self._required_upload_refusal(converter_type=request.type) + if refusal is not None: + raise NotSaveableError(refusal) + uploads = [ + parameter for parameter in self._upload_params(converter_type=request.type) if parameter in request.params + ] + if uploads: + raise NotSaveableError(f"Saved converters can't keep uploaded files yet ('{uploads[0]}').") + converter_cls = self._registry.get_class(request.type) + params = await prepare_saved_params_async( + registry=self._registry, type_name=request.type, cls=converter_cls, params=request.params + ) + try: + self._registry.instances.validate_name_available(name) + except RegistryNameTakenError as error: + raise SavedEntryConflictError(str(error)) from error + converter_obj = await construct_component_async( + self._registry.create_instance_from_external_input, request.type, params=params + ) + converter = self._build_instance_from_object( + converter_id=name, converter_obj=converter_obj, origin=RegistryEntryOrigin.SAVED + ) + creator = creator_metadata(name=name, requested_private=request.private, private_references=private_references) + await save_then_register_locked_async( + kind=RegistryRecipeKind.CONVERTERS, + name=name, + recipe=ComponentRecipe( + class_module=converter_cls.__module__, class_name=request.type, params=params, owner=owner + ), + source=recipes_source, + register=lambda metadata: self._registry.instances.register( + converter_obj, name=name, metadata={**creator, **metadata} + ), + replacing=replacing, + ) + return converter + async def preview_conversion_async(self, *, request: ConverterPreviewRequest) -> ConverterPreviewResponse: """ Preview conversion through a converter pipeline. @@ -482,6 +618,22 @@ def _upload_params(self, *, converter_type: str) -> dict[str, Parameter]: if parameter.is_path or parameter.is_path_or_str } + def _required_upload_refusal(self, *, converter_type: str) -> str | None: + """ + Return why a converter type that needs an uploaded file can't be saved. + + Args: + converter_type (str): The registered converter class name. + + Returns: + str | None: The reason, or None when the type needs no uploaded file. + """ + if any(parameter.required for parameter in self._upload_params(converter_type=converter_type).values()): + return ( + f"'{converter_type}' can't be saved. It needs an uploaded file, which saved converters can't keep yet." + ) + return None + async def _persist_data_uri_params_async( self, *, diff --git a/pyrit/backend/services/runtime_lifecycle.py b/pyrit/backend/services/runtime_lifecycle.py index 1c5a73a7ae..f1cffba18e 100644 --- a/pyrit/backend/services/runtime_lifecycle.py +++ b/pyrit/backend/services/runtime_lifecycle.py @@ -7,6 +7,7 @@ import logging import os import uuid +from contextvars import ContextVar from functools import partial from typing import TYPE_CHECKING, Any @@ -38,10 +39,13 @@ from pyrit.setup.initialization import validate_reinitialization_memory if TYPE_CHECKING: - from pyrit.models.catalog import IgnoredRecipeFile, RestoreFailure + from pyrit.models.catalog import IgnoredRecipeFile, RestoreFailure, SavedEntryRef logger = logging.getLogger(__name__) +# The admitted request that the running code belongs to, so a request doesn't count itself as work in progress. +current_operation: ContextVar[asyncio.Task[None] | None] = ContextVar("pyrit_runtime_operation", default=None) + class RuntimeLifecycle: """Own runtime readiness, admission, preflight, and idle replacement.""" @@ -317,8 +321,28 @@ async def _apply_async(self, *, version: str) -> None: finally: logger.info("PyRIT apply outcome=%s generation=%s", self.outcome, self.generation) - def _has_active_work(self) -> bool: - """Return whether any admitted or background runtime operation remains.""" + def has_active_work(self) -> bool: + """ + Return whether a run, send, estimate, or another request could still be using a registered entry. + + Returns: + bool: Whether any admitted or background runtime operation remains, apart from the caller's request. + """ + return self._has_active_work(excluding=current_operation.get()) + + def forget_restore_failure(self, ref: "SavedEntryRef") -> None: + """ + Stop listing a saved entry whose file was deleted among the ones that couldn't be restored. + + Args: + ref (SavedEntryRef): The deleted entry. + """ + self.restore_failures = [ + failure for failure in self.restore_failures if (failure.kind, failure.name) != (ref.kind, ref.name) + ] + + def _has_active_work(self, *, excluding: asyncio.Task[None] | None = None) -> bool: + """Return whether any admitted or background runtime operation remains, other than ``excluding``.""" service = peek_scenario_run_service() suite_execution_service = peek_scenario_suite_execution_service() generation_service = peek_prompt_generation_service() @@ -326,7 +350,7 @@ def _has_active_work(self) -> bool: (service and service.has_active_work()) or (suite_execution_service and suite_execution_service.has_active_work()) or (generation_service and generation_service.has_active_work()) - or self.operations + or any(operation is not excluding for operation in self.operations) or outstanding_estimates() or has_active_manual_sends() or has_active_analytics_work() diff --git a/pyrit/backend/services/saved_entries.py b/pyrit/backend/services/saved_entries.py new file mode 100644 index 0000000000..6b9cef8a84 --- /dev/null +++ b/pyrit/backend/services/saved_entries.py @@ -0,0 +1,118 @@ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT license. + +""" +Coordinate saved registry entries in the API, around the registry library that saves them. + +Saving, changing, and deleting saved entries hold one lock, so a delete can't miss a save that names the entry it +deletes, and an edit can't race another change. +""" + +import asyncio +import weakref +from collections.abc import AsyncGenerator, Callable, Mapping +from contextlib import asynccontextmanager +from contextvars import ContextVar +from typing import Any + +from pyrit.models.catalog import ComponentRecipe, RegistryRecipeKind, TechniqueRecipe +from pyrit.registry import ( + AttackTechniqueRegistry, + ConverterRegistry, + SavedEntryReplacement, + ScorerRegistry, + TargetRegistry, + save_then_register_async, +) + +_SAVED_ENTRY_LOCKS: "weakref.WeakKeyDictionary[asyncio.AbstractEventLoop, asyncio.Lock]" = weakref.WeakKeyDictionary() + +REGISTRIES_BY_KIND: Mapping[RegistryRecipeKind, Any] = { + RegistryRecipeKind.TARGETS: TargetRegistry, + RegistryRecipeKind.CONVERTERS: ConverterRegistry, + RegistryRecipeKind.SCORERS: ScorerRegistry, + RegistryRecipeKind.TECHNIQUES: AttackTechniqueRegistry, +} + +# Whether the running task holds the lock, so it can't wait on it a second time. +_HOLDING_SAVED_ENTRY_LOCK: ContextVar[bool] = ContextVar("_holding_saved_entry_lock", default=False) + + +class SavedEntryRemovalError(RuntimeError): + """A saved entry can't be removed through the API yet, since it comes back from its saved file at every start.""" + + +def saved_entry_lock() -> asyncio.Lock: + """ + Return the lock that saving and deleting saved entries hold, so a delete can't miss a save that names the entry. + + Returns: + asyncio.Lock: The lock for the running event loop. + """ + loop = asyncio.get_running_loop() + lock = _SAVED_ENTRY_LOCKS.get(loop) + if lock is None: + lock = _SAVED_ENTRY_LOCKS[loop] = asyncio.Lock() + return lock + + +@asynccontextmanager +async def hold_saved_entry_lock_async() -> AsyncGenerator[None, None]: + """ + Hold the lock that saving, changing, and deleting saved entries take. + + Yields: + None: While the lock is held. + + Raises: + RuntimeError: If the running task already holds it, which would otherwise wait forever. + """ + if _HOLDING_SAVED_ENTRY_LOCK.get(): + raise RuntimeError("This task already holds the saved entry lock, so it can't take it again.") + async with saved_entry_lock(): + token = _HOLDING_SAVED_ENTRY_LOCK.set(True) + try: + yield + finally: + _HOLDING_SAVED_ENTRY_LOCK.reset(token) + + +async def save_then_register_locked_async( + *, + kind: RegistryRecipeKind, + name: str, + recipe: ComponentRecipe | TechniqueRecipe, + register: Callable[[dict[str, Any]], object], + source: str | None, + replacing: SavedEntryReplacement | None = None, +) -> None: + """ + Save an entry through the registry library while holding the lock deleting takes. + + An edit already holds the lock through ``hold_saved_entry_lock_async()``, so a replacement is saved under it. + + Args: + kind (RegistryRecipeKind): The kind of entry. + name (str): The entry's name. + recipe (ComponentRecipe | TechniqueRecipe): How to rebuild the entry, naming who saved it. + register (Callable[[dict[str, Any]], object]): Registers the built entry with the metadata it's given. + source (str | None): Where saved entries are stored, or None for the default folder. + replacing (SavedEntryReplacement | None): The saved entry an edit rebuilds, whose recipe is overwritten + instead, or None to save a new entry. Defaults to None. + + Raises: + RuntimeError: If an edit replaces a saved entry without holding the lock. + SavedEntryConflictError: If a saved or registered entry of the kind already has the name, an entry the + recipe names was deleted, or the recipe an edit replaces changed since it was read. + SavedEntryStorageError: If the recipe can't be written, or can't be deleted or put back after registering + failed. + """ + if replacing is not None: + if not _HOLDING_SAVED_ENTRY_LOCK.get(): + raise RuntimeError("An edit must hold the saved entry lock while it replaces a saved entry.") + await save_then_register_async( + kind=kind, name=name, recipe=recipe, register=register, source=source, replacing=replacing + ) + return + async with hold_saved_entry_lock_async(): + await save_then_register_async(kind=kind, name=name, recipe=recipe, register=register, source=source) diff --git a/pyrit/backend/services/saved_entry_restore.py b/pyrit/backend/services/saved_entry_restore.py index c2cda4a33e..2593a11005 100644 --- a/pyrit/backend/services/saved_entry_restore.py +++ b/pyrit/backend/services/saved_entry_restore.py @@ -42,7 +42,7 @@ async def build_saved_entry_async(stored: StoredRecipe, *, upload_directory: str request = _create_request(stored) with caller_principal_scope(None): if isinstance(request, CreateTechniqueRequest): - await get_technique_service().create_async(request) + await get_technique_service().create_async(request=request) elif isinstance(request, CreateTargetRequest): await get_target_service().create_target_async( request=request, upload_directory=upload_directory, is_admin=True @@ -70,7 +70,7 @@ def _create_request( try: if isinstance(recipe, TechniqueRecipe): return CreateTechniqueRequest.model_validate( - fields | recipe.model_dump(exclude_unset=True, exclude={"schema_version"}) + fields | recipe.model_dump(exclude_unset=True, exclude={"schema_version", "owner"}) ) fields |= {"type": recipe.class_name, "params": recipe.params} if stored.ref.kind is RegistryRecipeKind.TARGETS: diff --git a/pyrit/backend/services/saved_entry_service.py b/pyrit/backend/services/saved_entry_service.py new file mode 100644 index 0000000000..7502b64649 --- /dev/null +++ b/pyrit/backend/services/saved_entry_service.py @@ -0,0 +1,615 @@ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT license. + +""" +Look up, change, and delete saved registry entries through their stored files. + +Saved entries are shared, so only an administrator may change or delete one, as for scenario presets and suites. +The person who saved an entry is kept in its file as attribution only. An entry that another saved entry names, or +that a registered entry holds, isn't deleted. An edit rebuilds the entry through the API that creates one, so it +passes every check a new entry does. +""" + +from __future__ import annotations + +import asyncio +import dataclasses +import logging +from collections.abc import Mapping +from typing import TYPE_CHECKING, Any + +from pydantic import ValidationError + +from pyrit.backend.models import CreateConverterRequest, CreateScorerRequest, CreateTargetRequest +from pyrit.backend.models.saved_entries import ( + SavedEntryResponse, + SavedEntryUpdateResponse, + UpdateSavedEntryRequest, +) +from pyrit.backend.models.techniques import CreateTechniqueRequest +from pyrit.backend.services import get_converter_service, get_target_service +from pyrit.backend.services.component_lifecycle import release_component_async +from pyrit.backend.services.saved_entries import REGISTRIES_BY_KIND, hold_saved_entry_lock_async +from pyrit.backend.services.scorer_service import get_scorer_service +from pyrit.backend.services.technique_service import get_technique_service +from pyrit.models import ComponentIdentifier, Identifiable +from pyrit.models.catalog import ( + ComponentRecipe, + RegistryEntryOrigin, + RegistryRecipeKind, + RestoreFailure, + SavedEntryRef, + StoredRecipe, + TechniqueRecipe, +) +from pyrit.registry import SavedEntryReplacement, SavedEntryStorageError, is_visible_to_caller +from pyrit.registry.file_document_storage import DocumentConflictError, DocumentStorageUnavailableError +from pyrit.registry.instance_registry import registry_entry_origin +from pyrit.registry.registry_recipe_restore import RegistryRecipeRestorer +from pyrit.registry.registry_recipe_storage import RegistryRecipeStorage + +if TYPE_CHECKING: + from pyrit.backend.services.runtime_lifecycle import RuntimeLifecycle + from pyrit.registry import RegistryEntry + +logger = logging.getLogger(__name__) + +# Deep enough for an attack's converter and scoring settings, which hold lists of configurations. +_MAX_SETTINGS_DEPTH = 8 +# Requests such as a list refresh finish quickly, so a delete waits briefly for them before saying it's busy. +_IDLE_WAIT_SECONDS = 2.0 +_IDLE_CHECK_SECONDS = 0.05 +_ORIGIN_WORDS = { + RegistryEntryOrigin.SAVED: "saved", + RegistryEntryOrigin.CONFIGURATION: "startup", + RegistryEntryOrigin.TEMPORARY: "temporary", +} + + +class SavedEntryNotFoundError(LookupError): + """No saved entry of the kind has the name.""" + + +class SavedEntryForbiddenError(PermissionError): + """The caller isn't an administrator, so may not change or delete the saved entry.""" + + +class SavedEntryVersionRequiredError(ValueError): + """A delete didn't say which version of the saved file it read.""" + + +class SavedEntryInUseError(ValueError): + """The saved entry changed since it was read, or something still uses it.""" + + +class SavedEntryRequestError(ValueError): + """An edit asks for a change a saved entry can't make, such as a different class.""" + + +class SavedEntryService: + """Look up and delete saved targets, converters, scorers, and techniques.""" + + async def get_saved_entry_async( + self, *, kind: RegistryRecipeKind, name: str, recipes_source: str | None, is_admin: bool + ) -> SavedEntryResponse: + """ + Describe a saved entry's file: its version, and whether the caller may change it. + + Args: + kind (RegistryRecipeKind): The kind of entry. + name (str): The entry's name. + recipes_source (str | None): Where saved entries are stored, or None for the default folder. + is_admin (bool): Whether the caller is an administrator. + + Returns: + SavedEntryResponse: The file's description. + + Raises: + SavedEntryNotFoundError: If no saved entry of the kind has the name. + SavedEntryStorageError: If storage can't be read. + """ + stored = await _read_async( + storage=RegistryRecipeStorage(kind=kind, source=recipes_source), kind=kind, name=name + ) + return _describe(kind=kind, name=name, stored=stored, is_admin=is_admin) + + async def update_saved_entry_async( + self, + *, + kind: RegistryRecipeKind, + name: str, + request: UpdateSavedEntryRequest, + recipes_source: str | None, + is_admin: bool, + runtime: RuntimeLifecycle | None, + ) -> SavedEntryUpdateResponse: + """ + Change a saved entry's settings, rebuilding it through the API that creates one. + + The running entry is removed while it's rebuilt and put back if the edit fails. Registered entries that hold + it keep the old object until the next apply or restart. An entry that hadn't been restored is only saved; the + next apply or restart restores it. The name, the class or attack type, and who saved it stay the same. + + Args: + kind (RegistryRecipeKind): The kind of entry. + name (str): The entry's name. + request (UpdateSavedEntryRequest): The version the caller read and the changed recipe. + recipes_source (str | None): Where saved entries are stored, or None for the default folder. + is_admin (bool): Whether the caller is an administrator, which changing takes. + runtime (RuntimeLifecycle | None): The runtime, to keep the old entry's resources open while work could + still be using it. + + Returns: + SavedEntryUpdateResponse: The saved file after the edit, and what still holds the old entry. + + Raises: + SavedEntryNotFoundError: If no saved entry of the kind has the name. + SavedEntryForbiddenError: If the caller isn't an administrator. + SavedEntryInUseError: If the file changed since it was read, or can't be read or isn't a valid entry. + SavedEntryRequestError: If the recipe changes the class or attack type, or what a saved entry can't hold. + NotSaveableError: If the new settings can't be saved, as for a new entry. + SavedEntryConflictError: If the new settings conflict with another entry, as for a new entry. + SavedEntryStorageError: If storage can't be read or written. + PermissionError: If the new settings need an administrator, as for a new entry. + ValueError: If the new settings aren't valid, as for a new entry. + """ + singular = _singular(kind) + storage = RegistryRecipeStorage(kind=kind, source=recipes_source) + async with hold_saved_entry_lock_async(): + stored = await _read_async(storage=storage, kind=kind, name=name) + if not is_admin: + raise SavedEntryForbiddenError(f"Only an administrator can change saved {singular} '{name}'.") + if not isinstance(stored, StoredRecipe): + raise SavedEntryInUseError( + f"Saved {singular} '{name}' can't be read or isn't a valid entry, so it can't be changed. " + "Delete it, then save it again." + ) + if request.expected_version != stored.version: + raise SavedEntryInUseError( + f"Saved {singular} '{name}' changed since it was read. Look at it again before changing it." + ) + instances = REGISTRIES_BY_KIND[kind].get_registry_singleton().instances + entry = instances.get_entry(name) + if entry is not None and registry_entry_origin(entry.metadata) is not RegistryEntryOrigin.SAVED: + entry = None + if entry is not None: + instances.unregister(name, expected_entry=entry) + try: + await _rebuild_async( + kind=kind, + name=name, + stored=stored.recipe, + changed=request.recipe, + is_admin=is_admin, + recipes_source=recipes_source, + replacing=SavedEntryReplacement( + version=stored.version, previous=stored.recipe, running=entry is not None + ), + ) + except BaseException: + # A cancelled edit finishes saving before it stops, so the rebuilt entry may hold the name by now. + if instances.get_entry(name) is None: + _put_back(kind=kind, entry=entry) + raise + # Listed after the rebuild, since a request that finished during it may have registered an entry that + # holds the old one. + holders = _holders(kind=kind, entry=entry) if entry is not None else [] + if ( + entry is not None + and not holders + and not _registered_anywhere(entry.instance) + and (runtime is None or not runtime.has_active_work()) + ): + await release_component_async(entry.instance) + updated = await _read_async(storage=storage, kind=kind, name=name) + return SavedEntryUpdateResponse( + **_describe(kind=kind, name=name, stored=updated, is_admin=is_admin).model_dump(), + running=entry is not None, + still_using_old=holders, + ) + + async def delete_saved_entry_async( + self, + *, + kind: RegistryRecipeKind, + name: str, + expected_version: str | None, + recipes_source: str | None, + is_admin: bool, + runtime: RuntimeLifecycle | None, + ) -> None: + """ + Delete a saved entry's file and remove the entry it restored, so it doesn't come back. + + The running entry is removed before its file is deleted, so no request can pick it up in between, and is + put back if the file can't be deleted. A startup entry that has the same name stays. Deleting an entry that + couldn't be restored takes it off the runtime's list of restore failures. + + Args: + kind (RegistryRecipeKind): The kind of entry. + name (str): The entry's name. + expected_version (str | None): The file version the caller read. Required unless the file can't be read. + recipes_source (str | None): Where saved entries are stored, or None for the default folder. + is_admin (bool): Whether the caller is an administrator, which deleting takes. + runtime (RuntimeLifecycle | None): The runtime, to check that nothing is using the entry and to stop + listing it among the entries that couldn't be restored. + + Raises: + SavedEntryNotFoundError: If no saved entry of the kind has the name. + SavedEntryForbiddenError: If the caller isn't an administrator. + SavedEntryVersionRequiredError: If ``expected_version`` is missing for a file that can be read. + SavedEntryInUseError: If the file changed since it was read, another saved entry names it, a registered + entry holds it, or a request, run, or send is in progress. + SavedEntryStorageError: If storage can't be read or written. + """ + singular = _singular(kind) + storage = RegistryRecipeStorage(kind=kind, source=recipes_source) + async with hold_saved_entry_lock_async(): + stored = await _read_async(storage=storage, kind=kind, name=name) + if not is_admin: + raise SavedEntryForbiddenError(f"Only an administrator can delete saved {singular} '{name}'.") + if stored.version is not None: + if expected_version is None: + raise SavedEntryVersionRequiredError( + f"Send the version of saved {singular} '{name}' you read as expected_version." + ) + if expected_version != stored.version: + raise SavedEntryInUseError(_changed_message(singular=singular, name=name)) + users = await _saved_users_async(kind=kind, name=name, recipes_source=recipes_source) + if users: + raise SavedEntryInUseError(_in_use_message(singular=singular, name=name, users=users)) + instances = REGISTRIES_BY_KIND[kind].get_registry_singleton().instances + entry = instances.get_entry(name) + if entry is not None and registry_entry_origin(entry.metadata) is not RegistryEntryOrigin.SAVED: + entry = None + if entry is not None: + _refuse_held(kind=kind, entry=entry) + if runtime is not None and not await _wait_until_idle_async(runtime): + raise SavedEntryInUseError( + f"Saved {singular} '{name}' could be in use by a request, run, or send in progress. " + "Try again when it finishes." + ) + # A request that finished during the wait may have registered an entry that holds this one. + _refuse_held(kind=kind, entry=entry) + instances.unregister(name, expected_entry=entry) + try: + await asyncio.to_thread(storage.delete_recipe, name, expected_version=stored.version) + except DocumentConflictError as error: + _put_back(kind=kind, entry=entry) + raise SavedEntryInUseError(_changed_message(singular=singular, name=name)) from error + except DocumentStorageUnavailableError as error: + _put_back(kind=kind, entry=entry) + logger.error( + "Saved %s '%s' couldn't be deleted from %s (%s).", + singular, + name, + storage.display_source, + error.reason, + ) + raise SavedEntryStorageError(f"Saved {kind.value} can't be deleted right now.") from error + if entry is not None and not _registered_anywhere(entry.instance): + await release_component_async(entry.instance) + if runtime is not None: + runtime.forget_restore_failure(SavedEntryRef(kind=kind, name=name)) + + +def _describe( + *, kind: RegistryRecipeKind, name: str, stored: StoredRecipe | RestoreFailure, is_admin: bool +) -> SavedEntryResponse: + """ + Describe a saved entry's file for the caller. + + Returns: + SavedEntryResponse: Its version and problem, whether the caller may change it, and, for an administrator, + what it saves. + """ + recipe = ( + stored.recipe.model_dump(mode="json", exclude_none=True, exclude={"owner"}) + if is_admin and isinstance(stored, StoredRecipe) + else None + ) + return SavedEntryResponse( + kind=kind, + name=name, + version=stored.version, + problem=stored.reason if isinstance(stored, RestoreFailure) else None, + recipe=recipe, + can_change=is_admin, + ) + + +async def _rebuild_async( + *, + kind: RegistryRecipeKind, + name: str, + stored: ComponentRecipe | TechniqueRecipe, + changed: dict[str, Any], + is_admin: bool, + recipes_source: str | None, + replacing: SavedEntryReplacement, +) -> None: + """ + Build an edited entry through the API that creates one, overwriting its recipe and registering it. + + Raises: + SavedEntryRequestError: If the recipe changes the name, class, attack type, or who saved the entry, or holds + fields a saved entry of the kind doesn't have. + """ + singular = _singular(kind) + owner = stored.owner + stored_owner = owner.model_dump(mode="json") if owner is not None else None + if changed.get("owner", stored_owner) != stored_owner: + raise SavedEntryRequestError(f"Who saved a saved {singular} can't change; leave out owner.") + changes = {key: value for key, value in changed.items() if key not in ("schema_version", "owner")} + try: + if isinstance(stored, TechniqueRecipe): + if changes.pop("type", stored.type) != stored.type: + raise SavedEntryRequestError( + "A saved technique's attack type can't change. Delete it and save a new one instead." + ) + if changes.pop("name", name) != name or changes.pop("persist", True) is not True: + raise SavedEntryRequestError( + "A saved technique keeps its name and stays saved. Delete it and save a new one instead." + ) + technique = CreateTechniqueRequest(name=name, type=stored.type, persist=True, **changes) + await get_technique_service().create_async( + request=technique, owner=owner, recipes_source=recipes_source, replacing=replacing + ) + return + for key in ("class_module", "class_name"): + if changes.pop(key, getattr(stored, key)) != getattr(stored, key): + raise SavedEntryRequestError( + f"A saved {singular}'s class can't change. Delete it and save a new one instead." + ) + params = changes.pop("params", {}) + # A target's auth mode sits beside its params, as in the create request; one left out stays as saved. + auth_mode = changes.pop("auth_mode", stored.auth_mode) if kind is RegistryRecipeKind.TARGETS else None + if changes: + changeable = "params and auth_mode" if kind is RegistryRecipeKind.TARGETS else "params" + raise SavedEntryRequestError( + f"Only the {changeable} of a saved {singular} can change; leave out {sorted(changes)}." + ) + if not isinstance(params, dict): + raise SavedEntryRequestError(f"A saved {singular}'s params must be an object.") + if kind is RegistryRecipeKind.TARGETS: + target = CreateTargetRequest( + name=name, + type=stored.class_name, + params=params, + persist=True, + **({"auth_mode": auth_mode} if auth_mode is not None else {}), + ) + await get_target_service().create_target_async( + request=target, + is_admin=is_admin, + owner=owner, + recipes_source=recipes_source, + replacing=replacing, + ) + elif kind is RegistryRecipeKind.CONVERTERS: + converter = CreateConverterRequest(name=name, type=stored.class_name, params=params, persist=True) + await get_converter_service().create_converter_async( + request=converter, owner=owner, recipes_source=recipes_source, replacing=replacing + ) + else: + scorer = CreateScorerRequest(name=name, type=stored.class_name, params=params, persist=True) + await get_scorer_service().create_scorer_async( + request=scorer, owner=owner, recipes_source=recipes_source, replacing=replacing + ) + except ValidationError as error: + raise SavedEntryRequestError(f"The changed recipe isn't valid for a saved {singular}: {error}") from error + + +async def _wait_until_idle_async(runtime: RuntimeLifecycle) -> bool: + """ + Wait briefly for requests in flight to finish. + + Nothing is awaited after the last check, so the caller can act on the answer before any other request starts. + + Returns: + bool: Whether nothing could be using a registered entry. Runs, sends, and estimates usually outlast the wait. + """ + loop = asyncio.get_running_loop() + deadline = loop.time() + _IDLE_WAIT_SECONDS + while runtime.has_active_work(): + if loop.time() >= deadline: + return False + await asyncio.sleep(_IDLE_CHECK_SECONDS) + return True + + +async def _read_async( + *, storage: RegistryRecipeStorage, kind: RegistryRecipeKind, name: str +) -> StoredRecipe | RestoreFailure: + """ + Read one saved entry's file off the event loop. + + Returns: + StoredRecipe | RestoreFailure: The recipe, or why its file can't be used. + + Raises: + SavedEntryNotFoundError: If no saved entry of the kind has the name. + SavedEntryStorageError: If storage can't be read. + """ + try: + stored = await asyncio.to_thread(storage.read_recipe, name) + except DocumentStorageUnavailableError as error: + logger.error( + "Saved %s '%s' couldn't be read from %s (%s).", + _singular(kind), + name, + storage.display_source, + error.reason, + ) + raise SavedEntryStorageError(f"Saved {kind.value} can't be read right now.") from error + if stored is None: + raise SavedEntryNotFoundError(f"No saved {_singular(kind)} is named '{name}'.") + return stored + + +async def _saved_users_async(*, kind: RegistryRecipeKind, name: str, recipes_source: str | None) -> list[str]: + """ + List the other saved entries whose files name this one, as restoring them would read them. + + Returns: + list[str]: Each one described as, for example, "saved technique 'formal_crescendo'". + + Raises: + SavedEntryStorageError: If storage can't be read. + """ + ref = SavedEntryRef(kind=kind, name=name) + restorer = RegistryRecipeRestorer(source=recipes_source) + + def scan() -> list[str]: + users = [] + for other_kind in RegistryRecipeKind: + listing = RegistryRecipeStorage(kind=other_kind, source=recipes_source).list_recipes() + for other_name, other in sorted(listing.recipes.items()): + if (other_kind, other_name) == (kind, name): + continue + if ref in restorer.recipe_references(kind=other_kind, recipe=other.recipe): + users.append(f"saved {_singular(other_kind)} '{other_name}'") + return users + + try: + return await asyncio.to_thread(scan) + except DocumentStorageUnavailableError as error: + logger.error("Saved entries couldn't be read to check what uses '%s' (%s).", name, error.reason) + raise SavedEntryStorageError("Saved entries can't be read right now.") from error + + +def _holders(*, kind: RegistryRecipeKind, entry: RegistryEntry[Any]) -> list[str]: + """ + List the registered entries that hold this one, whatever their origin. + + An entry holds another when that one appears in its configuration, such as a converter's target or a + technique's adversarial target. An entry with the same configuration counts too, since the two can't be told + apart. + + Returns: + list[str]: Each holder described as, for example, "temporary converter 'tone'". + """ + if kind is RegistryRecipeKind.TECHNIQUES: + return [] + held_hash = entry.instance.get_identifier().hash + holders = [] + for other_kind, registry in REGISTRIES_BY_KIND.items(): + # Another user's private entry holds it too, but its name isn't shown. + for other in registry.get_registry_singleton().instances.get_all_instances_of_every_owner(): + if (other_kind, other.name) == (kind, entry.name): + continue + if held_hash in _held_hashes(other.instance): + if is_visible_to_caller(other): + origin = _ORIGIN_WORDS[registry_entry_origin(other.metadata)] + holders.append(f"{origin} {_singular(other_kind)} '{other.name}'") + else: + holders.append(f"another user's private {_singular(other_kind)}") + return holders + + +def _refuse_held(*, kind: RegistryRecipeKind, entry: RegistryEntry[Any]) -> None: + """ + Refuse to remove an entry that a registered entry holds. + + Raises: + SavedEntryInUseError: If a registered entry holds it. + """ + holders = _holders(kind=kind, entry=entry) + if holders: + raise SavedEntryInUseError(_in_use_message(singular=_singular(kind), name=entry.name, users=holders)) + + +def _held_hashes(instance: object) -> set[str]: + """ + Collect the identifier hashes of the components a registered entry holds. + + Returns: + set[str]: The hashes of its children for a target, converter, or scorer, and of the components in its + settings for a technique. + """ + # A technique's identifier doesn't list the components it holds, so its settings are walked instead. + get_settings = getattr(instance, "get_effective_settings", None) + if callable(get_settings): + return _hashes_in(get_settings(), depth=0) + if isinstance(instance, Identifiable): + return _child_hashes(instance.get_identifier()) + return set() + + +def _hashes_in(value: object, *, depth: int) -> set[str]: + """ + Collect the identifier hashes of the components in a technique's settings. + + Returns: + set[str]: The hashes of each component found and of its children. + """ + if isinstance(value, Identifiable): + identifier = value.get_identifier() + return {identifier.hash, *_child_hashes(identifier)} + if depth >= _MAX_SETTINGS_DEPTH: + return set() + if isinstance(value, Mapping): + items: list[object] = list(value.values()) + elif isinstance(value, (list, tuple, set, frozenset)): + items = list(value) + elif dataclasses.is_dataclass(value) and not isinstance(value, type): + items = [getattr(value, field.name) for field in dataclasses.fields(value)] + else: + return set() + hashes: set[str] = set() + for item in items: + hashes |= _hashes_in(item, depth=depth + 1) + return hashes + + +def _child_hashes(identifier: ComponentIdentifier) -> set[str]: + """ + Collect the hashes of every component below an identifier. + + Returns: + set[str]: The descendants' hashes. + """ + hashes: set[str] = set() + for child in identifier.children.values(): + for item in child if isinstance(child, list) else [child]: + hashes.add(item.hash) + hashes |= _child_hashes(item) + return hashes + + +def _put_back(*, kind: RegistryRecipeKind, entry: RegistryEntry[Any] | None) -> None: + """Register an entry again after its file couldn't be deleted.""" + if entry is not None: + REGISTRIES_BY_KIND[kind].get_registry_singleton().instances.register( + entry.instance, name=entry.name, tags=entry.tags, metadata=entry.metadata + ) + + +def _registered_anywhere(instance: object) -> bool: + """ + Return whether an object is still registered under some name, so its resources must stay open. + + Returns: + bool: Whether any registry holds the same object. + """ + return any( + other.instance is instance + for registry in REGISTRIES_BY_KIND.values() + for other in registry.get_registry_singleton().instances.get_all_instances_of_every_owner() + ) + + +def _singular(kind: RegistryRecipeKind) -> str: + return kind.value.removesuffix("s") + + +def _changed_message(*, singular: str, name: str) -> str: + return f"Saved {singular} '{name}' changed since it was read. Look at it again before deleting it." + + +def _in_use_message(*, singular: str, name: str, users: list[str]) -> str: + them = "it" if len(users) == 1 else "them" + message = f"Saved {singular} '{name}' is used by {', '.join(users)}. Delete or change {them} first." + if any(user.startswith("temporary ") for user in users): + message += " A temporary entry is gone after the backend restarts or is reinitialized." + return message diff --git a/pyrit/backend/services/scorer_service.py b/pyrit/backend/services/scorer_service.py index db034736fb..0b74539a9b 100644 --- a/pyrit/backend/services/scorer_service.py +++ b/pyrit/backend/services/scorer_service.py @@ -15,11 +15,26 @@ ScorerTypeResponse, ) from pyrit.backend.models.scorers import UnregisteredScorer +from pyrit.backend.services.saved_entries import save_then_register_locked_async from pyrit.models import ScorerEvaluationIdentifier, ScorerIdentifier, project_behavioral_identity -from pyrit.models.catalog import ScorerInstance +from pyrit.models.catalog import ( + ComponentRecipe, + RegistryEntryOrigin, + RegistryRecipeKind, + SavedEntryOwner, + ScorerInstance, +) from pyrit.models.component_spec import RegisteredComponentReference from pyrit.output.scorer.json import format_scorer_type, scorer_metrics_to_dict -from pyrit.registry import ScorerRegistry +from pyrit.registry import ( + SavedEntryConflictError, + SavedEntryReplacement, + ScorerRegistry, + creator_metadata, + prepare_saved_params_async, + record_private_references, +) +from pyrit.registry.instance_registry import RegistryNameTakenError, registry_entry_origin from pyrit.score import Scorer, TrueFalseScorer @@ -30,7 +45,7 @@ def __init__(self) -> None: """Initialize the service with the scorer registry singleton.""" self._registry = ScorerRegistry.get_registry_singleton() - def _build_instance(self, *, name: str, scorer: Any) -> ScorerInstance: + def _build_instance(self, *, name: str, scorer: Any, origin: RegistryEntryOrigin | None) -> ScorerInstance: from pyrit.backend.services.chat_scoring_service import ChatScoringService metadata = self._registry.get_registered_class_metadata(scorer.__class__.__name__) @@ -50,6 +65,7 @@ def _build_instance(self, *, name: str, scorer: Any) -> ScorerInstance: metrics=scorer_metrics_to_dict(scorer.get_scorer_metrics()), description=metadata.class_description or None if metadata else None, chat_scoring_disabled_reason=ChatScoringService.disabled_reason(scorer), + origin=origin, ) def resolve_registered_scorer(self, reference: RegisteredComponentReference) -> Scorer: @@ -143,7 +159,12 @@ def list_instances() -> ScorerListResponse: page = entries[start : start + limit] has_more = len(entries) > start + limit return ScorerListResponse( - items=[self._build_instance(name=entry.name, scorer=entry.instance) for entry in page], + items=[ + self._build_instance( + name=entry.name, scorer=entry.instance, origin=registry_entry_origin(entry.metadata) + ) + for entry in page + ], pagination=PaginationInfo( limit=limit, has_more=has_more, @@ -163,17 +184,35 @@ async def get_scorer_async(self, *, scorer_registry_name: str) -> ScorerInstance """ def get_instance() -> ScorerInstance | None: - scorer = self._registry.instances.get(scorer_registry_name) - return self._build_instance(name=scorer_registry_name, scorer=scorer) if scorer is not None else None + entry = self._registry.instances.get_entry(scorer_registry_name) + if entry is None: + return None + return self._build_instance( + name=scorer_registry_name, scorer=entry.instance, origin=registry_entry_origin(entry.metadata) + ) return await asyncio.to_thread(get_instance) - async def create_scorer_async(self, *, request: CreateScorerRequest) -> ScorerInstance | UnregisteredScorer: + async def create_scorer_async( + self, + *, + request: CreateScorerRequest, + owner: SavedEntryOwner | None = None, + recipes_source: str | None = None, + replacing: SavedEntryReplacement | None = None, + ) -> ScorerInstance | UnregisteredScorer: """ Build a scorer through the shared registry resolver, with optional registration. A parameter that names a file on the server is rejected before the scorer is - built, so the server never reads a file a caller chose. + built, so the server never reads a file a caller chose. With ``persist``, the + scorer is saved so it is restored at every start; otherwise it is Temporary. + + Args: + request: The create scorer request with type, params, and name. + owner: The signed-in user, recorded on a saved scorer, or None when sign-in is off. + recipes_source: Where saved entries are stored, or None for the default folder. + replacing: The saved scorer an edit rebuilds, whose recipe is overwritten instead of created, or None. Returns: ScorerInstance | UnregisteredScorer: A named instance, or an unregistered @@ -182,7 +221,14 @@ async def create_scorer_async(self, *, request: CreateScorerRequest) -> ScorerIn Raises: ValueError: If the scorer type is unknown, a parameter names a file on the server, or the registry or scorer rejects the parameters. + NotSaveableError: If a scorer to save would hold a credential, or names a Temporary entry. + SavedEntryConflictError: If a scorer to save has the name of a registered or saved scorer. + SavedEntryStorageError: If a scorer to save can't be written to storage. """ + if request.persist and request.name is not None: + return await self._save_scorer_async( + name=request.name, request=request, owner=owner, recipes_source=recipes_source, replacing=replacing + ) def create() -> ScorerInstance | UnregisteredScorer: if request.type not in self._registry: @@ -203,10 +249,72 @@ def create() -> ScorerInstance | UnregisteredScorer: external_input=True, private=request.private, ) - return self._build_instance(name=request.name, scorer=scorer) + return self._build_instance(name=request.name, scorer=scorer, origin=RegistryEntryOrigin.TEMPORARY) return await asyncio.to_thread(create) + async def _save_scorer_async( + self, + *, + name: str, + request: CreateScorerRequest, + owner: SavedEntryOwner | None, + recipes_source: str | None, + replacing: SavedEntryReplacement | None = None, + ) -> ScorerInstance: + """ + Build the requested scorer, save its recipe, then register it as a saved entry. + + The recipe names the class by the registry name the request used, which restore looks up. + + Returns: + ScorerInstance: The saved scorer. + + Raises: + ValueError: If the scorer type is unknown, or the registry or scorer rejects the parameters. + NotSaveableError: If the scorer would hold a credential, or names a Temporary entry. + SavedEntryConflictError: If a saved or registered scorer already has the name. + SavedEntryStorageError: If the recipe can't be written, or can't be deleted after registering failed. + """ + + def find_class() -> type: + if request.type not in self._registry: + raise ValueError(f"Scorer type '{request.type}' not found") + return self._registry.get_class(request.type) + + # Finding the class can run the registry's first, slow class discovery, so it stays off the event loop. + scorer_cls = await asyncio.to_thread(find_class) + params = await prepare_saved_params_async( + registry=self._registry, type_name=request.type, cls=scorer_cls, params=request.params + ) + + def build() -> tuple[Any, ScorerInstance, dict[str, Any]]: + try: + self._registry.instances.validate_name_available(name) + except RegistryNameTakenError as error: + raise SavedEntryConflictError(str(error)) from error + with record_private_references() as private_references: + scorer = self._registry.create_instance_from_external_input(request.type, params=params) + creator = creator_metadata( + name=name, requested_private=request.private, private_references=private_references + ) + return scorer, self._build_instance(name=name, scorer=scorer, origin=RegistryEntryOrigin.SAVED), creator + + scorer, instance, creator = await asyncio.to_thread(build) + await save_then_register_locked_async( + kind=RegistryRecipeKind.SCORERS, + name=name, + recipe=ComponentRecipe( + class_module=scorer_cls.__module__, class_name=request.type, params=params, owner=owner + ), + source=recipes_source, + register=lambda metadata: self._registry.instances.register( + scorer, name=name, metadata={**creator, **metadata} + ), + replacing=replacing, + ) + return instance + @lru_cache(maxsize=1) def get_scorer_service() -> ScorerService: diff --git a/pyrit/backend/services/target_service.py b/pyrit/backend/services/target_service.py index 2d53e879c2..636d8482b5 100644 --- a/pyrit/backend/services/target_service.py +++ b/pyrit/backend/services/target_service.py @@ -41,6 +41,7 @@ UnregisteredTarget, ) from pyrit.backend.services.component_lifecycle import construct_component_async, release_component_async +from pyrit.backend.services.saved_entries import save_then_register_locked_async from pyrit.common import AUTH_MODES, REQUIRED_VALUE, AuthMode, default_values from pyrit.models import Parameter, PromptDataType, TargetCapabilities, TargetIdentifier from pyrit.models.catalog import ( @@ -66,6 +67,7 @@ NotSaveableError, RegistryEntry, SavedEntryConflictError, + SavedEntryReplacement, TargetRegistry, allows_credential_updates, creator_metadata, @@ -74,7 +76,6 @@ is_private_entry, prepare_saved_params_async, record_private_references, - save_then_register_async, ) from pyrit.registry.instance_registry import ( PRIVATE_METADATA_KEY, @@ -567,6 +568,7 @@ async def create_target_async( is_admin: bool = False, owner: SavedEntryOwner | None = None, recipes_source: str | None = None, + replacing: SavedEntryReplacement | None = None, ) -> TargetInstance | UnregisteredTarget: """ Create a new target instance from API request. @@ -602,6 +604,7 @@ async def create_target_async( authenticates with this server's stored credentials. owner: The signed-in user, recorded on a saved target, or None when sign-in is off. recipes_source: Where saved entries are stored, or None for the default folder. + replacing: The saved target an edit rebuilds, whose recipe is overwritten instead of created, or None. Returns: TargetInstance with the new target's details. @@ -686,7 +689,7 @@ async def create_target_async( private_references=private_references, ) if request.persist: - return await self._save_and_register_async( + target = await self._save_and_register_async( name=target_registry_name, type_name=request.type, target_cls=target_cls, @@ -696,20 +699,25 @@ async def create_target_async( owner=owner, recipes_source=recipes_source, creator=creator, + replacing=replacing, ) - allowed = self._credential_updates_allowed( - requested=request.allow_credential_updates, - target=target_obj, - private=bool(creator.get(PRIVATE_METADATA_KEY)), - ) - metadata = {**creator, **credential_update_metadata(allowed=allowed)} - entry = RegistryEntry(name=target_registry_name, instance=target_obj, metadata=metadata) - target = self._build_instance_from_entry(entry, origin=RegistryEntryOrigin.TEMPORARY) - self._registry.instances.register(target_obj, name=target_registry_name, metadata=entry.metadata) - return target + else: + allowed = self._credential_updates_allowed( + requested=request.allow_credential_updates, + target=target_obj, + private=bool(creator.get(PRIVATE_METADATA_KEY)), + ) + metadata = {**creator, **credential_update_metadata(allowed=allowed)} + entry = RegistryEntry(name=target_registry_name, instance=target_obj, metadata=metadata) + target = self._build_instance_from_entry(entry, origin=RegistryEntryOrigin.TEMPORARY) + self._registry.instances.register(target_obj, name=target_registry_name, metadata=entry.metadata) except Exception: await release_component_async(target_obj) raise + if replacing is not None and not replacing.running: + # An edit of an entry that isn't running only rewrote its file, so nothing holds what was built to check it. + await release_component_async(target_obj) + return target async def check_saveability_async( self, @@ -960,6 +968,7 @@ async def _save_and_register_async( owner: SavedEntryOwner | None, recipes_source: str | None, creator: Mapping[str, Any], + replacing: SavedEntryReplacement | None = None, ) -> TargetInstance: """ Save the target's recipe through the registry library, then return the saved target. @@ -979,21 +988,21 @@ async def _save_and_register_async( RegistryEntry(name=name, instance=target_obj, metadata=dict(creator)), origin=RegistryEntryOrigin.SAVED ) auth_parameters = target_cls.get_auth_mode_parameters(auth_mode=auth_mode) - recipe = ComponentRecipe( - class_module=target_cls.__module__, - class_name=type_name, - auth_mode=auth_mode, - params={key: value for key, value in params.items() if key not in auth_parameters}, - owner=owner, - ) - await save_then_register_async( + await save_then_register_locked_async( kind=RegistryRecipeKind.TARGETS, name=name, - recipe=recipe, + recipe=ComponentRecipe( + class_module=target_cls.__module__, + class_name=type_name, + auth_mode=auth_mode, + params={key: value for key, value in params.items() if key not in auth_parameters}, + owner=owner, + ), register=lambda metadata: self._registry.instances.register( target_obj, name=name, metadata={**creator, **metadata} ), source=recipes_source, + replacing=replacing, ) return target diff --git a/pyrit/backend/services/technique_service.py b/pyrit/backend/services/technique_service.py index a238397d36..0c6f4d3904 100644 --- a/pyrit/backend/services/technique_service.py +++ b/pyrit/backend/services/technique_service.py @@ -15,7 +15,31 @@ TechniqueTypeEntry, TechniqueTypeResponse, ) -from pyrit.registry import AttackRegistry, AttackTechniqueRegistry, creator_metadata, record_private_references +from pyrit.backend.services.saved_entries import save_then_register_locked_async +from pyrit.models import ComponentType +from pyrit.models.catalog import ( + RegistryEntryOrigin, + RegistryRecipeKind, + RestoreFailureReason, + SavedEntryOwner, + TechniqueRecipe, +) +from pyrit.registry import ( + AttackRegistry, + AttackTechniqueRegistry, + NotSaveableError, + SavedEntryConflictError, + SavedEntryReplacement, + creator_metadata, + get_class_saveability, + record_private_references, + refuse_temporary_entries, + refuse_temporary_references, +) +from pyrit.registry.components.attack_technique_registry import TechniqueSelectorConflictError +from pyrit.registry.instance_registry import registry_entry_origin +from pyrit.registry.registry_recipe_rules import SavedEntryRefusedError, check_saved_entry_params +from pyrit.scenario.core import AttackTechniqueFactory class TechniqueService: @@ -40,7 +64,12 @@ def _list(self, *, limit: int, cursor: str | None) -> TechniqueListResponse: page = entries[start : start + limit] has_more = len(entries) > start + limit return TechniqueListResponse( - items=[technique_to_instance(name=entry.name, factory=entry.instance) for entry in page], + items=[ + technique_to_instance( + name=entry.name, factory=entry.instance, origin=registry_entry_origin(entry.metadata) + ) + for entry in page + ], pagination=PaginationInfo( limit=limit, has_more=has_more, @@ -56,27 +85,54 @@ async def get_async(self, name: str) -> TechniqueInstance | None: Returns: TechniqueInstance | None: The factory settings, if registered. """ - factory = self._registry.instances.get(name) - if factory is None: + entry = self._registry.instances.get_entry(name) + if entry is None: return None - return await asyncio.to_thread(technique_to_instance, name=name, factory=factory) + return await asyncio.to_thread( + technique_to_instance, name=name, factory=entry.instance, origin=registry_entry_origin(entry.metadata) + ) - async def create_async(self, request: CreateTechniqueRequest) -> TechniqueInstance: + async def create_async( + self, + *, + request: CreateTechniqueRequest, + owner: SavedEntryOwner | None = None, + recipes_source: str | None = None, + replacing: SavedEntryReplacement | None = None, + ) -> TechniqueInstance: """ Validate, project, and register without sending prompts or creating attacks. + With ``persist``, the technique's recipe is saved before it's registered, so it comes back after a restart. + + Args: + request (CreateTechniqueRequest): The technique to create. + owner (SavedEntryOwner | None): The signed-in user, recorded on a saved technique, or None when sign-in + is off. Defaults to None. + recipes_source (str | None): Where saved entries are stored, or None for the default folder. Defaults to + None. + replacing (SavedEntryReplacement | None): The saved technique an edit rebuilds, whose recipe is + overwritten instead of created, or None. Defaults to None. + Returns: TechniqueInstance: Safe settings for the admitted factory. + + Raises: + NotSaveableError: If a technique to save has an attack type that a scan's launch script added, or uses a + Temporary converter or target. + SavedEntryConflictError: If a technique to save has the name or a tag of a registered technique. + SavedEntryStorageError: If the recipe can't be written, or can't be deleted after registering failed. """ + if request.persist: + return await self._save_async( + request=request, owner=owner, recipes_source=recipes_source, replacing=replacing + ) return await asyncio.to_thread(self._create, request) def _create(self, request: CreateTechniqueRequest) -> TechniqueInstance: - args = request.model_dump(exclude_unset=True, exclude={"name", "type", "tags", "private"}) with record_private_references() as private_references: - factory = self._registry.create_factory( - name=request.name, attack_type=request.type, technique_tags=request.tags, strict_json=True, **args - ) - result = technique_to_instance(name=request.name, factory=factory) + factory = self._build(request) + result = technique_to_instance(name=request.name, factory=factory, origin=RegistryEntryOrigin.TEMPORARY) # A technique built on the caller's private targets or converters is private to the caller too. metadata = creator_metadata( name=request.name, requested_private=request.private, private_references=private_references @@ -84,6 +140,95 @@ def _create(self, request: CreateTechniqueRequest) -> TechniqueInstance: self._registry.instances.register_runtime(factory, metadata=metadata) return result + def _build(self, request: CreateTechniqueRequest) -> AttackTechniqueFactory: + args = request.model_dump(exclude_unset=True, exclude={"name", "type", "tags", "persist", "private"}) + return self._registry.create_factory( + name=request.name, attack_type=request.type, technique_tags=request.tags, strict_json=True, **args + ) + + async def _save_async( + self, + *, + request: CreateTechniqueRequest, + owner: SavedEntryOwner | None, + recipes_source: str | None, + replacing: SavedEntryReplacement | None = None, + ) -> TechniqueInstance: + """ + Build the requested technique, save its recipe, then register it as a saved entry. + + The recipe is the request without its name, which restore builds with the same call. + + Returns: + TechniqueInstance: The saved technique. + + Raises: + NotSaveableError: If the technique's attack type was added by a scan's launch script or can't be saved, + an attack parameter holds a credential, or the technique uses a Temporary converter or target. + ValueError: If an address an attack parameter gives isn't a full http(s) or ws(s) address. + SavedEntryConflictError: If the name or a tag conflicts with a registered technique. + SavedEntryStorageError: If the recipe can't be written, or can't be deleted after registering failed. + """ + refuse_temporary_entries( + component_type=ComponentType.CONVERTER, + names=[*(request.request_converters or []), *(request.response_converters or [])], + ) + refuse_temporary_entries(component_type=ComponentType.TARGET, names=[request.adversarial_chat]) + with record_private_references() as private_references: + factory = await asyncio.to_thread(self._build, request) + _, class_reason = await asyncio.to_thread( + get_class_saveability, registry=AttackRegistry.get_registry_singleton(), type_name=request.type + ) + if class_reason is not None: + raise NotSaveableError(class_reason) + await asyncio.to_thread(self._refuse_attack_params_restore_would_refuse, request) + try: + await asyncio.to_thread(self._registry.instances.check_runtime_available, factory) + except TechniqueSelectorConflictError as error: + raise SavedEntryConflictError(str(error)) from error + result = await asyncio.to_thread( + technique_to_instance, name=request.name, factory=factory, origin=RegistryEntryOrigin.SAVED + ) + creator = creator_metadata( + name=request.name, requested_private=request.private, private_references=private_references + ) + recipe_fields = request.model_dump(exclude_unset=True, exclude={"name", "persist", "private"}) + await save_then_register_locked_async( + kind=RegistryRecipeKind.TECHNIQUES, + name=request.name, + recipe=TechniqueRecipe(**recipe_fields, owner=owner), + register=lambda metadata: self._registry.instances.register_runtime( + factory, metadata={**creator, **metadata} + ), + source=recipes_source, + replacing=replacing, + ) + return result + + @staticmethod + def _refuse_attack_params_restore_would_refuse(request: CreateTechniqueRequest) -> None: + """ + Check the attack type and its parameters the way restore does, so a saved technique comes back. + + Raises: + NotSaveableError: If the attack type can't be saved, or a parameter holds a credential or names a + Temporary entry. + ValueError: If an address a parameter gives isn't a full http(s) or ws(s) address. + """ + attack_registry = AttackRegistry.get_registry_singleton() + attack_class = attack_registry.get_class(request.type) + metadata = attack_registry.get_registered_class_metadata(request.type) or attack_registry.get_class_metadata( + attack_class + ) + try: + check_saved_entry_params(cls=attack_class, parameters=metadata.parameters, params=request.params) + except SavedEntryRefusedError as error: + # The address needs fixing; creating the technique without saving it wouldn't make it usable. + if error.reason is RestoreFailureReason.INVALID_RECIPE: + raise ValueError(str(error)) from error + raise NotSaveableError(str(error)) from error + refuse_temporary_references(parameters=metadata.parameters, params=request.params) + async def types_async(self) -> TechniqueTypeResponse: """ Discover metadata off the event loop. diff --git a/pyrit/models/catalog/registry_recipe.py b/pyrit/models/catalog/registry_recipe.py index 2e197252dd..5deb6c323d 100644 --- a/pyrit/models/catalog/registry_recipe.py +++ b/pyrit/models/catalog/registry_recipe.py @@ -93,6 +93,7 @@ class TechniqueRecipe(_RegistryRecipe): adversarial_system_prompt: str | None = None adversarial_seed_prompt: str | None = None adversarial_prompt_template: str | None = None + owner: SavedEntryOwner | None = Field(None, description="Who saved the entry; None when sign-in is off") @field_validator("tags") @classmethod diff --git a/pyrit/models/catalog/scorer.py b/pyrit/models/catalog/scorer.py index 57cfc69340..0509df9599 100644 --- a/pyrit/models/catalog/scorer.py +++ b/pyrit/models/catalog/scorer.py @@ -5,6 +5,7 @@ from pydantic import BaseModel, Field +from pyrit.models.catalog.registry_recipe import RegistryEntryOrigin from pyrit.models.identifiers.component_identifier import ComponentIdentifier from pyrit.models.identifiers.scorer_identifier import ScorerIdentifier @@ -25,3 +26,10 @@ class ScorerInstance(BaseModel): chat_scoring_disabled_reason: str | None = Field( None, description="Why this instance cannot be selected as a chat objective scorer" ) + origin: RegistryEntryOrigin | None = Field( + None, + description=( + "Where the scorer comes from: 'saved' (restored at every start), 'configuration' (the server's " + "startup scripts), or 'temporary' (gone after a restart or reinitialization)" + ), + ) diff --git a/pyrit/registry/__init__.py b/pyrit/registry/__init__.py index fd094231f9..048b8ef7c8 100644 --- a/pyrit/registry/__init__.py +++ b/pyrit/registry/__init__.py @@ -52,9 +52,12 @@ from pyrit.registry.registry_recipe_save import ( NotSaveableError, SavedEntryConflictError, + SavedEntryReplacement, SavedEntryStorageError, get_class_saveability, prepare_saved_params_async, + refuse_temporary_entries, + refuse_temporary_references, save_then_register_async, ) from pyrit.registry.scenario_preset_storage import ScenarioPresetConflictError, ScenarioPresetStorage @@ -84,9 +87,12 @@ "RegistryMetadata": "pyrit.registry.registry_metadata", "NotSaveableError": "pyrit.registry.registry_recipe_save", "SavedEntryConflictError": "pyrit.registry.registry_recipe_save", + "SavedEntryReplacement": "pyrit.registry.registry_recipe_save", "SavedEntryStorageError": "pyrit.registry.registry_recipe_save", "get_class_saveability": "pyrit.registry.registry_recipe_save", "prepare_saved_params_async": "pyrit.registry.registry_recipe_save", + "refuse_temporary_entries": "pyrit.registry.registry_recipe_save", + "refuse_temporary_references": "pyrit.registry.registry_recipe_save", "save_then_register_async": "pyrit.registry.registry_recipe_save", "SupportsInstances": "pyrit.registry.instance_registry", "discover_in_directory": "pyrit.registry.discovery", diff --git a/pyrit/registry/components/attack_technique_registry.py b/pyrit/registry/components/attack_technique_registry.py index c630d27641..7e7b038665 100644 --- a/pyrit/registry/components/attack_technique_registry.py +++ b/pyrit/registry/components/attack_technique_registry.py @@ -47,6 +47,7 @@ from pyrit.models import Parameter from pyrit.models.technique_edit import TechniqueChanges from pyrit.prompt_normalizer import ConverterConfiguration + from pyrit.registry.instance_registry import RegistryEntry from pyrit.scenario import ( AttackTechniqueFactory, ScenarioTechnique, @@ -66,6 +67,13 @@ def __call__(self) -> type[ScenarioTechnique]: ... logger = logging.getLogger(__name__) +def _record_saved_techniques_with_tag(*, entries: list[RegistryEntry[AttackTechniqueFactory]], folded_tag: str) -> None: + """Record each saved technique with a tag as a refused use, as a clash over the tag can leave it standing in.""" + for entry in entries: + if folded_tag in {tag.casefold() for tag in entry.instance.technique_tags}: + _record_saved_entry_refusal(entry) + + def _attack_technique_factory_type() -> type[AttackTechniqueFactory]: """ Return the ``AttackTechniqueFactory`` class, importing it lazily. @@ -138,7 +146,11 @@ class AttackTechniqueMetadata(RegistryMetadata): class TechniqueSelectorConflictError(RegistryNameTakenError): - """A technique's name or tag conflicts with the name or a tag of a registered technique.""" + """ + A technique's name or tag conflicts with the name or a tag of a registered technique. + + Names and tags both select techniques, so either one counts as taken. + """ class TechniqueAdmissionError(ValueError): @@ -148,6 +160,24 @@ class TechniqueAdmissionError(ValueError): class TechniqueInstanceRegistry(DefaultInstanceRegistry["AttackTechniqueFactory"]): """Factory storage with an atomic runtime-admission path.""" + def check_runtime_available(self, factory: AttackTechniqueFactory) -> None: + """ + Check that a technique could be registered now, without registering it. + + Args: + factory (AttackTechniqueFactory): The technique to check. + + Raises: + TechniqueSelectorConflictError: If the name or a tag conflicts with another technique's name or tag. + TechniqueAdmissionError: If a tag repeats the technique's own name, a selector can't become a scenario + member, or the factory doesn't fit the scenarios it would join. + """ + from pyrit.registry.components.scenario_registry import ScenarioRegistry + + ScenarioRegistry.get_registry_singleton().get_class_names() + with self._lock: + self._check_available(factory) + def register_runtime(self, factory: AttackTechniqueFactory, *, metadata: dict[str, Any] | None = None) -> None: """ Check selector collisions while holding the same lock as registration. @@ -166,53 +196,69 @@ def register_runtime(self, factory: AttackTechniqueFactory, *, metadata: dict[st # Discover builders before taking the instance lock; discovery has its own catalog lock. ScenarioRegistry.get_registry_singleton().get_class_names() with self._lock: - entries = self.get_all_instances() - # Names are global, so a technique can't take a name, or a tag spelled like one, that another caller's - # private technique uses. A tag groups techniques, so the exact same tag can be used by every caller. - every_entry = self.get_all_instances_of_every_owner() - names = {entry.name.casefold(): entry.name for entry in every_entry} - tags = {tag.casefold(): tag for entry in every_entry for tag in entry.instance.technique_tags} - visible_names = {entry.name.casefold() for entry in entries} - visible_tags = {tag.casefold() for entry in entries for tag in entry.instance.technique_tags} - hidden_names = names.keys() - visible_names - hidden_tags = {folded: tag for folded, tag in tags.items() if folded not in visible_tags} - # A clash with a technique the caller can't see says only that the selector is taken. - folded_name = factory.name.casefold() - if folded_name in hidden_names or folded_name in hidden_tags: - raise TechniqueSelectorConflictError(f"The technique name or tag '{factory.name}' is taken.") - for tag in factory.technique_tags: - folded = tag.casefold() - if folded in hidden_names or hidden_tags.get(folded, tag) != tag: - raise TechniqueSelectorConflictError(f"The technique name or tag '{tag}' is taken.") - if folded_name in names: - # Code that catches this error would leave a saved technique standing in, so the clash is recorded. - _record_saved_entry_refusal(self._registry_items.get(names[folded_name])) - raise TechniqueSelectorConflictError( - f"Technique '{factory.name}' already exists (names are case-insensitive)" - ) - if folded_name in tags: - raise TechniqueSelectorConflictError(f"Technique name '{factory.name}' conflicts with an aggregate tag") - for tag in factory.technique_tags: - folded = tag.casefold() - if folded == folded_name: - raise TechniqueAdmissionError(f"Tag '{tag}' repeats the technique's name") - if folded in names: - raise TechniqueSelectorConflictError(f"Tag '{tag}' conflicts with a technique name") - if folded in tags and tags[folded] != tag: - raise TechniqueSelectorConflictError(f"Tag '{tag}' conflicts with tag '{tags[folded]}'") - try: - _validate_generated_member_collisions( - class_name="ScenarioTechnique", - factories=[factory], - aggregate_tags=set(factory.technique_tags) - {"all", "default"}, - ) - AttackTechniqueRegistry.get_registry_singleton().validate_scenario_pools( - {**{entry.name: entry.instance for entry in entries}, factory.name: factory} - ) - except ValueError as error: - raise TechniqueAdmissionError(str(error)) from error + self._check_available(factory) self.register(factory, name=factory.name, tags=factory.technique_tags, metadata=metadata) + def _check_available(self, factory: AttackTechniqueFactory) -> None: + """ + Check a technique against the registered ones; the caller holds the instance lock. + + Raises: + TechniqueSelectorConflictError: If the name or a tag conflicts with another technique's name or tag. + TechniqueAdmissionError: If a tag repeats the technique's own name, a selector can't become a scenario + member, or the factory doesn't fit the scenarios it would join. + """ + entries = self.get_all_instances() + # Names are global, so a technique can't take a name, or a tag spelled like one, that another caller's + # private technique uses. A tag groups techniques, so the exact same tag can be used by every caller. + every_entry = self.get_all_instances_of_every_owner() + names = {entry.name.casefold(): entry.name for entry in every_entry} + tags = {tag.casefold(): tag for entry in every_entry for tag in entry.instance.technique_tags} + visible_names = {entry.name.casefold() for entry in entries} + visible_tags = {tag.casefold() for entry in entries for tag in entry.instance.technique_tags} + hidden_names = names.keys() - visible_names + hidden_tags = {folded: tag for folded, tag in tags.items() if folded not in visible_tags} + # A clash with a technique the caller can't see says only that the selector is taken. + folded_name = factory.name.casefold() + if folded_name in hidden_names or folded_name in hidden_tags: + raise TechniqueSelectorConflictError(f"The technique name or tag '{factory.name}' is taken.") + for tag in factory.technique_tags: + folded = tag.casefold() + if folded in hidden_names or hidden_tags.get(folded, tag) != tag: + raise TechniqueSelectorConflictError(f"The technique name or tag '{tag}' is taken.") + if folded_name in names: + # Code that catches this error would leave a saved technique standing in, so the clash is recorded. + _record_saved_entry_refusal(self._registry_items.get(names[folded_name])) + raise TechniqueSelectorConflictError( + f"Technique '{factory.name}' already exists (names are case-insensitive)" + ) + if folded_name in tags: + # Code that catches this error would leave the saved techniques with that tag standing in, so they're + # recorded too. + _record_saved_techniques_with_tag(entries=entries, folded_tag=folded_name) + raise TechniqueSelectorConflictError(f"Technique name '{factory.name}' conflicts with an aggregate tag") + for tag in factory.technique_tags: + folded = tag.casefold() + if folded == folded_name: + raise TechniqueAdmissionError(f"Tag '{tag}' repeats the technique's name") + if folded in names: + _record_saved_entry_refusal(self._registry_items.get(names[folded])) + raise TechniqueSelectorConflictError(f"Tag '{tag}' conflicts with a technique name") + if folded in tags and tags[folded] != tag: + _record_saved_techniques_with_tag(entries=entries, folded_tag=folded) + raise TechniqueSelectorConflictError(f"Tag '{tag}' conflicts with tag '{tags[folded]}'") + try: + _validate_generated_member_collisions( + class_name="ScenarioTechnique", + factories=[factory], + aggregate_tags=set(factory.technique_tags) - {"all", "default"}, + ) + AttackTechniqueRegistry.get_registry_singleton().validate_scenario_pools( + {**{entry.name: entry.instance for entry in entries}, factory.name: factory} + ) + except ValueError as error: + raise TechniqueAdmissionError(str(error)) from error + class AttackTechniqueRegistry(Registry["AttackTechniqueFactory", AttackTechniqueMetadata]): """ diff --git a/pyrit/registry/components/scorer_registry.py b/pyrit/registry/components/scorer_registry.py index 150fae8d1c..dfd40f9e70 100644 --- a/pyrit/registry/components/scorer_registry.py +++ b/pyrit/registry/components/scorer_registry.py @@ -80,7 +80,7 @@ def __init__(self, *, lazy_discovery: bool = True) -> None: lazy_discovery (bool): If True, class discovery is deferred until first access. If False, discovery runs immediately. """ - super().__init__(lazy_discovery=lazy_discovery) + super().__init__(lazy_discovery=lazy_discovery, reserved_instance_names={"types"}) def _base_type(self) -> type[Scorer]: """Return the ``Scorer`` base class, imported lazily.""" diff --git a/pyrit/registry/registry_recipe_restore.py b/pyrit/registry/registry_recipe_restore.py index 03acbc0189..3097bf34a4 100644 --- a/pyrit/registry/registry_recipe_restore.py +++ b/pyrit/registry/registry_recipe_restore.py @@ -79,8 +79,7 @@ class RegistryRecipeRestorer: this server or send requests where this server's settings say. Entries that can't come back are reported with the reason instead of being skipped. - Stored files are otherwise trusted the way configuration is. Converters and scorers don't - declare the credentials they read from server settings yet, so those rules cover targets only. + Stored files are otherwise trusted the way configuration is. """ _KIND_BY_COMPONENT_TYPE: ClassVar[dict[ComponentType, RegistryRecipeKind]] = { @@ -316,7 +315,7 @@ def _component_references(self, *, ref: SavedEntryRef, recipe: ComponentRecipe) raise RecipeRejectedError(reason=RestoreFailureReason.NAME_CLASH, message=str(error)) from error except ValueError as error: # A reserved name, which no entry of this kind can have. raise RecipeRejectedError(reason=RestoreFailureReason.INVALID_RECIPE, message=str(error)) from error - return self._parameter_references(parameters=parameters, params=recipe.params) + return self.recipe_references(kind=ref.kind, recipe=recipe) def _technique_references(self, *, ref: SavedEntryRef, recipe: TechniqueRecipe) -> list[SavedEntryRef]: """ @@ -339,13 +338,46 @@ def _technique_references(self, *, ref: SavedEntryRef, recipe: TechniqueRecipe) except KeyError as error: message = f"'{recipe.type}' is not a registered attack type." raise RecipeRejectedError(reason=RestoreFailureReason.UNKNOWN_CLASS, message=message) from error - converters = [*(recipe.request_converters or []), *(recipe.response_converters or [])] - references = [SavedEntryRef(kind=RegistryRecipeKind.CONVERTERS, name=name) for name in converters] - if recipe.adversarial_chat is not None: - references.append(SavedEntryRef(kind=RegistryRecipeKind.TARGETS, name=recipe.adversarial_chat)) parameters = self._class_parameters(registry=attack_registry, name=recipe.type, cls=attack_class) check_saved_entry_params(cls=attack_class, parameters=parameters, params=recipe.params) - return references + self._parameter_references(parameters=parameters, params=recipe.params) + return self.recipe_references(kind=RegistryRecipeKind.TECHNIQUES, recipe=recipe) + + def recipe_references( + self, *, kind: RegistryRecipeKind, recipe: ComponentRecipe | TechniqueRecipe + ) -> list[SavedEntryRef]: + """ + List the entries a saved recipe names, as restoring it reads them. + + A recipe whose class or attack type isn't registered names nothing, since it can't be restored. + + Args: + kind (RegistryRecipeKind): The kind of entry the recipe saves. + recipe (ComponentRecipe | TechniqueRecipe): The recipe. + + Returns: + list[SavedEntryRef]: The named entries, in the order the recipe names them. + """ + if isinstance(recipe, TechniqueRecipe): + from pyrit.registry.components.attack_registry import AttackRegistry + + converters = [*(recipe.request_converters or []), *(recipe.response_converters or [])] + references = [SavedEntryRef(kind=RegistryRecipeKind.CONVERTERS, name=name) for name in converters] + if recipe.adversarial_chat is not None: + references.append(SavedEntryRef(kind=RegistryRecipeKind.TARGETS, name=recipe.adversarial_chat)) + attack_registry = AttackRegistry.get_registry_singleton() + try: + attack_class = attack_registry.get_class(recipe.type) + except KeyError: + return references + parameters = self._class_parameters(registry=attack_registry, name=recipe.type, cls=attack_class) + return references + self._parameter_references(parameters=parameters, params=recipe.params) + registry = self._get_registry(kind) + try: + cls = registry.get_class(recipe.class_name) + except KeyError: + return [] + parameters = self._class_parameters(registry=registry, name=recipe.class_name, cls=cls) + return self._parameter_references(parameters=parameters, params=recipe.params) @staticmethod def _class_parameters(*, registry: Registry[Any, Any], name: str, cls: type) -> tuple[Parameter, ...]: diff --git a/pyrit/registry/registry_recipe_save.py b/pyrit/registry/registry_recipe_save.py index 372beb8197..aff7820448 100644 --- a/pyrit/registry/registry_recipe_save.py +++ b/pyrit/registry/registry_recipe_save.py @@ -6,21 +6,32 @@ Saving takes three steps: ``prepare_saved_params_async`` turns off the values the entry would take from this server and refuses what a saved entry can't hold, the caller builds the entry from the parameters it returns, and -``save_then_register_async`` writes the entry's recipe and registers the entry as saved. +``save_then_register_async`` writes the entry's recipe and registers the entry as saved. Targets, converters, and +scorers are saved the same way. """ from __future__ import annotations import asyncio +import inspect import logging import traceback +from dataclasses import dataclass from typing import TYPE_CHECKING, Any +from pyrit.common.apply_defaults import resolve_constructor_defaults from pyrit.common.azure_storage import redact_urls from pyrit.models import ComponentType -from pyrit.models.catalog import ComponentRecipe, RegistryEntryOrigin, RegistryRecipeKind, RestoreFailureReason +from pyrit.models.catalog import ( + ComponentRecipe, + RegistryEntryOrigin, + RegistryRecipeKind, + RestoreFailureReason, + TechniqueRecipe, +) from pyrit.registry.file_document_storage import DocumentConflictError, DocumentStorageUnavailableError from pyrit.registry.instance_registry import SAVED_ENTRY_METADATA_KEY, RegistryNameTakenError, registry_entry_origin +from pyrit.registry.registry_recipe_restore import RegistryRecipeRestorer from pyrit.registry.registry_recipe_rules import SavedEntryRefusedError, check_saveable_class, check_saved_entry_params from pyrit.registry.registry_recipe_storage import RegistryRecipeStorage from pyrit.registry.resolution import reject_non_external_params @@ -29,6 +40,7 @@ from collections.abc import Callable, Mapping, Sequence from pyrit.models import Parameter + from pyrit.registry.instance_registry import RegistryEntry from pyrit.registry.registry import InstanceHoldingRegistry, Registry logger = logging.getLogger(__name__) @@ -57,6 +69,25 @@ class SavedEntryStorageError(RuntimeError): """Saved entries can't be written right now.""" +@dataclass(frozen=True) +class SavedEntryReplacement: + """ + A saved entry an edit rebuilds, so its recipe is overwritten instead of created. + + Before the entry is rebuilt, the edit has removed the running entry. + + Attributes: + version (str): The version of the recipe the edit read. + previous (ComponentRecipe | TechniqueRecipe): That recipe, written back if the new entry can't be registered. + running (bool): Whether the entry was running, so the rebuilt one is registered in its place. One that + wasn't, such as an entry that failed to restore, is only saved, and the next apply or start restores it. + """ + + version: str + previous: ComponentRecipe | TechniqueRecipe + running: bool + + def get_class_saveability(*, registry: Registry[Any, Any], type_name: str) -> tuple[tuple[str, ...], str | None]: """ Return the auth modes a saved entry of a registered class can use, or why none can. @@ -107,32 +138,31 @@ async def prepare_saved_params_async( """ Turn off the server values an entry to save would read, then refuse what it still can't hold. - The checks are the ones restore makes, so an entry this accepts is rebuilt at every start. - Args: registry (InstanceHoldingRegistry[Any, Any]): The registry the entry's class is registered in. - type_name (str): The name the class is registered under, which the recipe names. + type_name (str): The name the class is registered under. cls (type): The class the entry is built from. params (Mapping[str, Any]): The entry's constructor parameters. - auth_mode (str | None): A target's auth mode, or None for an entry without one. + auth_mode (str | None): A target's auth mode from its create request, or None for converters and scorers. Returns: dict[str, Any]: The parameters to build and save the entry with. Raises: NotSaveableError: If the entry's class can't be saved or was added by a scan's launch script, or the entry - would hold or use a credential, leaves a setting to this server's environment, or uses a Temporary target. + would hold or use a credential, leaves a setting to this server's environment, or names a Temporary entry. ValueError: If an address the entry would use isn't a full http(s) or ws(s) address, or a parameter is one the API can't set, which restore can't pass either. """ + # Finding the class can run the registry's first, slow class discovery, so it stays off the event loop. + _, class_reason = await asyncio.to_thread(get_class_saveability, registry=registry, type_name=type_name) + if class_reason is not None: + raise NotSaveableError(class_reason) saved_params = dict(params) fallbacks: Mapping[str, str | None] = getattr(cls, "server_fallback_parameters", {}) for name, turned_off in fallbacks.items(): if turned_off is not None and saved_params.get(name) in (None, ""): saved_params[name] = turned_off - _, class_reason = get_class_saveability(registry=registry, type_name=type_name) - if class_reason is not None: - raise NotSaveableError(class_reason) metadata = await asyncio.to_thread(registry.get_registered_class_metadata, type_name) if metadata is None: # Restore falls back to the class itself the same way, so saving never checks less than restoring. @@ -145,9 +175,10 @@ async def prepare_saved_params_async( if error.reason is RestoreFailureReason.INVALID_RECIPE: raise ValueError(str(error)) from error raise NotSaveableError(str(error)) from error + _name_default_references(cls=cls, parameters=parameters, params=saved_params) _refuse_values_restore_cant_pass(cls=cls, parameters=parameters, params=saved_params) _refuse_environment_values(cls=cls, params=saved_params) - _refuse_temporary_references(parameters=parameters, params=saved_params) + refuse_temporary_references(parameters=parameters, params=saved_params) return saved_params @@ -186,58 +217,236 @@ def _refuse_environment_values(*, cls: type, params: Mapping[str, Any]) -> None: ) -def _refuse_temporary_references(*, parameters: Sequence[Parameter], params: Mapping[str, Any]) -> None: +def _name_default_references(*, cls: type, parameters: Sequence[Parameter], params: dict[str, Any]) -> None: + """ + Name the registered entry that a reference left unset takes from the configured defaults. + + A constructor that applies defaults fills an unset reference from them, and those can be set by code that + doesn't run again at startup, so the recipe names the entry instead of relying on the default. As when the + entry is built, a reference sent as null is null, while one left out or cleared starts from the constructor's + own default. + + Raises: + NotSaveableError: If a reference left unset takes a default that isn't a registered entry. + """ + unset = [ + parameter + for parameter in parameters + if parameter.reference is not None and params.get(parameter.name) in (None, "") + ] + if not unset: + return + unset_names = {parameter.name for parameter in unset} + signature = inspect.signature(cls.__init__) + sent_as_null = {name: None for name in unset_names if name in params and params[name] is None} + try: + effective = resolve_constructor_defaults( + class_type=cls, + arguments=sent_as_null, + excluded_parameters=set(signature.parameters) - unset_names, + ) + except ValueError: + # A required reference without a default; building the entry reports it. + return + for parameter in unset: + value = effective.get(parameter.name) + if value is None or parameter.reference is None: + continue + constructor_parameter = signature.parameters.get(parameter.name) + if ( + parameter.name not in sent_as_null + and constructor_parameter is not None + and value is constructor_parameter.default + ): + # The constructor's own default comes back the same way at every start. + continue + component_type = parameter.reference.component_type + names = [ + _registered_name(parameter_name=parameter.name, component_type=component_type, instance=item) + for item in (value if isinstance(value, (list, tuple)) else [value]) + ] + params[parameter.name] = names if isinstance(value, (list, tuple)) else names[0] + + +def _registered_name(*, parameter_name: str, component_type: ComponentType, instance: Any) -> str: """ - Refuse an entry to save that uses a Temporary target, which won't exist after a restart. + Name the registered entry that holds a default reference, preferring a name that comes back at every start. + + Returns: + str: The entry's registry name. Raises: - NotSaveableError: If a target parameter names a Temporary target. + NotSaveableError: If no registered entry holds the instance. """ + registry = _referenced_registry(component_type) + entries: list[RegistryEntry[Any]] = ( + [item for item in registry.instances.get_all_instances() if item.instance is instance] + if registry is not None + else [] + ) + if not entries: + raise NotSaveableError( + f"'{parameter_name}' is left to a default {component_type.value} that isn't registered, so it won't " + "exist after a restart." + ) + entry = next( + (item for item in entries if registry_entry_origin(item.metadata) is not RegistryEntryOrigin.TEMPORARY), + entries[0], + ) + return entry.name + + +def _referenced_registry(component_type: ComponentType) -> InstanceHoldingRegistry[Any, Any] | None: + """ + Return the registry whose entries a saved entry may name, or None for a kind saved entries can't use. + + Saved entries may use only the kinds that restore rebuilds. + + Returns: + InstanceHoldingRegistry[Any, Any] | None: The registry, or None. + """ + from pyrit.registry.components.converter_registry import ConverterRegistry + from pyrit.registry.components.scorer_registry import ScorerRegistry from pyrit.registry.components.target_registry import TargetRegistry - targets = TargetRegistry.get_registry_singleton().instances + registries: dict[ComponentType, Any] = { + ComponentType.TARGET: TargetRegistry, + ComponentType.CONVERTER: ConverterRegistry, + ComponentType.SCORER: ScorerRegistry, + } + registry = registries.get(component_type) + return registry.get_registry_singleton() if registry is not None else None + + +def refuse_temporary_references(*, parameters: Sequence[Parameter], params: Mapping[str, Any]) -> None: + """ + Refuse an entry to save that uses a Temporary entry, which won't exist after a restart. + + Args: + parameters (Sequence[Parameter]): The class's constructor parameters. + params (Mapping[str, Any]): The entry's constructor parameters. + + Raises: + NotSaveableError: If a parameter names a Temporary entry, or an entry of a kind saved entries can't use. + """ for parameter in parameters: - if parameter.reference is None or parameter.reference.component_type is not ComponentType.TARGET: + if parameter.reference is None: continue value = params.get(parameter.name) - for name in value if isinstance(value, list) else [value]: - entry = targets.get_entry(name) if isinstance(name, str) else None - if entry is not None and registry_entry_origin(entry.metadata) is RegistryEntryOrigin.TEMPORARY: - raise NotSaveableError(f"Uses temporary target '{name}', which won't exist after a restart.") + refuse_temporary_entries( + component_type=parameter.reference.component_type, + names=value if isinstance(value, list) else [value], + ) + + +def refuse_temporary_entries(*, component_type: ComponentType, names: Sequence[Any]) -> None: + """ + Refuse an entry to save that names a Temporary entry, which won't exist after a restart. + + Args: + component_type (ComponentType): The kind of entry the names refer to. + names (Sequence[Any]): The names the entry uses; values that aren't names are skipped. + + Raises: + NotSaveableError: If a name is a Temporary entry, or an entry of a kind saved entries can't use. + """ + for name in names: + if not isinstance(name, str) or not name: + continue + registry = _referenced_registry(component_type) + if registry is None: + raise NotSaveableError(f"Uses {component_type.value} '{name}', which saved entries can't use yet.") + entry = registry.instances.get_entry(name) + if entry is not None and registry_entry_origin(entry.metadata) is RegistryEntryOrigin.TEMPORARY: + raise NotSaveableError( + f"Uses temporary {component_type.value} '{name}', which won't exist after a restart." + ) async def save_then_register_async( *, kind: RegistryRecipeKind, name: str, - recipe: ComponentRecipe, + recipe: ComponentRecipe | TechniqueRecipe, register: Callable[[dict[str, Any]], object], source: str | None = None, + replacing: SavedEntryReplacement | None = None, ) -> None: """ Save an entry's recipe, then register the entry as saved. The recipe is written only if no saved entry of the kind has the name, so of two saves under one name only one - succeeds. If registering then fails, the recipe this save wrote is deleted again. A save that's cancelled - finishes, or is undone, before the cancellation is passed on, so the saved recipes and the registry agree. + succeeds. If registering then fails, the recipe this save wrote is deleted again, unless another writer has + replaced it since. Saving first checks that every entry the recipe names still comes back after a restart, since + one may have been deleted after the entry was checked; code that also deletes saved entries holds one lock around + both. A save that's cancelled finishes, or is undone, before the cancellation is passed on, so the saved recipes + and the registry agree. Args: kind (RegistryRecipeKind): The kind of entry. name (str): The entry's name. - recipe (ComponentRecipe): How restore rebuilds the entry. + recipe (ComponentRecipe | TechniqueRecipe): How restore rebuilds the entry. register (Callable[[dict[str, Any]], object]): Registers the built entry with the metadata it's given. source (str | None): Local directory or Azure Blob URI holding the saved entries. Defaults to ``registry_recipes`` under the PyRIT configuration directory. + replacing (SavedEntryReplacement | None): The saved entry an edit rebuilds, whose recipe is overwritten + instead, or None to save a new entry. Defaults to None. Raises: - SavedEntryConflictError: If a saved or registered entry of the kind already has the name. - SavedEntryStorageError: If the recipe can't be written, or can't be deleted after registering failed. + SavedEntryConflictError: If a saved or registered entry of the kind already has the name, an entry the + recipe names was deleted, or the recipe an edit replaces changed since it was read. + SavedEntryStorageError: If the recipe can't be written, or can't be deleted or put back after registering + failed. """ - await _settle_async( - asyncio.create_task( - _save_then_register_async(kind=kind, name=name, recipe=recipe, register=register, source=source) + # Looking up the recipe's classes can wait on discovery, so it stays off the event loop. + await asyncio.to_thread(_refuse_missing_references, kind=kind, recipe=recipe, source=source) + transaction = ( + _replace_then_register_async( + kind=kind, name=name, recipe=recipe, register=register, source=source, replacing=replacing ) + if replacing is not None + else _save_then_register_async(kind=kind, name=name, recipe=recipe, register=register, source=source) ) + await _settle_async(asyncio.create_task(transaction)) + + +def _refuse_missing_references( + *, kind: RegistryRecipeKind, recipe: ComponentRecipe | TechniqueRecipe, source: str | None +) -> None: + """ + Refuse a recipe that names an entry which no longer comes back after a restart. + + Raises: + SavedEntryConflictError: If a named entry isn't registered, or is Temporary. + """ + for ref in RegistryRecipeRestorer(source=source).recipe_references(kind=kind, recipe=recipe): + entry = _registry_for_kind(ref.kind).instances.get_entry(ref.name) + if entry is None or registry_entry_origin(entry.metadata) is RegistryEntryOrigin.TEMPORARY: + raise SavedEntryConflictError( + f"{ref.kind.value.removesuffix('s').capitalize()} '{ref.name}' was deleted while this was being " + "saved, so it can't be saved now." + ) + + +def _registry_for_kind(kind: RegistryRecipeKind) -> InstanceHoldingRegistry[Any, Any]: + """ + Return the registry that holds saved entries of a kind. + + Returns: + InstanceHoldingRegistry[Any, Any]: The registry. + """ + from pyrit.registry.components.attack_technique_registry import AttackTechniqueRegistry + from pyrit.registry.components.converter_registry import ConverterRegistry + from pyrit.registry.components.scorer_registry import ScorerRegistry + from pyrit.registry.components.target_registry import TargetRegistry + + registries: dict[RegistryRecipeKind, Any] = { + RegistryRecipeKind.TARGETS: TargetRegistry, + RegistryRecipeKind.CONVERTERS: ConverterRegistry, + RegistryRecipeKind.SCORERS: ScorerRegistry, + RegistryRecipeKind.TECHNIQUES: AttackTechniqueRegistry, + } + return registries[kind].get_registry_singleton() async def _settle_async(transaction: asyncio.Task[None]) -> None: @@ -268,7 +477,7 @@ async def _save_then_register_async( *, kind: RegistryRecipeKind, name: str, - recipe: ComponentRecipe, + recipe: ComponentRecipe | TechniqueRecipe, register: Callable[[dict[str, Any]], object], source: str | None, ) -> None: @@ -302,6 +511,61 @@ async def _save_then_register_async( raise +async def _replace_then_register_async( + *, + kind: RegistryRecipeKind, + name: str, + recipe: ComponentRecipe | TechniqueRecipe, + register: Callable[[dict[str, Any]], object], + source: str | None, + replacing: SavedEntryReplacement, +) -> None: + """ + Overwrite the recipe an edit read, then register the rebuilt entry if the old one was running. + + The old recipe is put back if registering fails. + + Raises: + SavedEntryConflictError: If the recipe changed since it was read, or registering refused the entry. + SavedEntryStorageError: If the recipe can't be written, or can't be put back after registering failed. + """ + singular = kind.value.removesuffix("s") + storage = RegistryRecipeStorage(kind=kind, source=source) + try: + version = await asyncio.to_thread( + storage.replace_recipe, name=name, recipe=recipe, expected_version=replacing.version + ) + except DocumentConflictError as error: + raise SavedEntryConflictError( + f"Saved {singular} '{name}' changed since it was read. Look at it again before changing it." + ) from error + except DocumentStorageUnavailableError as error: + _log_failure( + summary=f"Saved {singular} '{name}' couldn't be written to {storage.display_source} ({error.reason}).", + cause=error, + ) + raise SavedEntryStorageError(f"Saved {kind.value} can't be written right now.") from error + if not replacing.running: + return + try: + register({SAVED_ENTRY_METADATA_KEY: kind.value}) + except Exception as error: + try: + await asyncio.to_thread( + storage.replace_recipe, name=name, recipe=replacing.previous, expected_version=version + ) + except (DocumentConflictError, DocumentStorageUnavailableError) as put_back_error: + _log_failure( + summary=f"Saved {singular} '{name}' in {storage.display_source} holds the new settings, but the " + "edited entry couldn't be registered. Its old settings come back only if the file is fixed.", + cause=put_back_error, + ) + raise SavedEntryStorageError(f"Saved {kind.value} can't be written right now.") from error + if isinstance(error, RegistryNameTakenError): + raise SavedEntryConflictError(str(error)) from error + raise + + async def _delete_recipe_async(*, storage: RegistryRecipeStorage, singular: str, name: str, version: str) -> bool: """ Delete a recipe whose entry couldn't be registered, unless another writer has replaced it since. diff --git a/pyrit/registry/registry_recipe_storage.py b/pyrit/registry/registry_recipe_storage.py index 8438eb1b35..6ab17b89cf 100644 --- a/pyrit/registry/registry_recipe_storage.py +++ b/pyrit/registry/registry_recipe_storage.py @@ -26,7 +26,7 @@ TechniqueRecipe, ) from pyrit.models.catalog.registry_recipe import RECIPE_SCHEMA_VERSION -from pyrit.registry.file_document_storage import FileDocumentStorage +from pyrit.registry.file_document_storage import FileDocumentStorage, describe_storage_error if TYPE_CHECKING: from collections.abc import Mapping @@ -207,14 +207,61 @@ def create_recipe(self, *, name: str, recipe: ComponentRecipe | TechniqueRecipe) """ return self._save_document_conditional(name=name, content=self._serialize(recipe), expected_version=None) + def replace_recipe(self, *, name: str, recipe: ComponentRecipe | TechniqueRecipe, expected_version: str) -> str: + """ + Overwrite a saved recipe, but only if it is still the version the caller read. + + Args: + name (str): The entry's name. + recipe (ComponentRecipe | TechniqueRecipe): The new recipe. + expected_version (str): The version the caller read. + + Returns: + str: The version of the saved document. + + Raises: + DocumentConflictError: If the stored recipe is gone or isn't ``expected_version``. + ValueError: If the name isn't a legal registry name. + TimeoutError: If a local write could not acquire the document lock. + OSError: If the local folder can't be written. + AzureError: If the Blob container can't be written. + """ + content = recipe.model_dump_json(indent=2, exclude_none=True).encode("utf-8") + return self._save_document_conditional(name=name, content=content, expected_version=expected_version) + + def read_recipe(self, name: str) -> StoredRecipe | RestoreFailure | None: + """ + Read one saved recipe. + + Args: + name (str): The entry's name. + + Returns: + StoredRecipe | RestoreFailure | None: The recipe, why its file can't be used, or None if no + recipe of this kind has the name. + + Raises: + ValueError: If the name isn't a legal registry name. + AzureError: If the Blob container can't be read. + """ + try: + content = self._read_document_bytes(name) + except OSError as error: + return self._failure( + name=name, reason=RestoreFailureReason.UNREADABLE_RECIPE, message=describe_storage_error(error) + ) + if content is None: + return None + return self._parse_recipe(name=name, content=content) + def delete_recipe(self, name: str, *, expected_version: str | None = None) -> bool: """ - Delete a saved recipe, such as one whose entry couldn't be registered after it was saved. + Delete a saved recipe. Args: name (str): The entry's name. - expected_version (str | None): The version the caller saved or read, so a recipe that changed since - then isn't deleted, or None to delete whatever is stored. Defaults to None. + expected_version (str | None): The version the caller read, so a recipe that changed since then + isn't deleted, or None to delete whatever is stored. Defaults to None. Returns: bool: True if the recipe existed and was deleted, False if it was already gone. diff --git a/tests/unit/backend/test_api_routes.py b/tests/unit/backend/test_api_routes.py index f28b6cf999..343d23c734 100644 --- a/tests/unit/backend/test_api_routes.py +++ b/tests/unit/backend/test_api_routes.py @@ -50,13 +50,13 @@ from pyrit.backend.models.scores import ApplyChatScorerResponse from pyrit.backend.models.targets import TargetTypeResponse from pyrit.backend.routes import version as version_routes -from pyrit.backend.routes.common import parse_label_query_params +from pyrit.backend.routes.common import parse_label_query_params, saved_entry_owner_from_request from pyrit.backend.routes.scores import _get_user_identifier -from pyrit.backend.routes.targets import _saved_entry_owner from pyrit.backend.services import AttackService from pyrit.backend.services.attack_service import AttackObjectiveConflictError from pyrit.backend.services.chat_scoring_service import ChatScoringError from pyrit.backend.services.manual_send_scheduler import ManualSendConflictError, ManualSendQueueFullError +from pyrit.backend.services.saved_entries import SavedEntryRemovalError from pyrit.memory import MemoryInterface from pyrit.memory.memory_interface import AttackStateConflictError from pyrit.models import AttackOutcome, ConverterIdentifier, MessagePiece, Score, TargetCapabilities, TargetIdentifier @@ -1589,7 +1589,7 @@ def test_create_target_records_the_signed_in_user_as_the_owner(self, client: Tes owner = SavedEntryOwner(oid="user-oid", name="Ada") with ( patch("pyrit.backend.routes.targets.get_target_service") as mock_get_service, - patch("pyrit.backend.routes.targets._saved_entry_owner", return_value=owner), + patch("pyrit.backend.routes.targets.saved_entry_owner_from_request", return_value=owner), ): mock_get_service.return_value.create_target_async = AsyncMock(side_effect=ValueError("stop")) @@ -1600,7 +1600,7 @@ def test_create_target_records_the_signed_in_user_as_the_owner(self, client: Tes def test_create_target_records_no_owner_when_not_saving(self, client: TestClient) -> None: with ( patch("pyrit.backend.routes.targets.get_target_service") as mock_get_service, - patch("pyrit.backend.routes.targets._saved_entry_owner") as saved_entry_owner, + patch("pyrit.backend.routes.targets.saved_entry_owner_from_request") as saved_entry_owner, ): mock_get_service.return_value.create_target_async = AsyncMock(side_effect=ValueError("stop")) @@ -1630,8 +1630,8 @@ def test_saved_entry_owner_is_the_signed_in_user(self, name: str, expected: str) request = Request({"type": "http"}) request.state.user = AuthenticatedUser(oid="user-oid", name=name, email="ada@example.invalid", groups=[]) - assert _saved_entry_owner(request) == SavedEntryOwner(oid="user-oid", name=expected) - assert _saved_entry_owner(Request({"type": "http"})) is None + assert saved_entry_owner_from_request(request) == SavedEntryOwner(oid="user-oid", name=expected) + assert saved_entry_owner_from_request(Request({"type": "http"})) is None def test_create_target_passes_admin_flag_from_request(self, client: TestClient) -> None: """The route resolves administrator access and forwards it to the service.""" @@ -1954,6 +1954,148 @@ def test_delete_converter_not_found(self, client: TestClient) -> None: assert response.status_code == status.HTTP_404_NOT_FOUND + def test_delete_converter_refuses_a_saved_converter(self, client: TestClient) -> None: + refusal = SavedEntryRemovalError( + "Saved converter 'base64_converter' comes back from its saved file at every start, so delete it with " + "DELETE /api/saved-entries/converters/base64_converter instead." + ) + with patch("pyrit.backend.routes.converters.get_converter_service") as mock_get_service: + mock_get_service.return_value.delete_converter_async = AsyncMock(side_effect=refusal) + + response = client.delete("/api/converters/base64_converter") + + assert response.status_code == status.HTTP_409_CONFLICT + assert response.json()["detail"] == str(refusal) + + @pytest.mark.parametrize( + ("error", "status_code"), + [ + (SavedEntryConflictError("A saved converter named 'shift' already exists."), status.HTTP_409_CONFLICT), + ( + SavedEntryStorageError("Saved converters can't be written right now."), + status.HTTP_503_SERVICE_UNAVAILABLE, + ), + ], + ) + def test_create_converter_maps_save_errors(self, client: TestClient, error: Exception, status_code: int) -> None: + with patch("pyrit.backend.routes.converters.get_converter_service") as mock_get_service: + mock_get_service.return_value.create_converter_async = AsyncMock(side_effect=error) + + response = client.post( + "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/api/converters", json={"name": "shift", "type": "CaesarConverter", "params": {}, "persist": True} + ) + + assert response.status_code == status_code + assert response.json()["detail"] == str(error) + + @pytest.mark.usefixtures("patch_central_database") + @pytest.mark.parametrize("persist", [False, True]) + def test_create_converter_answers_a_taken_name_with_an_untyped_conflict( + self, client: TestClient, tmp_path: Path, persist: bool + ) -> None: + name = f"taken_{uuid.uuid4().hex[:8]}" + body = {"name": name, "type": "ROT13Converter", "params": {}} + assert client.post("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/api/converters", json=body).status_code == status.HTTP_201_CREATED + + with patch.object(client.app.state, "registry_recipes_source", str(tmp_path), create=True): + response = client.post("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/api/converters", json={**body, "persist": persist}) + + assert response.status_code == status.HTTP_409_CONFLICT + assert response.json() == {"detail": f"Instance '{name}' already exists"} + + @pytest.mark.parametrize( + ("path", "entry_type", "message"), + [ + ("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/api/converters", "ROT13Converter", "A private converter can't be saved"), + ("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/api/scorers", "SubStringScorer", "A private scorer can't be saved"), + ], + ) + def test_create_refuses_to_save_a_private_entry( + self, client: TestClient, path: str, entry_type: str, message: str + ) -> None: + response = client.post( + path, json={"name": "mine", "type": entry_type, "params": {}, "persist": True, "private": True} + ) + + assert response.status_code == status.HTTP_422_UNPROCESSABLE_CONTENT + assert message in response.text + + def test_create_converter_marks_a_save_refusal_so_it_can_be_created_without_saving( + self, client: TestClient + ) -> None: + refusal = NotSaveableError("Saved converters can't keep uploaded files yet ('font_name').") + with patch("pyrit.backend.routes.converters.get_converter_service") as mock_get_service: + mock_get_service.return_value.create_converter_async = AsyncMock(side_effect=refusal) + + response = client.post( + "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/api/converters", + json={"name": "banner", "type": "AddTextImageConverter", "params": {}, "persist": True}, + ) + + assert response.status_code == status.HTTP_400_BAD_REQUEST + assert response.json() == { + "type": "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/errors/not-saveable", + "title": "Can't be saved", + "status": 400, + "detail": str(refusal), + "instance": "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/api/converters", + "not_saveable_reason": refusal.cause, + } + + def test_create_converter_passes_the_signed_in_user_and_the_saved_entries_source(self, client: TestClient) -> None: + owner = SavedEntryOwner(oid="user-oid", name="Ada") + with ( + patch("pyrit.backend.routes.converters.get_converter_service") as mock_get_service, + patch("pyrit.backend.routes.converters.saved_entry_owner_from_request", return_value=owner), + patch.object(client.app.state, "registry_recipes_source", "/srv/registry-recipes", create=True), + ): + mock_get_service.return_value.create_converter_async = AsyncMock(side_effect=ValueError("stop")) + + client.post( + "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/api/converters", json={"name": "shift", "type": "CaesarConverter", "params": {}, "persist": True} + ) + + kwargs = mock_get_service.return_value.create_converter_async.call_args.kwargs + assert (kwargs["owner"], kwargs["recipes_source"], kwargs["request"].persist) == ( + owner, + "/srv/registry-recipes", + True, + ) + + def test_create_converter_records_no_owner_when_not_saving(self, client: TestClient) -> None: + with ( + patch("pyrit.backend.routes.converters.get_converter_service") as mock_get_service, + patch("pyrit.backend.routes.converters.saved_entry_owner_from_request") as saved_entry_owner, + ): + mock_get_service.return_value.create_converter_async = AsyncMock(side_effect=ValueError("stop")) + + client.post("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/api/converters", json={"name": "shift", "type": "CaesarConverter", "params": {}}) + + assert mock_get_service.return_value.create_converter_async.call_args.kwargs["owner"] is None + saved_entry_owner.assert_not_called() + + @pytest.mark.parametrize( + ("fields", "message"), + [ + ({}, "name is required when register=true"), + ({"name": "Shift-Two"}, "Invalid registry name"), + ({"name": "shift", "register": False}, "persist requires register=true"), + ( + {"name": "shift", "source": {"source_name": "caesar", "source_hash": "a" * 64, "params": {}}}, + "persist can't be used with source", + ), + ], + ) + def test_create_converter_checks_what_persist_needs( + self, client: TestClient, fields: dict[str, object], message: str + ) -> None: + body: dict[str, object] = {"type": "CaesarConverter", "persist": True, **fields} + + response = client.post("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/api/converters", json=body) + + assert response.status_code == status.HTTP_422_UNPROCESSABLE_CONTENT + assert message in json.dumps(response.json()) + def test_preview_conversion_success(self, client: TestClient) -> None: """Test previewing a conversion.""" with patch("pyrit.backend.routes.converters.get_converter_service") as mock_get_service: diff --git a/tests/unit/backend/test_converter_service.py b/tests/unit/backend/test_converter_service.py index 9ce5f20329..baba3fd1cd 100644 --- a/tests/unit/backend/test_converter_service.py +++ b/tests/unit/backend/test_converter_service.py @@ -8,14 +8,18 @@ import asyncio import base64 import codecs -from collections.abc import AsyncGenerator +import json +from collections.abc import AsyncGenerator, Iterator +from functools import partial from io import BytesIO from pathlib import Path +from typing import Any from unittest.mock import AsyncMock, MagicMock, call, patch from urllib.parse import quote, urlencode import pytest -from fastapi import HTTPException +from azure.core.exceptions import AzureError +from fastapi import FastAPI, HTTPException, Request from fastapi.testclient import TestClient from PIL import Image from pydantic import ValidationError @@ -31,6 +35,9 @@ ConverterService, get_converter_service, ) +from pyrit.backend.services.saved_entries import SavedEntryRemovalError +from pyrit.backend.services.saved_entry_restore import build_saved_entry_async +from pyrit.common import apply_defaults, reset_default_values, set_default_value from pyrit.converter import ( AzureSpeechTextToAudioConverter, Base64Converter, @@ -50,9 +57,30 @@ ) from pyrit.memory import AzureBlobStorageIO, CentralMemory, MemoryInterface from pyrit.models import ComponentIdentifier, PromptDataType, SeedPrompt +from pyrit.models.catalog import ( + ComponentRecipe, + RegistryEntryOrigin, + RegistryRecipeKind, + RegistryRestoreReport, + SavedEntryOwner, +) from pyrit.models.component_spec import SourceInstanceSpec from pyrit.prompt_normalizer import PromptNormalizer -from pyrit.registry import ConverterRegistry, TargetRegistry +from pyrit.prompt_target import PromptTarget +from pyrit.registry import ( + ConverterRegistry, + NotSaveableError, + SavedEntryConflictError, + SavedEntryStorageError, + TargetRegistry, +) +from pyrit.registry.instance_registry import ( + SAVED_ENTRY_METADATA_KEY, + RegistryNameTakenError, + registration_origin, +) +from pyrit.registry.registry_recipe_restore import RegistryRecipeRestorer +from pyrit.registry.registry_recipe_storage import RegistryRecipeStorage from unit.async_utils import TEST_WATCHDOG_SECONDS from unit.mocks import MockPromptTarget @@ -97,6 +125,10 @@ def _make_data_uri(*, mime_type: str, content: bytes) -> str: return f"data:{mime_type};base64,{base64.b64encode(content).decode('ascii')}" +def _route_request() -> Request: + return Request({"type": "http", "app": FastAPI(), "method": "POST", "path": "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/api/converters", "headers": []}) + + @pytest.fixture(autouse=True) def reset_registry(): """Reset the converter registry before each test.""" @@ -234,8 +266,10 @@ async def pause_deletion_async(*, paths: list[Path]) -> None: await asyncio.wait_for(release.wait(), timeout=TEST_WATCHDOG_SECONDS) await remove(paths=paths) - def signal_build(*, converter_id: str, converter_obj: object) -> object: - result = build(converter_id=converter_id, converter_obj=converter_obj) + def signal_build( + *, converter_id: str, converter_obj: object, origin: RegistryEntryOrigin | None = None + ) -> object: + result = build(converter_id=converter_id, converter_obj=converter_obj, origin=origin) built.set() return result @@ -275,7 +309,8 @@ async def test_converter_input_errors_return_400_async( with patch.object(converter_routes, "get_converter_service", return_value=upload_service): with pytest.raises(HTTPException) as exc: await converter_routes.create_converter( - CreateConverterRequest(name="invalid_binary", type="BinaryConverter", params=params) + body=CreateConverterRequest(name="invalid_binary", type="BinaryConverter", params=params), + request=_route_request(), ) assert exc.value.status_code == 400 assert next(iter(params)) in exc.value.detail @@ -288,9 +323,10 @@ async def test_speech_converter_region_must_be_a_region_name_async( with patch.object(converter_routes, "get_converter_service", return_value=upload_service): with pytest.raises(HTTPException) as exc: await converter_routes.create_converter( - CreateConverterRequest( + body=CreateConverterRequest( name="speech", type=converter_type, params={"azure_speech_region": "example.com#"} - ) + ), + request=_route_request(), ) assert exc.value.status_code == 400 assert "azure_speech_region must be an Azure region name" in exc.value.detail @@ -302,14 +338,15 @@ async def test_binary_creation_from_metadata_and_selection_async(upload_service: bits = next(param for param in binary.parameters if param.name == "bits_per_char").model_dump(mode="json") with patch.object(converter_routes, "get_converter_service", return_value=upload_service): result = await converter_routes.create_converter( - CreateConverterRequest( + request=_route_request(), + body=CreateConverterRequest( type="BinaryConverter", name="selected_binary", params={ "bits_per_char": bits["default"], "word_selection_strategy": {"type": "indices", "parameters": {"indices": [1]}}, }, - ) + ), ) instance = upload_service.get_converter_object(converter_id=result.converter_id) converted = await instance.convert_async(prompt="a b") @@ -324,7 +361,9 @@ def __init__(self) -> None: upload_service._registry.register_class(BrokenBinary) with patch.object(converter_routes, "get_converter_service", return_value=upload_service): with pytest.raises(HTTPException) as exc: - await converter_routes.create_converter(CreateConverterRequest(name="broken_binary", type="BrokenBinary")) + await converter_routes.create_converter( + body=CreateConverterRequest(name="broken_binary", type="BrokenBinary"), request=_route_request() + ) assert exc.value.status_code == 500 assert "constructor bug" in exc.value.detail @@ -2341,3 +2380,545 @@ def test_base64_converter_default_params(self) -> None: # Verify type info is populated from identifier assert isinstance(result.identifier.supported_input_types, list) assert isinstance(result.identifier.supported_output_types, list) + + +async def _restore(source: Path) -> RegistryRestoreReport: + """Restore the saved converters through the API's create, as startup does.""" + get_converter_service.cache_clear() + build_async = partial(build_saved_entry_async, upload_directory=None) + return await RegistryRecipeRestorer(source=str(source)).restore_async(build_async=build_async) + + +def _persist(name: str, converter_type: str, params: dict[str, Any] | None = None) -> CreateConverterRequest: + return CreateConverterRequest(name=name, type=converter_type, params=params or {}, persist=True) + + +def _saved_converter(source: Path, name: str) -> dict[str, Any]: + return json.loads((source / "converters" / f"{name}.json").read_text()) + + +@pytest.fixture +def startup_and_launch_targets(patch_central_database: MagicMock) -> Iterator[None]: + TargetRegistry.reset_registry_singleton() + targets = TargetRegistry.get_registry_singleton().instances + with registration_origin(RegistryEntryOrigin.CONFIGURATION): + targets.register(MockPromptTarget(), name="startup_chat") + targets.register(MockPromptTarget(), name="launch_chat") + yield + TargetRegistry.reset_registry_singleton() + + +@pytest.mark.usefixtures("patch_central_database") +class TestPersistConverter: + async def test_saves_a_converter_that_restore_rebuilds( + self, upload_service: ConverterService, tmp_path: Path + ) -> None: + owner = SavedEntryOwner(oid="00000000-0000-0000-0000-000000000001", name="Ada") + + converter = await upload_service.create_converter_async( + request=_persist("caesar_converter", "CaesarConverter", {"caesar_offset": 5}), + owner=owner, + recipes_source=str(tmp_path), + ) + + assert converter.origin is RegistryEntryOrigin.SAVED + assert _saved_converter(tmp_path, "caesar_converter") == { + "schema_version": 1, + "class_module": "pyrit.converter.caesar_converter", + "class_name": "CaesarConverter", + "params": {"caesar_offset": 5}, + "owner": {"oid": owner.oid, "name": "Ada"}, + } + entry = upload_service._registry.instances.get_entry("caesar_converter") + assert entry is not None + assert entry.metadata == {SAVED_ENTRY_METADATA_KEY: "converters"} + saved_hash = entry.instance.get_identifier().hash + ConverterRegistry.reset_registry_singleton() + assert (await _restore(tmp_path)).failures == [] + restored = ConverterRegistry.get_registry_singleton().instances.get("caesar_converter") + assert restored is not None + assert restored.get_identifier().hash == saved_hash + + async def test_saves_without_an_owner_when_sign_in_is_off( + self, upload_service: ConverterService, tmp_path: Path + ) -> None: + await upload_service.create_converter_async( + request=_persist("base64_converter", "Base64Converter"), recipes_source=str(tmp_path) + ) + + assert "owner" not in _saved_converter(tmp_path, "base64_converter") + + @pytest.mark.usefixtures("startup_and_launch_targets") + async def test_saves_a_converter_only_over_a_target_that_comes_back_after_a_restart( + self, upload_service: ConverterService, tmp_path: Path + ) -> None: + with pytest.raises(NotSaveableError) as refusal: + await upload_service.create_converter_async( + request=_persist( + "launch_french", "TranslationConverter", {"converter_target": "launch_chat", "language": "French"} + ), + recipes_source=str(tmp_path), + ) + startup_french = await upload_service.create_converter_async( + request=_persist( + "startup_french", "TranslationConverter", {"converter_target": "startup_chat", "language": "French"} + ), + recipes_source=str(tmp_path), + ) + + assert str(refusal.value) == ( + "Uses temporary target 'launch_chat', which won't exist after a restart. " + "It can still be created without saving it." + ) + assert upload_service._registry.instances.get("launch_french") is None + assert not (tmp_path / "converters" / "launch_french.json").exists() + assert startup_french.origin is RegistryEntryOrigin.SAVED + assert _saved_converter(tmp_path, "startup_french")["params"] == { + "converter_target": "startup_chat", + "language": "French", + } + + @pytest.mark.parametrize("converter_type", ["AzureSpeechTextToAudioConverter", "AzureSpeechAudioToTextConverter"]) + async def test_saves_a_converter_that_uses_this_servers_key( + self, upload_service: ConverterService, tmp_path: Path, converter_type: str + ) -> None: + with patch.dict("os.environ", {"AZURE_SPEECH_KEY": "server-speech-key"}): + converter = await upload_service.create_converter_async( + request=_persist("speech", converter_type, {"azure_speech_region": "eastus"}), + recipes_source=str(tmp_path), + ) + ConverterRegistry.reset_registry_singleton() + report = await _restore(tmp_path) + + assert converter.origin is RegistryEntryOrigin.SAVED + assert _saved_converter(tmp_path, "speech")["params"] == {"azure_speech_region": "eastus"} + assert "server-speech-key" not in (tmp_path / "converters" / "speech.json").read_text() + assert report.failures == [] + assert ConverterRegistry.get_registry_singleton().instances.get("speech") is not None + + @pytest.mark.parametrize("converter_type", ["AzureSpeechTextToAudioConverter", "AzureSpeechAudioToTextConverter"]) + async def test_refuses_a_converter_that_would_save_a_key( + self, upload_service: ConverterService, tmp_path: Path, converter_type: str + ) -> None: + params = {"azure_speech_region": "eastus", "azure_speech_key": "typed-speech-key"} + + with pytest.raises(NotSaveableError) as refusal: + await upload_service.create_converter_async( + request=_persist("speech", converter_type, params), recipes_source=str(tmp_path) + ) + + assert str(refusal.value) == ( + "Saved entries can't hold credentials ('azure_speech_key'). It can still be created without saving it." + ) + assert upload_service._registry.instances.get("speech") is None + assert not (tmp_path / "converters").exists() + + @pytest.mark.parametrize( + "font_name", + [ + _make_data_uri(mime_type="font/ttf", content=b"font"), + "https://contoso.blob.core.windows.net/results/fonts/font.ttf", + None, + ], + ) + async def test_refuses_an_uploaded_file_before_storing_it( + self, upload_service: ConverterService, tmp_path: Path, font_name: str | None + ) -> None: + request = _persist("banner", "AddTextImageConverter", {"text_to_add": "hello", "font_name": font_name}) + + with pytest.raises(NotSaveableError) as refusal: + await upload_service.create_converter_async(request=request, recipes_source=str(tmp_path)) + + assert str(refusal.value) == ( + "Saved converters can't keep uploaded files yet ('font_name'). It can still be created without saving it." + ) + assert list(upload_service._upload_path.iterdir()) == [] + assert upload_service._registry.instances.get("banner") is None + assert not (tmp_path / "converters").exists() + + @pytest.mark.parametrize( + ("converter_type", "parameter"), + [ + ("AddImageTextConverter", "img_to_add"), + ("AddImageVideoConverter", "video_path"), + ("ImageOverlayConverter", "base_image"), + ("TransparencyAttackConverter", "benign_image_path"), + ], + ) + @pytest.mark.parametrize("with_file", [True, False]) + async def test_refuses_a_converter_type_that_needs_an_uploaded_file( + self, upload_service: ConverterService, tmp_path: Path, converter_type: str, parameter: str, with_file: bool + ) -> None: + params = {parameter: _make_data_uri(mime_type="image/png", content=b"image")} if with_file else {} + + with pytest.raises(NotSaveableError) as refusal: + await upload_service.create_converter_async( + request=_persist("uploads", converter_type, params), recipes_source=str(tmp_path) + ) + + assert str(refusal.value) == ( + f"'{converter_type}' can't be saved. It needs an uploaded file, which saved converters can't keep yet. " + "It can still be created without saving it." + ) + assert list(upload_service._upload_path.iterdir()) == [] + assert not (tmp_path / "converters").exists() + + async def test_saves_a_converter_whose_optional_file_is_left_out( + self, upload_service: ConverterService, tmp_path: Path + ) -> None: + await upload_service.create_converter_async( + request=_persist("banner", "AddTextImageConverter", {"text_to_add": "hello"}), recipes_source=str(tmp_path) + ) + + assert _saved_converter(tmp_path, "banner")["params"] == {"text_to_add": "hello"} + ConverterRegistry.reset_registry_singleton() + assert (await _restore(tmp_path)).failures == [] + + async def test_a_taken_name_is_a_conflict_only_when_saving( + self, upload_service: ConverterService, tmp_path: Path + ) -> None: + await upload_service.create_converter_async( + request=CreateConverterRequest(name="base64_converter", type="Base64Converter") + ) + + with pytest.raises(SavedEntryConflictError, match="already"): + await upload_service.create_converter_async( + request=_persist("base64_converter", "Base64Converter"), recipes_source=str(tmp_path) + ) + with pytest.raises(ValueError, match="already") as temporary_clash: + await upload_service.create_converter_async( + request=CreateConverterRequest(name="base64_converter", type="Base64Converter") + ) + + assert not isinstance(temporary_clash.value, SavedEntryConflictError) + assert not (tmp_path / "converters").exists() + + async def test_a_reserved_name_is_refused_as_invalid_not_as_taken( + self, upload_service: ConverterService, tmp_path: Path + ) -> None: + with pytest.raises(ValueError, match="reserved") as refusal: + await upload_service.create_converter_async( + request=_persist("preview", "Base64Converter"), recipes_source=str(tmp_path) + ) + + assert not isinstance(refusal.value, (SavedEntryConflictError, NotSaveableError)) + assert not (tmp_path / "converters").exists() + + async def test_a_saved_file_with_the_name_is_a_conflict_that_leaves_the_file( + self, upload_service: ConverterService, tmp_path: Path + ) -> None: + storage = RegistryRecipeStorage(kind=RegistryRecipeKind.CONVERTERS, source=str(tmp_path)) + storage.create_recipe(name="base64_converter", recipe=ComponentRecipe(class_module="m", class_name="X")) + before = (tmp_path / "converters" / "base64_converter.json").read_bytes() + + with pytest.raises(SavedEntryConflictError, match="A saved converter named 'base64_converter' already exists."): + await upload_service.create_converter_async( + request=_persist("base64_converter", "Base64Converter"), recipes_source=str(tmp_path) + ) + + assert upload_service._registry.instances.get("base64_converter") is None + assert (tmp_path / "converters" / "base64_converter.json").read_bytes() == before + + @pytest.mark.parametrize( + ("error", "reason"), + [ + (PermissionError(13, "Permission denied", "/srv/recipes/converters/x.json"), "Permission denied"), + (OSError("disk full"), "OSError"), + (AzureError("unreachable"), "AzureError"), + ], + ) + async def test_reports_storage_failures_as_unavailable( + self, upload_service: ConverterService, tmp_path: Path, error: Exception, reason: str + ) -> None: + with ( + patch.object(RegistryRecipeStorage, "_save_local_conditional", side_effect=error), + patch("pyrit.registry.registry_recipe_save.logger") as log, + pytest.raises(SavedEntryStorageError, match="Saved converters can't be written right now."), + ): + await upload_service.create_converter_async( + request=_persist("base64_converter", "Base64Converter"), recipes_source=str(tmp_path) + ) + + assert upload_service._registry.instances.get("base64_converter") is None + assert log.error.call_args.args[0].startswith( + f"Saved converter 'base64_converter' couldn't be written to {tmp_path / 'converters'} " + f"({reason}). If the write reached storage anyway, the converter is restored at the next start.\n" + ) + + @pytest.mark.parametrize( + ("error", "raised"), + [ + (RegistryNameTakenError("Instance 'base64_converter' already exists"), SavedEntryConflictError), + (ValueError("Instance name 'base64_converter' is reserved"), ValueError), + (RuntimeError("x"), RuntimeError), + ], + ) + async def test_deletes_the_saved_file_when_the_converter_cant_be_registered( + self, upload_service: ConverterService, tmp_path: Path, error: Exception, raised: type[Exception] + ) -> None: + with ( + patch.object(upload_service._registry.instances, "register", side_effect=error), + pytest.raises(raised) as refusal, + ): + await upload_service.create_converter_async( + request=_persist("base64_converter", "Base64Converter"), recipes_source=str(tmp_path) + ) + + assert type(refusal.value) is raised + assert not (tmp_path / "converters" / "base64_converter.json").exists() + + async def test_two_saves_of_one_name_save_one_converter( + self, upload_service: ConverterService, tmp_path: Path + ) -> None: + results = await asyncio.gather( + upload_service.create_converter_async( + request=_persist("shift", "CaesarConverter", {"caesar_offset": 1}), recipes_source=str(tmp_path) + ), + upload_service.create_converter_async( + request=_persist("shift", "CaesarConverter", {"caesar_offset": 2}), recipes_source=str(tmp_path) + ), + return_exceptions=True, + ) + + assert sorted(type(result).__name__ for result in results) == ["ConverterInstance", "SavedEntryConflictError"] + registered = upload_service._registry.instances.get("shift") + assert registered is not None + assert ( + _saved_converter(tmp_path, "shift")["params"]["caesar_offset"] + == registered.get_identifier().params["caesar_offset"] + ) + + async def test_refuses_to_remove_a_saved_converter(self, upload_service: ConverterService, tmp_path: Path) -> None: + await upload_service.create_converter_async( + request=_persist("base64_converter", "Base64Converter"), recipes_source=str(tmp_path) + ) + + with pytest.raises(SavedEntryRemovalError) as refusal: + await upload_service.delete_converter_async(converter_id="base64_converter") + + assert str(refusal.value) == ( + "Saved converter 'base64_converter' comes back from its saved file at every start, so delete it with " + "DELETE /api/saved-entries/converters/base64_converter instead." + ) + assert upload_service._registry.instances.get("base64_converter") is not None + assert (tmp_path / "converters" / "base64_converter.json").exists() + + async def test_still_removes_converters_from_configuration_and_temporary_ones( + self, upload_service: ConverterService + ) -> None: + instances = upload_service._registry.instances + with registration_origin(RegistryEntryOrigin.CONFIGURATION): + instances.register(Base64Converter(), name="startup_base64") + await upload_service.create_converter_async( + request=CreateConverterRequest(name="launch_base64", type="Base64Converter") + ) + + assert await upload_service.delete_converter_async(converter_id="startup_base64") + assert await upload_service.delete_converter_async(converter_id="launch_base64") + assert instances.get_names() == [] + + async def test_list_get_and_create_tell_where_each_converter_comes_from( + self, upload_service: ConverterService, tmp_path: Path + ) -> None: + instances = upload_service._registry.instances + with registration_origin(RegistryEntryOrigin.CONFIGURATION): + instances.register(Base64Converter(), name="startup_base64") + saved = await upload_service.create_converter_async( + request=_persist("saved_base64", "Base64Converter"), recipes_source=str(tmp_path) + ) + temporary = await upload_service.create_converter_async( + request=CreateConverterRequest(name="launch_base64", type="Base64Converter") + ) + + listed = await upload_service.list_converters_async() + fetched = [ + await upload_service.get_converter_async(converter_id=name) + for name in ("startup_base64", "saved_base64", "launch_base64") + ] + + expected = { + "startup_base64": RegistryEntryOrigin.CONFIGURATION, + "saved_base64": RegistryEntryOrigin.SAVED, + "launch_base64": RegistryEntryOrigin.TEMPORARY, + } + assert {item.converter_id: item.origin for item in listed.items} == expected + assert {item.converter_id: item.origin for item in fetched if item is not None} == expected + assert (saved.origin, temporary.origin) == (RegistryEntryOrigin.SAVED, RegistryEntryOrigin.TEMPORARY) + + +@pytest.fixture +def default_converter_target(startup_and_launch_targets: None) -> Iterator[None]: + yield + reset_default_values() + + +@pytest.mark.usefixtures("patch_central_database", "default_converter_target") +class TestPersistConverterWithADefaultTarget: + async def test_names_a_default_target_from_configuration_in_the_saved_file( + self, upload_service: ConverterService, tmp_path: Path + ) -> None: + startup_chat = TargetRegistry.get_registry_singleton().instances.get("startup_chat") + set_default_value(class_type=TranslationConverter, parameter_name="converter_target", value=startup_chat) + + await upload_service.create_converter_async( + request=_persist("french", "TranslationConverter", {"language": "French"}), recipes_source=str(tmp_path) + ) + + assert _saved_converter(tmp_path, "french")["params"] == { + "language": "French", + "converter_target": "startup_chat", + } + reset_default_values() + ConverterRegistry.reset_registry_singleton() + assert (await _restore(tmp_path)).failures == [] + + async def test_names_a_default_target_by_a_name_that_lasts( + self, upload_service: ConverterService, tmp_path: Path + ) -> None: + targets = TargetRegistry.get_registry_singleton().instances + startup_chat = targets.get("startup_chat") + targets.register(startup_chat, name="a_launch_alias") + set_default_value(class_type=TranslationConverter, parameter_name="converter_target", value=startup_chat) + + await upload_service.create_converter_async( + request=_persist("french", "TranslationConverter", {"language": "French"}), recipes_source=str(tmp_path) + ) + + assert _saved_converter(tmp_path, "french")["params"]["converter_target"] == "startup_chat" + + @pytest.mark.parametrize("left_unset", [{}, {"converter_target": ""}, {"converter_target": None}]) + async def test_saves_an_optional_target_left_unset_as_sent( + self, upload_service: ConverterService, tmp_path: Path, left_unset: dict[str, Any] + ) -> None: + await upload_service.create_converter_async( + request=_persist("puzzled", "PuzzledConverter", left_unset), recipes_source=str(tmp_path) + ) + + assert _saved_converter(tmp_path, "puzzled")["params"] == left_unset + ConverterRegistry.reset_registry_singleton() + assert (await _restore(tmp_path)).failures == [] + + @pytest.mark.parametrize("left_unset", [{}, {"converter_target": None}, {"converter_target": ""}]) + async def test_refuses_a_default_target_that_is_gone_after_a_restart( + self, upload_service: ConverterService, tmp_path: Path, left_unset: dict[str, Any] + ) -> None: + launch_chat = TargetRegistry.get_registry_singleton().instances.get("launch_chat") + set_default_value(class_type=TranslationConverter, parameter_name="converter_target", value=launch_chat) + + with pytest.raises(NotSaveableError) as refusal: + await upload_service.create_converter_async( + request=_persist("french", "TranslationConverter", {"language": "French", **left_unset}), + recipes_source=str(tmp_path), + ) + + assert str(refusal.value) == ( + "Uses temporary target 'launch_chat', which won't exist after a restart. " + "It can still be created without saving it." + ) + assert not (tmp_path / "converters").exists() + + async def test_refuses_a_default_target_that_isnt_registered( + self, upload_service: ConverterService, tmp_path: Path + ) -> None: + set_default_value(class_type=TranslationConverter, parameter_name="converter_target", value=MockPromptTarget()) + + with pytest.raises(NotSaveableError) as refusal: + await upload_service.create_converter_async( + request=_persist("french", "TranslationConverter", {"language": "French"}), recipes_source=str(tmp_path) + ) + + assert str(refusal.value) == ( + "'converter_target' is left to a default target that isn't registered, so it won't exist after a " + "restart. It can still be created without saving it." + ) + assert not (tmp_path / "converters").exists() + + async def test_keeps_a_target_the_converter_class_names_itself( + self, upload_service: ConverterService, tmp_path: Path + ) -> None: + own_target = _register_own_target_converter(upload_service) + + try: + await upload_service.create_converter_async( + request=_persist("own_target", "OwnTargetTranslationConverter"), recipes_source=str(tmp_path) + ) + + assert _saved_converter(tmp_path, "own_target")["params"] == {} + saved = upload_service.get_converter_object(converter_id="own_target") + assert saved.converter_target is own_target + finally: + ConverterRegistry.reset_registry_singleton() + + async def test_a_target_sent_as_null_still_takes_the_configured_default( + self, upload_service: ConverterService, tmp_path: Path + ) -> None: + _register_own_target_converter(upload_service) + + try: + with pytest.raises(NotSaveableError) as refusal: + await upload_service.create_converter_async( + request=_persist("own_target", "OwnTargetTranslationConverter", {"converter_target": None}), + recipes_source=str(tmp_path), + ) + finally: + ConverterRegistry.reset_registry_singleton() + + assert str(refusal.value) == ( + "Uses temporary target 'launch_chat', which won't exist after a restart. " + "It can still be created without saving it." + ) + + +def _register_own_target_converter(service: ConverterService) -> PromptTarget: + """Register a converter class whose constructor names its own target, with a Temporary target as the default.""" + targets = TargetRegistry.get_registry_singleton().instances + own_target = targets.get("startup_chat") + assert own_target is not None + + class OwnTargetTranslationConverter(TranslationConverter): + @apply_defaults + def __init__(self, *, converter_target: PromptTarget = own_target) -> None: + super().__init__(converter_target=converter_target, language="French") + + service._registry.register_class(OwnTargetTranslationConverter) + set_default_value( + class_type=OwnTargetTranslationConverter, parameter_name="converter_target", value=targets.get("launch_chat") + ) + return own_target + + +async def test_types_say_why_a_converter_type_cant_be_saved() -> None: + types = await ConverterService().list_converter_types_async() + reasons = {item.converter_type: item.not_saveable_reason for item in types.items} + + assert reasons["AzureSpeechTextToAudioConverter"] is None + assert reasons["ImageOverlayConverter"] == ( + "'ImageOverlayConverter' can't be saved. It needs an uploaded file, which saved converters can't keep yet." + ) + assert reasons["AddTextImageConverter"] is None + assert reasons["CaesarConverter"] is None + assert {name for name, reason in reasons.items() if reason is not None} == { + "AddImageTextConverter", + "AddImageVideoConverter", + "ImageOverlayConverter", + "TransparencyAttackConverter", + } + + +class _LaunchScriptCaesarConverter(CaesarConverter): + """A converter class that only a scan's launch script registers.""" + + +async def test_types_say_a_converter_type_a_launch_script_added_cant_be_saved() -> None: + service = ConverterService() + with registration_origin(RegistryEntryOrigin.TEMPORARY): + service._registry.register_class(_LaunchScriptCaesarConverter) + + types = await service.list_converter_types_async() + + reasons = {item.converter_type: item.not_saveable_reason for item in types.items} + assert reasons["_LaunchScriptCaesarConverter"] == ( + "'_LaunchScriptCaesarConverter' was added by a scan's launch script, so a saved entry of it couldn't be " + "restored after a restart." + ) + assert reasons["CaesarConverter"] is None diff --git a/tests/unit/backend/test_private_targets.py b/tests/unit/backend/test_private_targets.py index fb36320851..9bc555c648 100644 --- a/tests/unit/backend/test_private_targets.py +++ b/tests/unit/backend/test_private_targets.py @@ -318,9 +318,9 @@ async def test_a_technique_using_a_private_converter_is_private_async() -> None: request = CreateTechniqueRequest(name="encoded", type="PromptSendingAttack", request_converters=["mine"]) with caller_principal_scope("bob"), pytest.raises(ValueError): - await TechniqueService().create_async(request) + await TechniqueService().create_async(request=request) with caller_principal_scope("alice"): - await TechniqueService().create_async(request) + await TechniqueService().create_async(request=request) with caller_principal_scope("bob"): assert await TechniqueService().get_async("encoded") is None diff --git a/tests/unit/backend/test_runtime_lifecycle.py b/tests/unit/backend/test_runtime_lifecycle.py index 933a1b0c8b..b3c71fe26b 100644 --- a/tests/unit/backend/test_runtime_lifecycle.py +++ b/tests/unit/backend/test_runtime_lifecycle.py @@ -24,7 +24,7 @@ from pyrit.backend.authentication_policy import AuthenticationPolicy from pyrit.backend.middleware.auth import require_admin from pyrit.backend.middleware.runtime import RuntimeAdmissionMiddleware -from pyrit.backend.routes import configuration, health, targets +from pyrit.backend.routes import configuration, health, saved_entries, targets 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 @@ -33,15 +33,21 @@ 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.converter import Base64Converter +from pyrit.executor.attack import PromptSendingAttack from pyrit.memory import CentralMemory, MemoryInterface from pyrit.models import ScenarioRunState -from pyrit.models.catalog import ComponentRecipe, RunScenarioRequest +from pyrit.models.catalog import ComponentRecipe, RegistryEntryOrigin, RunScenarioRequest from pyrit.prompt_target import OpenAIChatTarget, TextTarget from pyrit.registry import AttackTechniqueRegistry, ConverterRegistry, ScorerRegistry, TargetRegistry -from pyrit.registry.instance_registry import CONFIGURATION_ENTRY_METADATA_KEY +from pyrit.registry.instance_registry import ( + CONFIGURATION_ENTRY_METADATA_KEY, + registry_entry_origin, +) from pyrit.registry.registry_recipe_restore import RegistryRecipeRestorer, SavedRecipes from pyrit.registry.registry_recipe_storage import RegistryRecipeStorage -from pyrit.scenario import Scenario +from pyrit.scenario import AttackTechniqueFactory, Scenario +from pyrit.score import SubStringScorer from pyrit.setup import ConfigurationLoader from pyrit.setup.initialization import reset_setup_registries from unit.async_utils import TEST_WATCHDOG_SECONDS @@ -468,6 +474,28 @@ async def test_admitted_manual_send_blocks_reinitialization_without_an_http_requ get_manual_send_scheduler.cache_clear() +async def test_a_request_doesnt_count_itself_as_active_work_async(runtime: RuntimeLifecycle) -> None: + @runtime.app.get("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/api/probe-active-work") + async def probe() -> dict[str, bool]: + return {"active": runtime.has_active_work()} + + release = asyncio.Event() + + async def other_request_async() -> None: + await release.wait() + + async with httpx.AsyncClient(transport=httpx.ASGITransport(app=runtime.app), base_url="http://test") as client: + assert (await client.get("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/api/probe-active-work")).json() == {"active": False} + other = asyncio.create_task(other_request_async()) + runtime.operations.add(other) + try: + assert (await client.get("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/api/probe-active-work")).json() == {"active": True} + finally: + release.set() + await other + runtime.operations.discard(other) + + async def test_second_idle_check_closes_admission_race(runtime: RuntimeLifecycle) -> None: with patch.object(runtime, "_has_active_work", side_effect=[False, True]): await apply_async(runtime) @@ -1130,6 +1158,80 @@ async def test_startup_marks_the_targets_its_scripts_register_but_not_saved_ones assert CONFIGURATION_ENTRY_METADATA_KEY not in saved_entry.metadata +@pytest.mark.usefixtures("patch_central_database", "startup_chat") +async def test_startup_marks_the_converters_and_scorers_its_scripts_register_but_not_saved_ones_async( + runtime: RuntimeLifecycle, tmp_path: Path +) -> None: + ScorerRegistry.reset_registry_singleton() + recipes = tmp_path / "recipes" + base64 = {"class_module": Base64Converter.__module__, "class_name": "Base64Converter", "params": {}} + leak = {"class_module": SubStringScorer.__module__, "class_name": "SubStringScorer", "params": {"substring": "x"}} + _save_recipe(recipes, kind="converters", name="saved_base64", document=base64) + _save_recipe(recipes, kind="scorers", name="saved_leak", document=leak) + converters = ConverterRegistry.get_registry_singleton().instances + scorers = ScorerRegistry.get_registry_singleton().instances + + def register_startup_entries(**_: object) -> None: + converters.register(Base64Converter(), name="startup_base64") + scorers.register(SubStringScorer(substring="y"), name="startup_leak") + + try: + await _start_with_recipes_async(runtime, recipes=recipes, initialize=register_startup_entries) + + assert (runtime.state, runtime.outcome) == ("ready", "success") + entries = { + name: instances.get_entry(name) + for instances, name in ( + (converters, "startup_base64"), + (converters, "saved_base64"), + (scorers, "startup_leak"), + (scorers, "saved_leak"), + ) + } + assert {name: registry_entry_origin(entry.metadata) for name, entry in entries.items() if entry} == { + "startup_base64": RegistryEntryOrigin.CONFIGURATION, + "saved_base64": RegistryEntryOrigin.SAVED, + "startup_leak": RegistryEntryOrigin.CONFIGURATION, + "saved_leak": RegistryEntryOrigin.SAVED, + } + assert all( + CONFIGURATION_ENTRY_METADATA_KEY not in entry.metadata + for name, entry in entries.items() + if entry and name.startswith("saved_") + ) + finally: + ScorerRegistry.reset_registry_singleton() + + +@pytest.mark.usefixtures("patch_central_database", "startup_chat") +async def test_startup_marks_the_techniques_its_scripts_register_and_restores_saved_ones_with_their_owner_async( + runtime: RuntimeLifecycle, tmp_path: Path +) -> None: + AttackTechniqueRegistry.reset_registry_singleton() + recipes = tmp_path / "recipes" + owner = {"oid": "00000000-0000-0000-0000-000000000001", "name": "Ada"} + _save_recipe( + recipes, kind="techniques", name="saved_send", document={"type": "PromptSendingAttack", "owner": owner} + ) + techniques = AttackTechniqueRegistry.get_registry_singleton().instances + + def register_startup_technique(**_: object) -> None: + techniques.register_runtime(AttackTechniqueFactory(name="startup_send", attack_class=PromptSendingAttack)) + + try: + await _start_with_recipes_async(runtime, recipes=recipes, initialize=register_startup_technique) + + assert (runtime.state, runtime.outcome) == ("ready", "success") + startup, saved = techniques.get_entry("startup_send"), techniques.get_entry("saved_send") + assert startup is not None and saved is not None + assert (registry_entry_origin(startup.metadata), registry_entry_origin(saved.metadata)) == ( + RegistryEntryOrigin.CONFIGURATION, + RegistryEntryOrigin.SAVED, + ) + finally: + AttackTechniqueRegistry.reset_registry_singleton() + + class _LoopBoundTarget(MockPromptTarget): """A target whose constructor needs the running event loop, as HuggingFaceChatTarget's does.""" @@ -1580,6 +1682,54 @@ async def test_fixing_the_file_and_applying_restores_the_entry_async(runtime: Ru assert isinstance(TargetRegistry.get_registry_singleton().instances.get("ghost"), OpenAIChatTarget) +@pytest.mark.usefixtures("patch_central_database", "startup_chat") +async def test_an_edit_that_fixes_an_entry_that_couldnt_be_restored_comes_back_on_apply_async( + runtime: RuntimeLifecycle, tmp_path: Path +) -> None: + # The cached service holds the registry it was made with, so it's made again with this test's. + get_target_service.cache_clear() + recipes = tmp_path / "recipes" + unreachable = {"endpoint": "https://api.example.test/v1"} + _save_recipe( + recipes, + kind="targets", + name="ghost", + document={**_RESTORABLE_TARGET, "params": {**_RESTORABLE_TARGET["params"], **unreachable}}, + ) + await _start_with_recipes_async(runtime, recipes=recipes) + assert runtime.state == "failed" + # The fixture skips the management setup that names the storage source. + runtime.app.state.registry_recipes_source = str(recipes) + # Changing a saved entry takes an administrator. + runtime.app.state.authentication_policy = AuthenticationPolicy(mode="local", allow_unauthenticated_admin=True) + runtime.app.include_router(saved_entries.router, prefix="/api") + + async with httpx.AsyncClient(transport=httpx.ASGITransport(app=runtime.app), base_url="http://test") as client: + details = (await client.get("/api/saved-entries/targets/ghost")).json() + edit = await client.put( + "/api/saved-entries/targets/ghost", + json={ + "expected_version": details["version"], + "recipe": {**details["recipe"], "params": _RESTORABLE_TARGET["params"]}, + }, + ) + get_target_service.cache_clear() + + assert (edit.status_code, edit.json()["running"]) == (200, False) + assert runtime.state == "failed" + assert [failure["name"] for failure in runtime.status()["restore_failures"]] == ["ghost"] + assert TargetRegistry.get_registry_singleton().instances.get("ghost") is None + + config = await runtime._load_async() + config.apply_prepared_reinitialization_async.side_effect = lambda **_: TargetRegistry.reset_registry_singleton() + lifecycle_module.close_services_async.side_effect = _forget_registry_services_async + await apply_async(runtime) + + assert (runtime.state, runtime.outcome) == ("ready", "success") + assert runtime.status()["restore_failures"] == [] + assert isinstance(TargetRegistry.get_registry_singleton().instances.get("ghost"), OpenAIChatTarget) + + async def test_readiness_counts_restore_failures_without_their_details_async( runtime: RuntimeLifecycle, tmp_path: Path ) -> None: diff --git a/tests/unit/backend/test_saved_entry_edit.py b/tests/unit/backend/test_saved_entry_edit.py new file mode 100644 index 0000000000..b3f01e676b --- /dev/null +++ b/tests/unit/backend/test_saved_entry_edit.py @@ -0,0 +1,718 @@ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT license. + +import asyncio +import hashlib +import json +import threading +from collections.abc import Iterator +from functools import partial +from pathlib import Path +from typing import Any +from unittest.mock import AsyncMock, patch + +import pytest +from fastapi import FastAPI + +from pyrit.backend.models import CreateConverterRequest, CreateScorerRequest +from pyrit.backend.models.saved_entries import UpdateSavedEntryRequest +from pyrit.backend.models.techniques import CreateTechniqueRequest +from pyrit.backend.services import ConverterService, get_converter_service, get_target_service +from pyrit.backend.services.component_lifecycle import release_component_async +from pyrit.backend.services.configuration_file_service import ConfigurationFileService +from pyrit.backend.services.runtime_lifecycle import RuntimeLifecycle +from pyrit.backend.services.saved_entries import hold_saved_entry_lock_async, save_then_register_locked_async +from pyrit.backend.services.saved_entry_restore import build_saved_entry_async +from pyrit.backend.services.saved_entry_service import ( + SavedEntryForbiddenError, + SavedEntryInUseError, + SavedEntryRequestError, + SavedEntryService, +) +from pyrit.backend.services.scorer_service import ScorerService, get_scorer_service +from pyrit.backend.services.technique_service import TechniqueService, get_technique_service +from pyrit.converter import SearchReplaceConverter, ToneConverter +from pyrit.models.catalog import ( + ComponentRecipe, + RegistryEntryOrigin, + RegistryRecipeKind, + RegistryRestoreReport, + RestoreFailureReason, + SavedEntryOwner, +) +from pyrit.prompt_target import OpenAIChatTarget +from pyrit.registry import ( + AttackTechniqueRegistry, + ConverterRegistry, + NotSaveableError, + SavedEntryConflictError, + SavedEntryReplacement, + ScorerRegistry, + TargetRegistry, +) +from pyrit.registry.instance_registry import ( + RegistryNameTakenError, + registration_origin, + registry_entry_origin, +) +from pyrit.registry.registry_recipe_restore import RegistryRecipeRestorer +from pyrit.registry.registry_recipe_storage import RegistryRecipeStorage +from pyrit.setup.initializers.techniques import build_technique_factories +from unit.async_utils import TEST_WATCHDOG_SECONDS +from unit.mocks import MockPromptTarget + +ADA = SavedEntryOwner(oid="00000000-0000-0000-0000-000000000001", name="Ada") +BEN_OID = "00000000-0000-0000-0000-000000000002" +CONVERTERS, TARGETS = RegistryRecipeKind.CONVERTERS, RegistryRecipeKind.TARGETS +_SAVED_CHAT = { + "schema_version": 1, + "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", "headers": "{}"}, + "owner": {"oid": ADA.oid, "name": "Ada"}, +} + +pytestmark = pytest.mark.usefixtures("patch_central_database") + + +@pytest.fixture(autouse=True) +def isolated_registries() -> Iterator[None]: + # The cached services hold the registries they were made with, so they're made again with the new ones. + caches = (get_target_service, get_converter_service, get_scorer_service, get_technique_service) + registries = (TargetRegistry, ConverterRegistry, ScorerRegistry, AttackTechniqueRegistry) + for registry in registries: + registry.reset_registry_singleton() + for cache in caches: + cache.cache_clear() + yield + for registry in registries: + registry.reset_registry_singleton() + for cache in caches: + cache.cache_clear() + + +def _file(root: Path, kind: RegistryRecipeKind, name: str) -> Path: + return root / kind.value / f"{name}.json" + + +def _write(root: Path, kind: RegistryRecipeKind, name: str, document: dict[str, Any] | str) -> None: + path = _file(root, kind, name) + path.parent.mkdir(parents=True, exist_ok=True) + path.write_text(document if isinstance(document, str) else json.dumps(document), encoding="utf-8") + + +async def _restore(root: Path) -> RegistryRestoreReport: + """Restore the saved entries through the API's create, as startup does.""" + for cache in (get_target_service, get_converter_service, get_scorer_service, get_technique_service): + cache.cache_clear() + build_async = partial(build_saved_entry_async, upload_directory=None) + return await RegistryRecipeRestorer(source=str(root)).restore_async(build_async=build_async) + + +async def _save_replace(root: Path) -> None: + await ConverterService().create_converter_async( + request=CreateConverterRequest( + name="cat_replace", type="SearchReplaceConverter", params={"pattern": "cat", "replace": "dog"}, persist=True + ), + owner=ADA, + recipes_source=str(root), + ) + + +async def _read(root: Path, kind: RegistryRecipeKind, name: str, *, is_admin: bool = True) -> Any: + return await SavedEntryService().get_saved_entry_async( + kind=kind, name=name, recipes_source=str(root), is_admin=is_admin + ) + + +async def _edit( + root: Path, + kind: RegistryRecipeKind, + name: str, + *, + version: str, + recipe: dict[str, Any], + is_admin: bool = True, + runtime: RuntimeLifecycle | None = None, +) -> Any: + return await SavedEntryService().update_saved_entry_async( + kind=kind, + name=name, + request=UpdateSavedEntryRequest(expected_version=version, recipe=recipe), + recipes_source=str(root), + is_admin=is_admin, + runtime=runtime, + ) + + +async def test_an_administrator_changes_a_saved_converter_and_a_restart_keeps_the_change(tmp_path: Path) -> None: + await _save_replace(tmp_path) + old = ConverterRegistry.get_registry_singleton().instances.get("cat_replace") + details = await _read(tmp_path, CONVERTERS, "cat_replace") + assert details.recipe == { + "schema_version": 1, + "class_module": "pyrit.converter.search_replace_converter", + "class_name": "SearchReplaceConverter", + "params": {"pattern": "cat", "replace": "dog"}, + } + + edited = await _edit( + tmp_path, + CONVERTERS, + "cat_replace", + version=details.version, + recipe={**details.recipe, "params": {"pattern": "cat", "replace": "bird"}}, + ) + + content = _file(tmp_path, CONVERTERS, "cat_replace").read_bytes() + assert json.loads(content) == { + "schema_version": 1, + "class_module": "pyrit.converter.search_replace_converter", + "class_name": "SearchReplaceConverter", + "params": {"pattern": "cat", "replace": "bird"}, + "owner": {"oid": ADA.oid, "name": "Ada"}, + } + assert edited.version == hashlib.sha256(content).hexdigest() + assert (edited.running, edited.still_using_old) == (True, []) + entry = ConverterRegistry.get_registry_singleton().instances.get_entry("cat_replace") + assert entry is not None + assert entry.instance is not old + assert entry.instance.get_identifier().params["replace_list"] == ["bird"] + assert registry_entry_origin(entry.metadata) is RegistryEntryOrigin.SAVED + ConverterRegistry.reset_registry_singleton() + assert (await _restore(tmp_path)).failures == [] + restored = ConverterRegistry.get_registry_singleton().instances.get("cat_replace") + assert restored.get_identifier().params["replace_list"] == ["bird"] + + +async def test_an_administrator_changes_a_saved_target_and_who_saved_it_stays_in_its_file(tmp_path: Path) -> None: + _write(tmp_path, TARGETS, "saved_chat", _SAVED_CHAT) + assert (await _restore(tmp_path)).failures == [] + details = await _read(tmp_path, TARGETS, "saved_chat") + + await _edit( + tmp_path, + TARGETS, + "saved_chat", + version=details.version, + recipe={**details.recipe, "params": {**details.recipe["params"], "model_name": "gpt-4o-mini"}}, + ) + + saved = json.loads(_file(tmp_path, TARGETS, "saved_chat").read_text()) + assert saved["params"]["model_name"] == "gpt-4o-mini" + assert saved["owner"] == {"oid": ADA.oid, "name": "Ada"} + target = TargetRegistry.get_registry_singleton().instances.get("saved_chat") + assert target._model_name == "gpt-4o-mini" # type: ignore[attr-defined] + + +async def test_a_saved_scorer_and_technique_change_through_their_create_checks(tmp_path: Path) -> None: + await ScorerService().create_scorer_async( + request=CreateScorerRequest( + name="leak", type="SubStringScorer", params={"substring": "secret", "categories": ["leak"]}, persist=True + ), + owner=ADA, + recipes_source=str(tmp_path), + ) + AttackTechniqueRegistry.get_registry_singleton().register_from_factories(build_technique_factories()) + await TechniqueService().create_async( + request=CreateTechniqueRequest( + name="patient_send", type="PromptSendingAttack", params={"max_attempts_on_failure": 1}, persist=True + ), + owner=ADA, + recipes_source=str(tmp_path), + ) + scorer = await _read(tmp_path, RegistryRecipeKind.SCORERS, "leak") + technique = await _read(tmp_path, RegistryRecipeKind.TECHNIQUES, "patient_send") + + await _edit( + tmp_path, + RegistryRecipeKind.SCORERS, + "leak", + version=scorer.version, + recipe={**scorer.recipe, "params": {"substring": "password", "categories": ["leak"]}}, + ) + await _edit( + tmp_path, + RegistryRecipeKind.TECHNIQUES, + "patient_send", + version=technique.version, + recipe={**technique.recipe, "params": {"max_attempts_on_failure": 3}, "tags": ["patient"]}, + ) + + assert json.loads(_file(tmp_path, RegistryRecipeKind.SCORERS, "leak").read_text())["params"]["substring"] == ( + "password" + ) + saved = json.loads(_file(tmp_path, RegistryRecipeKind.TECHNIQUES, "patient_send").read_text()) + assert (saved["params"], saved["tags"]) == ({"max_attempts_on_failure": 3}, ["patient"]) + entry = AttackTechniqueRegistry.get_registry_singleton().instances.get_entry("patient_send") + assert entry is not None + assert entry.tags == {"patient": ""} + + +async def test_a_saved_technique_keeps_its_attack_type(tmp_path: Path) -> None: + AttackTechniqueRegistry.get_registry_singleton().register_from_factories(build_technique_factories()) + await TechniqueService().create_async( + request=CreateTechniqueRequest(name="patient_send", type="PromptSendingAttack", persist=True), + owner=ADA, + recipes_source=str(tmp_path), + ) + details = await _read(tmp_path, RegistryRecipeKind.TECHNIQUES, "patient_send") + + with pytest.raises(SavedEntryRequestError) as refusal: + await _edit( + tmp_path, + RegistryRecipeKind.TECHNIQUES, + "patient_send", + version=details.version, + recipe={**details.recipe, "type": "CrescendoAttack"}, + ) + + assert str(refusal.value) == "A saved technique's attack type can't change. Delete it and save a new one instead." + assert AttackTechniqueRegistry.get_registry_singleton().instances.get("patient_send") is not None + + +async def test_replacing_a_saved_entry_needs_the_lock_an_edit_holds(tmp_path: Path) -> None: + recipe = ComponentRecipe(class_module="m", class_name="SearchReplaceConverter", params={}) + register = AsyncMock() + + with pytest.raises(RuntimeError): + await save_then_register_locked_async( + kind=CONVERTERS, + name="cat_replace", + recipe=recipe, + register=register, + source=str(tmp_path), + replacing=SavedEntryReplacement(version="v1", previous=recipe, running=True), + ) + + register.assert_not_called() + + +async def test_a_task_that_holds_the_saved_entry_lock_cant_wait_on_it_again() -> None: + async def take_again() -> None: + async with hold_saved_entry_lock_async(): + pass + + async with hold_saved_entry_lock_async(): + # Without the check this would wait forever; the timeout turns that into a different error. + with pytest.raises(RuntimeError): + await asyncio.wait_for(take_again(), timeout=2) + + async with hold_saved_entry_lock_async(): + pass + + +async def test_an_edit_needs_the_version_it_read_and_an_administrator(tmp_path: Path) -> None: + await _save_replace(tmp_path) + details = await _read(tmp_path, CONVERTERS, "cat_replace") + changed = {**details.recipe, "params": {"pattern": "cat", "replace": "bird"}} + + with pytest.raises(SavedEntryInUseError): + await _edit(tmp_path, CONVERTERS, "cat_replace", version="0" * 64, recipe=changed) + with pytest.raises(SavedEntryForbiddenError) as refusal: + await _edit(tmp_path, CONVERTERS, "cat_replace", version=details.version, recipe=changed, is_admin=False) + + assert str(refusal.value) == "Only an administrator can change saved converter 'cat_replace'." + other = await _read(tmp_path, CONVERTERS, "cat_replace", is_admin=False) + assert (other.can_change, other.recipe) == (False, None) + assert json.loads(_file(tmp_path, CONVERTERS, "cat_replace").read_text())["params"]["replace"] == "dog" + + +@pytest.mark.parametrize( + ("change", "message"), + [ + ({"class_name": "ROT13Converter"}, "A saved converter's class can't change."), + ({"owner": {"oid": BEN_OID, "name": "Ben"}}, "Who saved a saved converter can't change"), + ({"source": "other"}, "Only the params of a saved converter"), + ({"auth_mode": "identity"}, "Only the params of a saved converter"), + ({"params": None}, "A saved converter's params must be an object."), + ], +) +async def test_an_edit_keeps_the_class_and_holds_only_what_a_saved_entry_can( + tmp_path: Path, change: dict[str, Any], message: str +) -> None: + await _save_replace(tmp_path) + details = await _read(tmp_path, CONVERTERS, "cat_replace") + + with pytest.raises(SavedEntryRequestError) as refusal: + await _edit(tmp_path, CONVERTERS, "cat_replace", version=details.version, recipe={**details.recipe, **change}) + + assert str(refusal.value).startswith(message) + assert ConverterRegistry.get_registry_singleton().instances.get("cat_replace") is not None + + +async def test_settings_a_new_entry_couldnt_save_leave_the_saved_one_as_it_was(tmp_path: Path) -> None: + _write(tmp_path, TARGETS, "saved_chat", _SAVED_CHAT) + _write( + tmp_path, + CONVERTERS, + "formal_tone", + { + "class_module": "pyrit.converter.tone_converter", + "class_name": "ToneConverter", + "params": {"converter_target": "saved_chat", "tone": "formal"}, + "owner": {"oid": ADA.oid, "name": "Ada"}, + }, + ) + assert (await _restore(tmp_path)).failures == [] + TargetRegistry.get_registry_singleton().instances.register(MockPromptTarget(), name="launch_chat") + converters = ConverterRegistry.get_registry_singleton().instances + old = converters.get("formal_tone") + details = await _read(tmp_path, CONVERTERS, "formal_tone") + before = _file(tmp_path, CONVERTERS, "formal_tone").read_bytes() + + with pytest.raises(NotSaveableError): + await _edit( + tmp_path, + CONVERTERS, + "formal_tone", + version=details.version, + recipe={**details.recipe, "params": {"converter_target": "launch_chat", "tone": "formal"}}, + ) + + assert _file(tmp_path, CONVERTERS, "formal_tone").read_bytes() == before + assert converters.get("formal_tone") is old + assert registry_entry_origin(converters.get_entry("formal_tone").metadata) is RegistryEntryOrigin.SAVED + + +async def test_an_entry_that_holds_the_edited_one_keeps_the_old_object_until_a_restart(tmp_path: Path) -> None: + _write(tmp_path, TARGETS, "saved_chat", _SAVED_CHAT) + assert (await _restore(tmp_path)).failures == [] + targets = TargetRegistry.get_registry_singleton().instances + old = targets.get("saved_chat") + tone = ToneConverter(converter_target=old, tone="formal") + ConverterRegistry.get_registry_singleton().instances.register(tone, name="formal_tone") + details = await _read(tmp_path, TARGETS, "saved_chat") + + with patch("pyrit.backend.services.saved_entry_service.release_component_async", AsyncMock()) as release: + edited = await _edit( + tmp_path, + TARGETS, + "saved_chat", + version=details.version, + recipe={**details.recipe, "params": {**details.recipe["params"], "model_name": "gpt-4o-mini"}}, + ) + + assert edited.still_using_old == ["temporary converter 'formal_tone'"] + assert targets.get("saved_chat") is not old + assert tone._converter_target is old # type: ignore[attr-defined] + release.assert_not_awaited() + + +async def test_an_entry_registered_while_the_edit_rebuilds_keeps_the_old_object(tmp_path: Path) -> None: + _write(tmp_path, TARGETS, "saved_chat", _SAVED_CHAT) + assert (await _restore(tmp_path)).failures == [] + old = TargetRegistry.get_registry_singleton().instances.get("saved_chat") + details = await _read(tmp_path, TARGETS, "saved_chat") + replace_recipe = RegistryRecipeStorage.replace_recipe + + def replace_while_a_request_registers_a_holder(storage: RegistryRecipeStorage, **kwargs: Any) -> str: + ConverterRegistry.get_registry_singleton().instances.register( + ToneConverter(converter_target=old, tone="formal"), name="formal_tone" + ) + return replace_recipe(storage, **kwargs) + + with ( + patch.object(RegistryRecipeStorage, "replace_recipe", replace_while_a_request_registers_a_holder), + patch("pyrit.backend.services.saved_entry_service.release_component_async", AsyncMock()) as release, + ): + edited = await _edit( + tmp_path, + TARGETS, + "saved_chat", + version=details.version, + recipe={**details.recipe, "params": {**details.recipe["params"], "model_name": "gpt-4o-mini"}}, + ) + + assert edited.still_using_old == ["temporary converter 'formal_tone'"] + release.assert_not_awaited() + + +@pytest.mark.parametrize("change", [{"name": "other_send"}, {"persist": False}]) +async def test_a_saved_technique_keeps_its_name_and_stays_saved(tmp_path: Path, change: dict[str, Any]) -> None: + AttackTechniqueRegistry.get_registry_singleton().register_from_factories(build_technique_factories()) + await TechniqueService().create_async( + request=CreateTechniqueRequest(name="patient_send", type="PromptSendingAttack", persist=True), + owner=ADA, + recipes_source=str(tmp_path), + ) + details = await _read(tmp_path, RegistryRecipeKind.TECHNIQUES, "patient_send") + + with pytest.raises(SavedEntryRequestError) as refusal: + await _edit( + tmp_path, + RegistryRecipeKind.TECHNIQUES, + "patient_send", + version=details.version, + recipe={**details.recipe, **change}, + ) + + assert str(refusal.value) == ( + "A saved technique keeps its name and stays saved. Delete it and save a new one instead." + ) + assert AttackTechniqueRegistry.get_registry_singleton().instances.get("patient_send") is not None + + +async def test_a_saved_target_needs_its_params_as_an_object(tmp_path: Path) -> None: + _write(tmp_path, TARGETS, "saved_chat", _SAVED_CHAT) + assert (await _restore(tmp_path)).failures == [] + details = await _read(tmp_path, TARGETS, "saved_chat") + + with pytest.raises(SavedEntryRequestError) as refusal: + await _edit(tmp_path, TARGETS, "saved_chat", version=details.version, recipe={**details.recipe, "params": None}) + + assert str(refusal.value) == "A saved target's params must be an object." + assert TargetRegistry.get_registry_singleton().instances.get("saved_chat") is not None + + +@pytest.mark.parametrize("held", [False, True]) +async def test_the_old_entry_is_released_only_when_nothing_could_use_it(tmp_path: Path, held: bool) -> None: + _write(tmp_path, TARGETS, "saved_chat", _SAVED_CHAT) + assert (await _restore(tmp_path)).failures == [] + old = TargetRegistry.get_registry_singleton().instances.get("saved_chat") + runtime = RuntimeLifecycle(app=FastAPI(), source=ConfigurationFileService(config_file_value=None)) + details = await _read(tmp_path, TARGETS, "saved_chat") + + with ( + patch.object(runtime, "_has_active_work", return_value=held), + patch("pyrit.backend.services.saved_entry_service.release_component_async", AsyncMock()) as release, + ): + await _edit( + tmp_path, + TARGETS, + "saved_chat", + version=details.version, + recipe={**details.recipe, "params": {**details.recipe["params"], "model_name": "gpt-4o-mini"}}, + runtime=runtime, + ) + + if held: + release.assert_not_awaited() + else: + release.assert_awaited_once_with(old) + + +async def test_an_edit_that_fixes_an_entry_that_failed_to_restore_only_saves_it(tmp_path: Path) -> None: + broken = {**_SAVED_CHAT, "params": {**_SAVED_CHAT["params"], "endpoint": "https://api.example.test/v1"}} + _write(tmp_path, TARGETS, "saved_chat", broken) + assert [failure.name for failure in (await _restore(tmp_path)).failures] == ["saved_chat"] + instances = TargetRegistry.get_registry_singleton().instances + details = await _read(tmp_path, TARGETS, "saved_chat") + + release = AsyncMock(wraps=release_component_async) + with patch("pyrit.backend.services.target_service.release_component_async", release): + edited = await _edit( + tmp_path, + TARGETS, + "saved_chat", + version=details.version, + recipe={**details.recipe, "params": _SAVED_CHAT["params"]}, + ) + + assert edited.running is False + # The next apply or start restores it into the registries as they are, so the edit must not have registered it. + assert instances.get("saved_chat") is None + # Nothing holds the target the edit built to check the new settings, so it's released. + release.assert_awaited_once() + assert isinstance(release.await_args.args[0], OpenAIChatTarget) + assert (await _restore(tmp_path)).failures == [] + assert isinstance(instances.get("saved_chat"), OpenAIChatTarget) + + +async def test_an_edit_that_doesnt_fix_an_entry_that_failed_to_restore_leaves_its_file(tmp_path: Path) -> None: + broken = {**_SAVED_CHAT, "params": {**_SAVED_CHAT["params"], "endpoint": "https://api.example.test/v1"}} + _write(tmp_path, TARGETS, "saved_chat", broken) + assert len((await _restore(tmp_path)).failures) == 1 + instances = TargetRegistry.get_registry_singleton().instances + details = await _read(tmp_path, TARGETS, "saved_chat") + before = _file(tmp_path, TARGETS, "saved_chat").read_bytes() + + with pytest.raises(ValueError): + await _edit(tmp_path, TARGETS, "saved_chat", version=details.version, recipe=details.recipe) + + assert instances.get("saved_chat") is None + assert _file(tmp_path, TARGETS, "saved_chat").read_bytes() == before + + +async def test_a_file_rewritten_after_the_edit_read_it_isnt_overwritten(tmp_path: Path) -> None: + await _save_replace(tmp_path) + instances = ConverterRegistry.get_registry_singleton().instances + old = instances.get("cat_replace") + details = await _read(tmp_path, CONVERTERS, "cat_replace") + path = _file(tmp_path, CONVERTERS, "cat_replace") + read_recipe = RegistryRecipeStorage.read_recipe + + def read_then_rewrite(storage: RegistryRecipeStorage, name: str) -> Any: + stored = read_recipe(storage, name) + path.write_text(path.read_text().replace('"dog"', '"fish"'), encoding="utf-8") + return stored + + with patch.object(RegistryRecipeStorage, "read_recipe", read_then_rewrite): + with pytest.raises(SavedEntryConflictError) as refusal: + await _edit( + tmp_path, + CONVERTERS, + "cat_replace", + version=details.version, + recipe={**details.recipe, "params": {"pattern": "cat", "replace": "bird"}}, + ) + + assert "changed since it was read" in str(refusal.value) + assert '"fish"' in path.read_text() + assert instances.get("cat_replace") is old + + +@pytest.mark.parametrize( + ("kind", "document"), + [ + (TARGETS, {"class_module": "pyrit.prompt_target.gone", "class_name": "GoneTarget", "params": {}}), + (CONVERTERS, {"class_module": "pyrit.converter.gone", "class_name": "GoneConverter", "params": {}}), + (RegistryRecipeKind.SCORERS, {"class_module": "pyrit.score.gone", "class_name": "GoneScorer", "params": {}}), + (RegistryRecipeKind.TECHNIQUES, {"type": "GoneAttack", "params": {}}), + ], +) +async def test_a_saved_entry_whose_class_is_gone_cant_be_changed( + tmp_path: Path, kind: RegistryRecipeKind, document: dict[str, Any] +) -> None: + _write(tmp_path, kind, "gone", {**document, "owner": {"oid": ADA.oid, "name": "Ada"}}) + details = await _read(tmp_path, kind, "gone") + before = _file(tmp_path, kind, "gone").read_bytes() + + # A plain ValueError is a 400 that names the class, rather than a server error. + with pytest.raises(ValueError) as refusal: + await _edit(tmp_path, kind, "gone", version=details.version, recipe={**details.recipe, "params": {"a": 1}}) + + assert "Gone" in str(refusal.value) + assert _file(tmp_path, kind, "gone").read_bytes() == before + + +async def test_a_file_that_cant_be_read_cant_be_changed(tmp_path: Path) -> None: + _write(tmp_path, CONVERTERS, "broken", "not json") + details = await _read(tmp_path, CONVERTERS, "broken") + + with pytest.raises(SavedEntryInUseError) as refusal: + await _edit(tmp_path, CONVERTERS, "broken", version=details.version, recipe={}) + + assert "can't be read or isn't a valid entry, so it can't be changed" in str(refusal.value) + + +async def test_a_name_a_startup_entry_took_cant_be_edited_into_coming_back(tmp_path: Path) -> None: + await _save_replace(tmp_path) + ConverterRegistry.reset_registry_singleton() + instances = ConverterRegistry.get_registry_singleton().instances + startup = SearchReplaceConverter(pattern="fish", replace="dog") + with registration_origin(RegistryEntryOrigin.CONFIGURATION): + instances.register(startup, name="cat_replace") + details = await _read(tmp_path, CONVERTERS, "cat_replace") + before = _file(tmp_path, CONVERTERS, "cat_replace").read_bytes() + + with pytest.raises(SavedEntryConflictError): + await _edit( + tmp_path, + CONVERTERS, + "cat_replace", + version=details.version, + recipe={**details.recipe, "params": {"pattern": "cat", "replace": "bird"}}, + ) + + assert instances.get("cat_replace") is startup + assert _file(tmp_path, CONVERTERS, "cat_replace").read_bytes() == before + + +async def test_an_edit_of_an_entry_whose_name_a_startup_entry_took_leaves_the_startup_entry(tmp_path: Path) -> None: + await _save_replace(tmp_path) + ConverterRegistry.reset_registry_singleton() + instances = ConverterRegistry.get_registry_singleton().instances + startup = SearchReplaceConverter(pattern="fish", replace="dog") + with registration_origin(RegistryEntryOrigin.CONFIGURATION): + instances.register(startup, name="cat_replace") + failures = (await _restore(tmp_path)).failures + assert [failure.reason for failure in failures] == [RestoreFailureReason.NAME_CLASH] + details = await _read(tmp_path, CONVERTERS, "cat_replace") + + with pytest.raises(SavedEntryConflictError, match="already exists"): + await _edit( + tmp_path, + CONVERTERS, + "cat_replace", + version=details.version, + recipe={**details.recipe, "params": {"pattern": "cat", "replace": "bird"}}, + ) + + assert instances.get("cat_replace") is startup + + +@pytest.mark.parametrize( + ("error", "raised"), + [ + (RegistryNameTakenError("Instance 'cat_replace' already exists"), SavedEntryConflictError), + (ValueError("refused"), ValueError), + ], +) +async def test_a_new_entry_that_cant_be_registered_puts_the_old_file_and_entry_back( + tmp_path: Path, error: Exception, raised: type[Exception] +) -> None: + await _save_replace(tmp_path) + instances = ConverterRegistry.get_registry_singleton().instances + old = instances.get("cat_replace") + details = await _read(tmp_path, CONVERTERS, "cat_replace") + before = _file(tmp_path, CONVERTERS, "cat_replace").read_bytes() + register = type(instances).register + + def refuse_the_new_one(registry: Any, instance: Any, **kwargs: Any) -> None: + if instance is not old: + raise error + register(registry, instance, **kwargs) + + with patch.object(type(instances), "register", refuse_the_new_one): + with pytest.raises(raised) as refusal: + await _edit( + tmp_path, + CONVERTERS, + "cat_replace", + version=details.version, + recipe={**details.recipe, "params": {"pattern": "cat", "replace": "bird"}}, + ) + + assert type(refusal.value) is raised + assert _file(tmp_path, CONVERTERS, "cat_replace").read_bytes() == before + assert instances.get("cat_replace") is old + + +async def test_a_cancelled_edit_keeps_the_new_entry_it_finished_saving(tmp_path: Path) -> None: + await _save_replace(tmp_path) + instances = ConverterRegistry.get_registry_singleton().instances + old = instances.get("cat_replace") + details = await _read(tmp_path, CONVERTERS, "cat_replace") + writing, release = threading.Event(), threading.Event() + replace_recipe = RegistryRecipeStorage.replace_recipe + + def slow_replace_recipe(storage: RegistryRecipeStorage, **kwargs: Any) -> str: + writing.set() + release.wait(TEST_WATCHDOG_SECONDS) + return replace_recipe(storage, **kwargs) + + with patch.object(RegistryRecipeStorage, "replace_recipe", slow_replace_recipe): + edit = asyncio.create_task( + _edit( + tmp_path, + CONVERTERS, + "cat_replace", + version=details.version, + recipe={**details.recipe, "params": {"pattern": "cat", "replace": "bird"}}, + ) + ) + try: + await asyncio.to_thread(writing.wait, TEST_WATCHDOG_SECONDS) + edit.cancel() + finally: + release.set() + with pytest.raises(asyncio.CancelledError): + await edit + + entry = instances.get_entry("cat_replace") + assert entry is not None + assert entry.instance is not old + assert entry.instance.get_identifier().params["replace_list"] == ["bird"] + assert json.loads(_file(tmp_path, CONVERTERS, "cat_replace").read_text())["params"]["replace"] == "bird" diff --git a/tests/unit/backend/test_saved_entry_routes.py b/tests/unit/backend/test_saved_entry_routes.py new file mode 100644 index 0000000000..10a399673b --- /dev/null +++ b/tests/unit/backend/test_saved_entry_routes.py @@ -0,0 +1,236 @@ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT license. + +from collections.abc import Iterator +from unittest.mock import AsyncMock, patch + +import httpx +import pytest +from fastapi import FastAPI +from fastapi.testclient import TestClient + +from pyrit.backend.authentication_policy import AuthenticationPolicy +from pyrit.backend.main import app +from pyrit.backend.middleware.runtime import RuntimeAdmissionMiddleware +from pyrit.backend.models.saved_entries import SavedEntryResponse, SavedEntryUpdateResponse +from pyrit.backend.routes import converters, saved_entries +from pyrit.backend.services.configuration_file_service import ConfigurationFileService +from pyrit.backend.services.runtime_lifecycle import RuntimeLifecycle +from pyrit.backend.services.saved_entry_service import ( + SavedEntryForbiddenError, + SavedEntryInUseError, + SavedEntryNotFoundError, + SavedEntryRequestError, + SavedEntryService, + SavedEntryVersionRequiredError, +) +from pyrit.models.catalog import RegistryRecipeKind +from pyrit.registry import NotSaveableError, SavedEntryConflictError, SavedEntryStorageError + +_ENTRY = SavedEntryResponse( + kind=RegistryRecipeKind.CONVERTERS, + name="cat_replace", + version="v1", + can_change=True, +) + + +@pytest.fixture +def client(compatibility_headers: dict[str, str]) -> Iterator[TestClient]: + with patch.object(app.state, "registry_recipes_source", "/recipes", create=True): + yield TestClient(app, headers=compatibility_headers) + + +def test_get_describes_the_saved_file(client: TestClient) -> None: + with patch.object(SavedEntryService, "get_saved_entry_async", AsyncMock(return_value=_ENTRY)) as get: + response = client.get("/api/saved-entries/converters/cat_replace") + + assert response.status_code == 200 + assert response.json() == { + "kind": "converters", + "name": "cat_replace", + "version": "v1", + "problem": None, + "recipe": None, + "can_change": True, + } + assert get.call_args.kwargs["recipes_source"] == "/recipes" + assert get.call_args.kwargs["kind"] is RegistryRecipeKind.CONVERTERS + + +@pytest.mark.parametrize( + "path", ["/api/saved-entries/converters/Cat-Replace", "/api/saved-entries/presets/cat_replace"] +) +def test_a_name_or_kind_that_cant_be_saved_is_refused(client: TestClient, path: str) -> None: + with patch.object(SavedEntryService, "get_saved_entry_async", AsyncMock()) as get: + assert client.get(path).status_code == 422 + assert client.delete(f"{path}?expected_version=v1").status_code == 422 + get.assert_not_awaited() + + +def test_delete_sends_the_version_and_the_runtime(client: TestClient) -> None: + runtime = RuntimeLifecycle(app=app, source=ConfigurationFileService(config_file_value=None)) + runtime.state = "ready" + with ( + patch.object(app.state, "runtime_lifecycle", runtime, create=True), + patch.object(SavedEntryService, "delete_saved_entry_async", AsyncMock()) as delete, + ): + response = client.delete("/api/saved-entries/techniques/formal_send?expected_version=v1") + + assert response.status_code == 204 + kwargs = delete.call_args.kwargs + assert (kwargs["kind"], kwargs["name"], kwargs["expected_version"]) == ( + RegistryRecipeKind.TECHNIQUES, + "formal_send", + "v1", + ) + assert kwargs["runtime"] is runtime + + +@pytest.mark.parametrize( + ("error", "status_code"), + [ + (SavedEntryNotFoundError("No saved converter is named 'cat_replace'."), 404), + (SavedEntryForbiddenError("Only an administrator can delete saved converter 'cat_replace'."), 403), + (SavedEntryVersionRequiredError("Send the version."), 422), + (SavedEntryInUseError("Saved converter 'cat_replace' is used by saved technique 'x'."), 409), + (SavedEntryStorageError("Saved converters can't be deleted right now."), 503), + ], +) +def test_delete_explains_why_it_didnt_delete(client: TestClient, error: Exception, status_code: int) -> None: + with patch.object(SavedEntryService, "delete_saved_entry_async", AsyncMock(side_effect=error)): + response = client.delete("/api/saved-entries/converters/cat_replace?expected_version=v1") + + assert response.status_code == status_code + assert response.json()["detail"] == str(error) + + +@pytest.mark.parametrize( + ("error", "status_code"), + [(SavedEntryNotFoundError("No saved converter is named 'x'."), 404), (SavedEntryStorageError("down"), 503)], +) +def test_get_explains_why_it_found_nothing(client: TestClient, error: Exception, status_code: int) -> None: + with patch.object(SavedEntryService, "get_saved_entry_async", AsyncMock(side_effect=error)): + response = client.get("/api/saved-entries/converters/cat_replace") + + assert response.status_code == status_code + + +@pytest.mark.parametrize( + ("policy", "is_admin"), + [ + (AuthenticationPolicy(mode="local"), False), + (AuthenticationPolicy(mode="local", allow_unauthenticated_admin=True), True), + ], +) +def test_changing_a_saved_entry_takes_an_administrator_in_local_mode_too( + client: TestClient, policy: AuthenticationPolicy, is_admin: bool +) -> None: + with ( + patch.object(app.state, "authentication_policy", policy), + patch.object(SavedEntryService, "get_saved_entry_async", AsyncMock(return_value=_ENTRY)) as get, + patch.object(SavedEntryService, "delete_saved_entry_async", AsyncMock()) as delete, + ): + client.get("/api/saved-entries/converters/cat_replace") + client.delete("/api/saved-entries/converters/cat_replace?expected_version=v1") + + assert (get.call_args.kwargs["is_admin"], delete.call_args.kwargs["is_admin"]) == (is_admin, is_admin) + + +async def test_a_saved_entry_can_be_deleted_while_the_runtime_isnt_ready() -> None: + failed_app = FastAPI() + failed_app.state.authentication_policy = AuthenticationPolicy(mode="local") + runtime = RuntimeLifecycle(app=failed_app, source=ConfigurationFileService(config_file_value=None)) + runtime.state = "failed" + failed_app.state.runtime_lifecycle = runtime + failed_app.add_middleware(RuntimeAdmissionMiddleware) + failed_app.include_router(saved_entries.router, prefix="/api") + failed_app.include_router(converters.router, prefix="/api") + + with patch.object(SavedEntryService, "delete_saved_entry_async", AsyncMock()) as delete: + transport = httpx.ASGITransport(app=failed_app) + async with httpx.AsyncClient(transport=transport, base_url="http://test") as http: + deleted = await http.delete("/api/saved-entries/converters/ghost?expected_version=v1") + listed = await http.get("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/api/converters") + + assert deleted.status_code == 204 + delete.assert_awaited_once() + assert listed.status_code == 503 + + +async def test_deleting_a_saved_entry_waits_while_the_runtime_is_starting() -> None: + starting_app = FastAPI() + starting_app.state.authentication_policy = AuthenticationPolicy(mode="local") + runtime = RuntimeLifecycle(app=starting_app, source=ConfigurationFileService(config_file_value=None)) + runtime.state = "initializing" + starting_app.state.runtime_lifecycle = runtime + starting_app.add_middleware(RuntimeAdmissionMiddleware) + starting_app.include_router(saved_entries.router, prefix="/api") + + with patch.object(SavedEntryService, "delete_saved_entry_async", AsyncMock()) as delete: + transport = httpx.ASGITransport(app=starting_app) + async with httpx.AsyncClient(transport=transport, base_url="http://test") as http: + deleted = await http.delete("/api/saved-entries/converters/ghost?expected_version=v1") + + assert deleted.status_code == 503 + delete.assert_not_awaited() + + +def test_put_sends_the_changed_recipe_and_returns_the_saved_file(client: TestClient) -> None: + updated = SavedEntryUpdateResponse(**_ENTRY.model_dump(), running=True, still_using_old=["temporary converter 'x'"]) + with patch.object(SavedEntryService, "update_saved_entry_async", AsyncMock(return_value=updated)) as update: + response = client.put( + "/api/saved-entries/converters/cat_replace", + json={"expected_version": "v1", "recipe": {"params": {"pattern": "cat", "replace": "bird"}}}, + ) + + assert response.status_code == 200 + assert (response.json()["running"], response.json()["still_using_old"]) == (True, ["temporary converter 'x'"]) + body = update.call_args.kwargs["request"] + assert (body.expected_version, body.recipe) == ("v1", {"params": {"pattern": "cat", "replace": "bird"}}) + + +@pytest.mark.parametrize( + "body", [{"recipe": {}}, {"expected_version": "v1"}, {"expected_version": "v1", "recipe": {}, "x": 1}] +) +def test_put_needs_a_version_and_a_recipe(client: TestClient, body: dict[str, object]) -> None: + with patch.object(SavedEntryService, "update_saved_entry_async", AsyncMock()) as update: + response = client.put("/api/saved-entries/converters/cat_replace", json=body) + + assert response.status_code == 422 + update.assert_not_awaited() + + +@pytest.mark.parametrize( + ("error", "status_code"), + [ + (SavedEntryNotFoundError("No saved converter is named 'cat_replace'."), 404), + (SavedEntryForbiddenError("Only Ada or an administrator can change saved converter 'cat_replace'."), 403), + (SavedEntryInUseError("Saved converter 'cat_replace' changed since it was read."), 409), + (SavedEntryRequestError("A saved converter's class can't change."), 422), + (SavedEntryConflictError("Converter 'x' was deleted while this was being saved."), 409), + (SavedEntryStorageError("Saved converters can't be written right now."), 503), + (PermissionError("Only an administrator can set trust_remote_code."), 403), + (ValueError("tone must be one of ..."), 400), + ], +) +def test_put_explains_why_it_didnt_change_it(client: TestClient, error: Exception, status_code: int) -> None: + with patch.object(SavedEntryService, "update_saved_entry_async", AsyncMock(side_effect=error)): + response = client.put( + "/api/saved-entries/converters/cat_replace", json={"expected_version": "v1", "recipe": {}} + ) + + assert response.status_code == status_code + assert response.json()["detail"] == str(error) + + +def test_put_says_when_the_new_settings_cant_be_saved(client: TestClient) -> None: + error = NotSaveableError("Uses temporary target 'launch_chat', which won't exist after a restart.") + with patch.object(SavedEntryService, "update_saved_entry_async", AsyncMock(side_effect=error)): + response = client.put( + "/api/saved-entries/converters/cat_replace", json={"expected_version": "v1", "recipe": {}} + ) + + assert response.status_code == 400 + assert response.json()["type"] == "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/errors/not-saveable" + assert response.json()["detail"] == str(error) diff --git a/tests/unit/backend/test_saved_entry_service.py b/tests/unit/backend/test_saved_entry_service.py new file mode 100644 index 0000000000..38eacc46bd --- /dev/null +++ b/tests/unit/backend/test_saved_entry_service.py @@ -0,0 +1,541 @@ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT license. + +import asyncio +import json +import threading +from collections.abc import Iterator +from functools import partial +from pathlib import Path +from typing import Any +from unittest.mock import AsyncMock, patch + +import pytest +from fastapi import FastAPI + +from pyrit.auth import caller_principal_scope +from pyrit.backend.models import CreateConverterRequest +from pyrit.backend.models.techniques import CreateTechniqueRequest +from pyrit.backend.services import ConverterService, get_converter_service, get_target_service +from pyrit.backend.services.configuration_file_service import ConfigurationFileService +from pyrit.backend.services.runtime_lifecycle import RuntimeLifecycle +from pyrit.backend.services.saved_entry_restore import build_saved_entry_async +from pyrit.backend.services.saved_entry_service import ( + SavedEntryForbiddenError, + SavedEntryInUseError, + SavedEntryNotFoundError, + SavedEntryService, + SavedEntryVersionRequiredError, +) +from pyrit.backend.services.scorer_service import get_scorer_service +from pyrit.backend.services.technique_service import TechniqueService, get_technique_service +from pyrit.converter import SearchReplaceConverter, ToneConverter +from pyrit.models.catalog import ( + ComponentRecipe, + RegistryEntryOrigin, + RegistryRecipeKind, + RegistryRestoreReport, + RestoreFailure, + RestoreFailureReason, + SavedEntryOwner, +) +from pyrit.registry import ( + AttackTechniqueRegistry, + ConverterRegistry, + SavedEntryStorageError, + ScorerRegistry, + TargetRegistry, + owner_metadata, +) +from pyrit.registry.file_document_storage import DocumentConflictError, DocumentStorageUnavailableError +from pyrit.registry.instance_registry import registration_origin, registry_entry_origin +from pyrit.registry.registry_recipe_restore import RegistryRecipeRestorer +from pyrit.registry.registry_recipe_storage import RegistryRecipeStorage +from unit.async_utils import TEST_WATCHDOG_SECONDS + +ADA = SavedEntryOwner(oid="00000000-0000-0000-0000-000000000001", name="Ada") +BEN_OID = "00000000-0000-0000-0000-000000000002" +CONVERTERS, TARGETS = RegistryRecipeKind.CONVERTERS, RegistryRecipeKind.TARGETS +_SAVED_CHAT = { + "schema_version": 1, + "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", "headers": "{}"}, + "owner": {"oid": ADA.oid, "name": "Ada"}, +} + +pytestmark = pytest.mark.usefixtures("patch_central_database") + + +@pytest.fixture(autouse=True) +def isolated_registries() -> Iterator[None]: + registries = (TargetRegistry, ConverterRegistry, ScorerRegistry, AttackTechniqueRegistry) + for registry in registries: + registry.reset_registry_singleton() + yield + for registry in registries: + registry.reset_registry_singleton() + + +def _write(root: Path, kind: RegistryRecipeKind, name: str, document: dict[str, Any] | str) -> Path: + folder = root / kind.value + folder.mkdir(parents=True, exist_ok=True) + path = folder / f"{name}.json" + path.write_text(document if isinstance(document, str) else json.dumps(document), encoding="utf-8") + return path + + +async def _restore_report(root: Path) -> RegistryRestoreReport: + for factory in (get_target_service, get_converter_service, get_scorer_service, get_technique_service): + factory.cache_clear() + build_async = partial(build_saved_entry_async, upload_directory=None) + return await RegistryRecipeRestorer(source=str(root)).restore_async(build_async=build_async) + + +async def _restore(root: Path) -> list[RestoreFailure]: + return (await _restore_report(root)).failures + + +async def _save_replace(root: Path, name: str = "cat_replace") -> None: + await ConverterService().create_converter_async( + request=CreateConverterRequest( + name=name, type="SearchReplaceConverter", params={"pattern": "cat", "replace": "dog"}, persist=True + ), + owner=ADA, + recipes_source=str(root), + ) + + +async def _version(root: Path, kind: RegistryRecipeKind, name: str) -> str: + details = await SavedEntryService().get_saved_entry_async( + kind=kind, name=name, recipes_source=str(root), is_admin=True + ) + assert details.version is not None + return details.version + + +async def _delete( + root: Path, + kind: RegistryRecipeKind, + name: str, + *, + version: str | None, + is_admin: bool = True, + runtime: RuntimeLifecycle | None = None, +) -> None: + await SavedEntryService().delete_saved_entry_async( + kind=kind, + name=name, + expected_version=version, + recipes_source=str(root), + is_admin=is_admin, + runtime=runtime, + ) + + +def _runtime() -> RuntimeLifecycle: + return RuntimeLifecycle(app=FastAPI(), source=ConfigurationFileService(config_file_value=None)) + + +async def test_an_administrator_deletes_a_saved_converter_and_it_doesnt_come_back(tmp_path: Path) -> None: + await _save_replace(tmp_path) + service = SavedEntryService() + + details = await service.get_saved_entry_async( + kind=CONVERTERS, name="cat_replace", recipes_source=str(tmp_path), is_admin=True + ) + assert (details.can_change, details.problem) == (True, None) + await _delete(tmp_path, CONVERTERS, "cat_replace", version=details.version) + + assert not (tmp_path / "converters" / "cat_replace.json").exists() + assert ConverterRegistry.get_registry_singleton().instances.get("cat_replace") is None + ConverterRegistry.reset_registry_singleton() + assert (await _restore_report(tmp_path)).restored == [] + + +async def test_only_an_administrator_may_change_a_saved_entry_even_for_whoever_saved_it(tmp_path: Path) -> None: + await _save_replace(tmp_path) + version = await _version(tmp_path, CONVERTERS, "cat_replace") + + details = await SavedEntryService().get_saved_entry_async( + kind=CONVERTERS, name="cat_replace", recipes_source=str(tmp_path), is_admin=False + ) + assert details.can_change is False + with pytest.raises(SavedEntryForbiddenError) as refusal: + await _delete(tmp_path, CONVERTERS, "cat_replace", version=version, is_admin=False) + assert str(refusal.value) == "Only an administrator can delete saved converter 'cat_replace'." + assert (tmp_path / "converters" / "cat_replace.json").exists() + assert ConverterRegistry.get_registry_singleton().instances.get("cat_replace") is not None + + +async def test_a_delete_needs_the_version_it_read_and_keeps_a_file_that_changed(tmp_path: Path) -> None: + await _save_replace(tmp_path) + + with pytest.raises(SavedEntryVersionRequiredError): + await _delete(tmp_path, CONVERTERS, "cat_replace", version=None) + with pytest.raises(SavedEntryInUseError) as refusal: + await _delete(tmp_path, CONVERTERS, "cat_replace", version="0" * 64) + + assert str(refusal.value) == ( + "Saved converter 'cat_replace' changed since it was read. Look at it again before deleting it." + ) + assert (tmp_path / "converters" / "cat_replace.json").exists() + assert ConverterRegistry.get_registry_singleton().instances.get("cat_replace") is not None + + +async def test_a_name_without_a_saved_file_isnt_found_and_its_startup_entry_stays(tmp_path: Path) -> None: + instances = ConverterRegistry.get_registry_singleton().instances + with registration_origin(RegistryEntryOrigin.CONFIGURATION): + instances.register(SearchReplaceConverter(pattern="cat", replace="dog"), name="startup_replace") + + for name in ("startup_replace", "never_saved"): + with pytest.raises(SavedEntryNotFoundError) as refusal: + await _delete(tmp_path, CONVERTERS, name, version="0" * 64) + assert str(refusal.value) == f"No saved converter is named '{name}'." + assert instances.get("startup_replace") is not None + + +async def test_deleting_a_saved_file_whose_name_a_startup_entry_took_keeps_that_entry(tmp_path: Path) -> None: + await _save_replace(tmp_path) + ConverterRegistry.reset_registry_singleton() + instances = ConverterRegistry.get_registry_singleton().instances + startup = SearchReplaceConverter(pattern="fish", replace="dog") + with registration_origin(RegistryEntryOrigin.CONFIGURATION): + instances.register(startup, name="cat_replace") + assert [failure.reason for failure in await _restore(tmp_path)] == [RestoreFailureReason.NAME_CLASH] + assert instances.get("cat_replace") is startup + + await _delete(tmp_path, CONVERTERS, "cat_replace", version=await _version(tmp_path, CONVERTERS, "cat_replace")) + + assert not (tmp_path / "converters" / "cat_replace.json").exists() + assert instances.get("cat_replace") is startup + + +async def test_an_entry_another_saved_entry_names_isnt_deleted(tmp_path: Path) -> None: + _write(tmp_path, TARGETS, "saved_chat", _SAVED_CHAT) + tone = { + "class_module": "pyrit.converter.tone_converter", + "class_name": "ToneConverter", + "params": {"converter_target": "saved_chat", "tone": "formal"}, + } + _write(tmp_path, CONVERTERS, "formal_tone", tone) + _write( + tmp_path, + RegistryRecipeKind.TECHNIQUES, + "formal_send", + {"type": "PromptSendingAttack", "request_converters": ["formal_tone"]}, + ) + assert await _restore(tmp_path) == [] + + with pytest.raises(SavedEntryInUseError) as target_refusal: + await _delete(tmp_path, TARGETS, "saved_chat", version=await _version(tmp_path, TARGETS, "saved_chat")) + with pytest.raises(SavedEntryInUseError) as converter_refusal: + await _delete( + tmp_path, + CONVERTERS, + "formal_tone", + version=await _version(tmp_path, CONVERTERS, "formal_tone"), + ) + + assert str(target_refusal.value) == ( + "Saved target 'saved_chat' is used by saved converter 'formal_tone'. Delete or change it first." + ) + assert str(converter_refusal.value) == ( + "Saved converter 'formal_tone' is used by saved technique 'formal_send'. Delete or change it first." + ) + assert TargetRegistry.get_registry_singleton().instances.get("saved_chat") is not None + assert (tmp_path / "targets" / "saved_chat.json").exists() + + +async def test_an_entry_a_temporary_entry_holds_isnt_deleted(tmp_path: Path) -> None: + _write(tmp_path, TARGETS, "saved_chat", _SAVED_CHAT) + assert await _restore(tmp_path) == [] + targets = TargetRegistry.get_registry_singleton().instances + converters = ConverterRegistry.get_registry_singleton().instances + converters.register(ToneConverter(converter_target=targets.get("saved_chat"), tone="formal"), name="formal_tone") + + with pytest.raises(SavedEntryInUseError) as refusal: + await _delete(tmp_path, TARGETS, "saved_chat", version=await _version(tmp_path, TARGETS, "saved_chat")) + + assert str(refusal.value) == ( + "Saved target 'saved_chat' is used by temporary converter 'formal_tone'. Delete or change it first. " + "A temporary entry is gone after the backend restarts or is reinitialized." + ) + assert targets.get("saved_chat") is not None + + +async def test_an_entry_another_users_private_entry_holds_isnt_deleted_and_isnt_named(tmp_path: Path) -> None: + _write(tmp_path, TARGETS, "saved_chat", _SAVED_CHAT) + assert await _restore(tmp_path) == [] + targets = TargetRegistry.get_registry_singleton().instances + ConverterRegistry.get_registry_singleton().instances.register( + ToneConverter(converter_target=targets.get("saved_chat"), tone="formal"), + name="bens_tone", + metadata=owner_metadata(BEN_OID, private=True), + ) + + with caller_principal_scope(ADA.oid), pytest.raises(SavedEntryInUseError) as refusal: + await _delete(tmp_path, TARGETS, "saved_chat", version=await _version(tmp_path, TARGETS, "saved_chat")) + + assert "another user's private converter" in str(refusal.value) + assert "bens_tone" not in str(refusal.value) + assert targets.get("saved_chat") is not None + + +async def test_a_converter_a_temporary_technique_holds_isnt_deleted(tmp_path: Path) -> None: + await _save_replace(tmp_path) + await TechniqueService().create_async( + request=CreateTechniqueRequest( + name="replace_send", type="PromptSendingAttack", request_converters=["cat_replace"] + ) + ) + + with pytest.raises(SavedEntryInUseError) as refusal: + await _delete(tmp_path, CONVERTERS, "cat_replace", version=await _version(tmp_path, CONVERTERS, "cat_replace")) + + assert "temporary technique 'replace_send'" in str(refusal.value) + + +async def test_a_target_a_temporary_technique_holds_through_its_converter_isnt_deleted(tmp_path: Path) -> None: + _write(tmp_path, TARGETS, "saved_chat", _SAVED_CHAT) + assert await _restore(tmp_path) == [] + converters = ConverterRegistry.get_registry_singleton().instances + tone = ToneConverter( + converter_target=TargetRegistry.get_registry_singleton().instances.get("saved_chat"), tone="formal" + ) + converters.register(tone, name="formal_tone") + await TechniqueService().create_async( + request=CreateTechniqueRequest( + name="formal_send", type="PromptSendingAttack", request_converters=["formal_tone"] + ) + ) + # The converter is no longer registered, but the technique still holds it, and through it the target. + converters.unregister("formal_tone") + + with pytest.raises(SavedEntryInUseError) as refusal: + await _delete(tmp_path, TARGETS, "saved_chat", version=await _version(tmp_path, TARGETS, "saved_chat")) + + assert "temporary technique 'formal_send'" in str(refusal.value) + + +async def test_a_file_rewritten_after_it_was_read_isnt_deleted(tmp_path: Path) -> None: + await _save_replace(tmp_path) + version = await _version(tmp_path, CONVERTERS, "cat_replace") + path = tmp_path / "converters" / "cat_replace.json" + read_recipe = RegistryRecipeStorage.read_recipe + + def read_then_rewrite(storage: RegistryRecipeStorage, name: str) -> Any: + stored = read_recipe(storage, name) + path.write_text(path.read_text().replace('"dog"', '"bird"'), encoding="utf-8") + return stored + + with patch.object(RegistryRecipeStorage, "read_recipe", read_then_rewrite): + with pytest.raises(SavedEntryInUseError) as refusal: + await _delete(tmp_path, CONVERTERS, "cat_replace", version=version) + + assert "changed since it was read" in str(refusal.value) + assert '"bird"' in path.read_text() + assert ConverterRegistry.get_registry_singleton().instances.get("cat_replace") is not None + + +async def test_a_running_entry_isnt_deleted_while_work_could_be_using_it(tmp_path: Path) -> None: + await _save_replace(tmp_path) + runtime = _runtime() + + with ( + patch.object(runtime, "_has_active_work", return_value=True), + patch("pyrit.backend.services.saved_entry_service._IDLE_WAIT_SECONDS", 0.1), + ): + with pytest.raises(SavedEntryInUseError) as refusal: + await _delete( + tmp_path, + CONVERTERS, + "cat_replace", + version=await _version(tmp_path, CONVERTERS, "cat_replace"), + runtime=runtime, + ) + + assert str(refusal.value) == ( + "Saved converter 'cat_replace' could be in use by a request, run, or send in progress. " + "Try again when it finishes." + ) + assert ConverterRegistry.get_registry_singleton().instances.get("cat_replace") is not None + assert (tmp_path / "converters" / "cat_replace.json").exists() + + +async def test_a_delete_waits_for_requests_in_flight_to_finish(tmp_path: Path) -> None: + await _save_replace(tmp_path) + runtime = _runtime() + version = await _version(tmp_path, CONVERTERS, "cat_replace") + + with patch.object(runtime, "_has_active_work", side_effect=[True, True, False]) as active: + await _delete(tmp_path, CONVERTERS, "cat_replace", version=version, runtime=runtime) + + assert active.call_count == 3 + assert not (tmp_path / "converters" / "cat_replace.json").exists() + + +async def test_an_entry_a_request_comes_to_hold_while_the_delete_waits_isnt_deleted(tmp_path: Path) -> None: + _write(tmp_path, TARGETS, "saved_chat", _SAVED_CHAT) + assert await _restore(tmp_path) == [] + targets = TargetRegistry.get_registry_singleton().instances + runtime = _runtime() + version = await _version(tmp_path, TARGETS, "saved_chat") + busy = iter([True, False]) + + def finish_a_request_that_registers_a_holder(**_: object) -> bool: + still_busy = next(busy) + if not still_busy: + ConverterRegistry.get_registry_singleton().instances.register( + ToneConverter(converter_target=targets.get("saved_chat"), tone="formal"), name="formal_tone" + ) + return still_busy + + with patch.object(runtime, "_has_active_work", side_effect=finish_a_request_that_registers_a_holder): + with pytest.raises(SavedEntryInUseError) as refusal: + await _delete(tmp_path, TARGETS, "saved_chat", version=version, runtime=runtime) + + assert "temporary converter 'formal_tone'" in str(refusal.value) + assert targets.get("saved_chat") is not None + assert (tmp_path / "targets" / "saved_chat.json").exists() + + +async def test_an_entry_that_failed_to_restore_is_deleted_and_no_longer_listed(tmp_path: Path) -> None: + _write( + tmp_path, + CONVERTERS, + "ghost", + {"class_module": "nowhere", "class_name": "Nope", "owner": {"oid": ADA.oid, "name": "Ada"}}, + ) + runtime = _runtime() + runtime.restore_failures = await _restore(tmp_path) + assert [failure.name for failure in runtime.restore_failures] == ["ghost"] + + # Nothing registered can be using it, so work in progress doesn't stop the delete. + with patch.object(runtime, "_has_active_work", return_value=True): + await _delete( + tmp_path, CONVERTERS, "ghost", version=await _version(tmp_path, CONVERTERS, "ghost"), runtime=runtime + ) + + assert not (tmp_path / "converters" / "ghost.json").exists() + assert runtime.restore_failures == [] + + +@pytest.mark.parametrize( + ("document", "read_error", "problem"), + [ + ("not json", None, RestoreFailureReason.INVALID_RECIPE), + ( + {"class_module": "m", "class_name": "C"}, + PermissionError(13, "Permission denied"), + RestoreFailureReason.UNREADABLE_RECIPE, + ), + ], +) +async def test_a_file_that_cant_be_used_is_deleted_only_by_an_administrator( + tmp_path: Path, document: dict[str, Any] | str, read_error: OSError | None, problem: RestoreFailureReason +) -> None: + _write(tmp_path, CONVERTERS, "broken", document) + read = patch.object(RegistryRecipeStorage, "_read_document_bytes", side_effect=read_error) if read_error else None + service = SavedEntryService() + if read is not None: + read.start() + try: + details = await service.get_saved_entry_async( + kind=CONVERTERS, name="broken", recipes_source=str(tmp_path), is_admin=False + ) + assert (details.problem, details.can_change) == (problem, False) + assert (details.version is None) is (read_error is not None) + with pytest.raises(SavedEntryForbiddenError) as refusal: + await _delete(tmp_path, CONVERTERS, "broken", version=details.version, is_admin=False) + assert str(refusal.value) == "Only an administrator can delete saved converter 'broken'." + + await _delete(tmp_path, CONVERTERS, "broken", version=details.version) + finally: + if read is not None: + read.stop() + + assert not (tmp_path / "converters" / "broken.json").exists() + + +@pytest.mark.parametrize( + "error", + [ + DocumentStorageUnavailableError(label="Converter", source="/srv/recipes", reason="No space left on device"), + DocumentConflictError(name="cat_replace", expected_version="a", actual_version="b"), + ], +) +async def test_an_entry_whose_file_cant_be_deleted_is_put_back(tmp_path: Path, error: Exception) -> None: + await _save_replace(tmp_path) + instances = ConverterRegistry.get_registry_singleton().instances + entry = instances.get_entry("cat_replace") + assert entry is not None + version = await _version(tmp_path, CONVERTERS, "cat_replace") + + with patch.object(RegistryRecipeStorage, "delete_recipe", side_effect=error): + expected = SavedEntryInUseError if isinstance(error, DocumentConflictError) else SavedEntryStorageError + with pytest.raises(expected): + await _delete(tmp_path, CONVERTERS, "cat_replace", version=version) + + restored = instances.get_entry("cat_replace") + assert restored is not None + assert restored.instance is entry.instance + assert registry_entry_origin(restored.metadata) is RegistryEntryOrigin.SAVED + assert (tmp_path / "converters" / "cat_replace.json").exists() + + +@pytest.mark.parametrize("also_registered", [False, True]) +async def test_a_deleted_entry_is_released_unless_it_is_still_registered(tmp_path: Path, also_registered: bool) -> None: + _write(tmp_path, TARGETS, "saved_chat", _SAVED_CHAT) + assert await _restore(tmp_path) == [] + targets = TargetRegistry.get_registry_singleton().instances + target = targets.get("saved_chat") + if also_registered: + targets.register(target, name="same_chat") + + with patch("pyrit.backend.services.saved_entry_service.release_component_async", AsyncMock()) as release: + await _delete(tmp_path, TARGETS, "saved_chat", version=await _version(tmp_path, TARGETS, "saved_chat")) + + assert targets.get("saved_chat") is None + if also_registered: + release.assert_not_awaited() + else: + release.assert_awaited_once_with(target) + + +async def test_a_delete_waits_for_a_save_in_progress_and_then_sees_it(tmp_path: Path) -> None: + _write(tmp_path, TARGETS, "saved_chat", _SAVED_CHAT) + assert await _restore(tmp_path) == [] + version = await _version(tmp_path, TARGETS, "saved_chat") + writing, finish_writing = threading.Event(), threading.Event() + create_recipe = RegistryRecipeStorage.create_recipe + + def create_recipe_slowly(storage: RegistryRecipeStorage, *, name: str, recipe: ComponentRecipe) -> str: + writing.set() + finish_writing.wait(TEST_WATCHDOG_SECONDS) + return create_recipe(storage, name=name, recipe=recipe) + + request = CreateConverterRequest( + name="formal_tone", + type="ToneConverter", + params={"converter_target": "saved_chat", "tone": "formal"}, + persist=True, + ) + with patch.object(RegistryRecipeStorage, "create_recipe", create_recipe_slowly): + save = asyncio.create_task( + ConverterService().create_converter_async(request=request, recipes_source=str(tmp_path)) + ) + try: + assert await asyncio.to_thread(writing.wait, TEST_WATCHDOG_SECONDS) + delete = asyncio.create_task(_delete(tmp_path, TARGETS, "saved_chat", version=version)) + await asyncio.sleep(0.05) + assert not delete.done() + finally: + finish_writing.set() + await save + + with pytest.raises(SavedEntryInUseError) as refusal: + await delete + assert "saved converter 'formal_tone'" in str(refusal.value) + assert (tmp_path / "targets" / "saved_chat.json").exists() diff --git a/tests/unit/backend/test_scorer_routes.py b/tests/unit/backend/test_scorer_routes.py index 1c468da242..4d1f8089a3 100644 --- a/tests/unit/backend/test_scorer_routes.py +++ b/tests/unit/backend/test_scorer_routes.py @@ -3,8 +3,10 @@ """Tests for scorer API routes.""" +import json +from pathlib import Path from typing import Any -from unittest.mock import MagicMock +from unittest.mock import AsyncMock, MagicMock, patch import pytest from fastapi.testclient import TestClient @@ -13,8 +15,9 @@ from pyrit.backend.models.common import MAX_CURSOR_LENGTH, MAX_IDENTIFIER_LENGTH, MAX_ITEMS from pyrit.backend.services.scorer_service import get_scorer_service from pyrit.models import ComponentIdentifier, Scorable, Score, ScoringExpectation, TargetIdentifier +from pyrit.models.catalog import SavedEntryOwner from pyrit.prompt_target import PromptTarget -from pyrit.registry import ScorerRegistry, TargetRegistry +from pyrit.registry import SavedEntryConflictError, SavedEntryStorageError, ScorerRegistry, TargetRegistry from pyrit.score import Scorer @@ -304,3 +307,116 @@ def test_scorer_types_list_azure_content_filter_api_key_as_sensitive(compatibili entry = next(item for item in response.json()["items"] if item["scorer_type"] == "AzureContentFilterScorer") api_key = next(parameter for parameter in entry["parameters"] if parameter["name"] == "api_key") assert api_key["sensitive"] is True + + +def test_create_scorer_with_persist_saves_it_and_lists_it_as_saved( + compatibility_headers: dict[str, str], patch_central_database: None, tmp_path: Path +) -> None: + client = TestClient(app, headers=compatibility_headers) + body = {"name": "leak_substring", "type": "SubStringScorer", "params": {"substring": "secret"}, "persist": True} + + with patch.object(client.app.state, "registry_recipes_source", str(tmp_path), create=True): + created = client.post("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/api/scorers", json=body) + fetched = client.get("/api/scorers/leak_substring") + listed = client.get("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/api/scorers") + + assert created.status_code == 201 + assert (created.json()["origin"], fetched.json()["origin"]) == ("saved", "saved") + assert [item["origin"] for item in listed.json()["items"]] == ["saved"] + assert json.loads((tmp_path / "scorers" / "leak_substring.json").read_text())["params"] == {"substring": "secret"} + + +def test_create_scorer_marks_a_save_refusal_so_it_can_be_created_without_saving( + compatibility_headers: dict[str, str], patch_central_database: None, tmp_path: Path +) -> None: + client = TestClient(app, headers=compatibility_headers) + body = { + "name": "content_safety", + "type": "AzureContentFilterScorer", + "params": {"endpoint": "https://contoso.cognitiveservices.azure.com/", "api_key": "typed-safety-key"}, + "persist": True, + } + + with patch.object(client.app.state, "registry_recipes_source", str(tmp_path), create=True): + response = client.post("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/api/scorers", json=body) + + assert response.status_code == 400 + assert response.json() == { + "type": "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/errors/not-saveable", + "title": "Can't be saved", + "status": 400, + "detail": "Saved entries can't hold credentials ('api_key'). It can still be created without saving it.", + "instance": "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/api/scorers", + "not_saveable_reason": "Saved entries can't hold credentials ('api_key').", + } + assert "typed-safety-key" not in response.text + assert not (tmp_path / "scorers").exists() + + +@pytest.mark.parametrize( + ("fields", "message"), + [ + ({}, "name is required when register=true"), + ({"name": "Leak-Substring"}, "Invalid registry name"), + ({"name": "leak", "register": False}, "persist requires register=true"), + ], +) +def test_create_scorer_checks_what_persist_needs( + compatibility_headers: dict[str, str], fields: dict[str, Any], message: str +) -> None: + client = TestClient(app, headers=compatibility_headers) + + response = client.post( + "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/api/scorers", json={"type": "SubStringScorer", "params": {"substring": "x"}, "persist": True, **fields} + ) + + assert response.status_code == 422 + assert message in json.dumps(response.json()) + + +@pytest.mark.parametrize( + ("error", "status_code"), + [ + (SavedEntryConflictError("A saved scorer named 'leak' already exists."), 409), + (SavedEntryStorageError("Saved scorers can't be written right now."), 503), + ], +) +def test_create_scorer_maps_save_errors( + compatibility_headers: dict[str, str], error: Exception, status_code: int +) -> None: + client = TestClient(app, headers=compatibility_headers) + owner = SavedEntryOwner(oid="user-oid", name="Ada") + with ( + patch("pyrit.backend.routes.scorers.get_scorer_service") as get_service, + patch("pyrit.backend.routes.scorers.saved_entry_owner_from_request", return_value=owner), + patch.object(client.app.state, "registry_recipes_source", "/srv/registry-recipes", create=True), + ): + get_service.return_value.create_scorer_async = AsyncMock(side_effect=error) + + response = client.post( + "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/api/scorers", + json={"name": "leak", "type": "SubStringScorer", "params": {"substring": "x"}, "persist": True}, + ) + + assert response.status_code == status_code + assert response.json()["detail"] == str(error) + kwargs = get_service.return_value.create_scorer_async.call_args.kwargs + assert (kwargs["owner"], kwargs["recipes_source"], kwargs["request"].persist) == ( + owner, + "/srv/registry-recipes", + True, + ) + + +def test_create_scorer_records_no_owner_when_not_saving(compatibility_headers: dict[str, str]) -> None: + client = TestClient(app, headers=compatibility_headers) + with ( + patch("pyrit.backend.routes.scorers.get_scorer_service") as get_service, + patch("pyrit.backend.routes.scorers.saved_entry_owner_from_request") as saved_entry_owner, + ): + get_service.return_value.create_scorer_async = AsyncMock(side_effect=ValueError("stop")) + + client.post("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/api/scorers", json={"name": "leak", "type": "SubStringScorer", "params": {"substring": "x"}}) + + assert get_service.return_value.create_scorer_async.call_args.kwargs["owner"] is None + saved_entry_owner.assert_not_called() diff --git a/tests/unit/backend/test_scorer_service.py b/tests/unit/backend/test_scorer_service.py index 7cd756178e..88d8e6a43d 100644 --- a/tests/unit/backend/test_scorer_service.py +++ b/tests/unit/backend/test_scorer_service.py @@ -4,17 +4,22 @@ """Tests for the scorer backend service.""" import asyncio +import json import threading from collections.abc import Callable, Iterator +from functools import partial from pathlib import Path +from typing import Any from unittest.mock import MagicMock, patch import pytest from pyrit.backend.models import CreateScorerRequest from pyrit.backend.services.chat_scoring_service import ChatScoringService +from pyrit.backend.services.saved_entry_restore import build_saved_entry_async from pyrit.backend.services.scorer_service import ScorerService, get_scorer_service from pyrit.backend.services.service_lifecycle import close_services_async +from pyrit.common import REQUIRED_VALUE, apply_defaults, reset_default_values, set_default_value from pyrit.models import ( ComponentIdentifier, Scorable, @@ -24,9 +29,29 @@ ScoringExpectation, TargetIdentifier, ) +from pyrit.models.catalog import ( + ComponentRecipe, + RegistryEntryOrigin, + RegistryRecipeKind, + RegistryRestoreReport, + SavedEntryOwner, +) from pyrit.models.component_spec import RegisteredComponentReference from pyrit.prompt_target import TextTarget -from pyrit.registry import DefaultInstanceRegistry, ScorerRegistry, TargetRegistry +from pyrit.registry import ( + DefaultInstanceRegistry, + NotSaveableError, + SavedEntryConflictError, + SavedEntryStorageError, + ScorerRegistry, + TargetRegistry, +) +from pyrit.registry.instance_registry import ( + SAVED_ENTRY_METADATA_KEY, + registration_origin, +) +from pyrit.registry.registry_recipe_restore import RegistryRecipeRestorer +from pyrit.registry.registry_recipe_storage import RegistryRecipeStorage from pyrit.score import ( ManualScorer, MessageToolCallScorer, @@ -35,7 +60,10 @@ OtelToolCallScorer, Scorer, SubStringScorer, + TrueFalseCompositeScorer, TrueFalseInverterScorer, + TrueFalseScoreAggregator, + TrueFalseScorer, ) @@ -487,3 +515,289 @@ async def test_decision_scorer_unknown_parameter_does_not_list_its_question_path assert "'chat_target'" in str(error.value) assert "decision_question_path" not in str(error.value) + + +async def _restore(source: Path) -> RegistryRestoreReport: + """Restore the saved scorers through the API's create, as startup does.""" + get_scorer_service.cache_clear() + build_async = partial(build_saved_entry_async, upload_directory=None) + return await RegistryRecipeRestorer(source=str(source)).restore_async(build_async=build_async) + + +def _persist_scorer(name: str, scorer_type: str, params: dict[str, Any]) -> CreateScorerRequest: + return CreateScorerRequest(name=name, type=scorer_type, params=params, persist=True) + + +def _saved_scorer(source: Path, name: str) -> dict[str, Any]: + return json.loads((source / "scorers" / f"{name}.json").read_text()) + + +_LEAK = {"substring": "secret", "categories": ["leak"]} + + +async def test_saves_a_scorer_that_restore_rebuilds(tmp_path: Path) -> None: + service = ScorerService() + owner = SavedEntryOwner(oid="00000000-0000-0000-0000-000000000001", name="Ada") + + scorer = await service.create_scorer_async( + request=_persist_scorer("leak_substring", "SubStringScorer", _LEAK), owner=owner, recipes_source=str(tmp_path) + ) + + assert scorer.origin is RegistryEntryOrigin.SAVED + assert _saved_scorer(tmp_path, "leak_substring") == { + "schema_version": 1, + "class_module": "pyrit.score.true_false.substring_scorer", + "class_name": "SubStringScorer", + "params": {"substring": "secret", "categories": ["leak"]}, + "owner": {"oid": owner.oid, "name": "Ada"}, + } + entry = ScorerRegistry.get_registry_singleton().instances.get_entry("leak_substring") + assert entry is not None + assert entry.metadata == {SAVED_ENTRY_METADATA_KEY: "scorers"} + saved_hash = entry.instance.get_identifier().hash + ScorerRegistry.reset_registry_singleton() + assert (await _restore(tmp_path)).failures == [] + restored = ScorerRegistry.get_registry_singleton().instances.get("leak_substring") + assert restored is not None + assert restored.get_identifier().hash == saved_hash + + +async def test_saves_a_scorer_only_over_a_target_that_comes_back_after_a_restart( + chat_target: str, tmp_path: Path +) -> None: + service = ScorerService() + request = _persist_scorer("decision", "DecisionScorer", {"chat_target": chat_target}) + + with pytest.raises(NotSaveableError) as refusal: + await service.create_scorer_async(request=request, recipes_source=str(tmp_path)) + # The startup scripts register the same target again. + with registration_origin(RegistryEntryOrigin.CONFIGURATION): + TargetRegistry.get_registry_singleton().instances.register(TextTarget(), name=chat_target, replace=True) + saved = await service.create_scorer_async(request=request, recipes_source=str(tmp_path)) + + assert str(refusal.value) == ( + "Uses temporary target 'chat', which won't exist after a restart. It can still be created without saving it." + ) + assert saved.origin is RegistryEntryOrigin.SAVED + assert _saved_scorer(tmp_path, "decision")["params"] == {"chat_target": "chat"} + + +async def test_saves_a_scorer_that_uses_this_servers_key(tmp_path: Path) -> None: + service = ScorerService() + endpoint = "https://contoso.cognitiveservices.azure.com/" + + with patch.dict("os.environ", {"AZURE_CONTENT_SAFETY_API_KEY": "server-safety-key"}): + scorer = await service.create_scorer_async( + request=_persist_scorer("content_safety", "AzureContentFilterScorer", {"endpoint": endpoint}), + recipes_source=str(tmp_path), + ) + ScorerRegistry.reset_registry_singleton() + report = await _restore(tmp_path) + + assert scorer.origin is RegistryEntryOrigin.SAVED + assert _saved_scorer(tmp_path, "content_safety")["params"] == {"endpoint": endpoint} + assert "server-safety-key" not in (tmp_path / "scorers" / "content_safety.json").read_text() + assert report.failures == [] + assert ScorerRegistry.get_registry_singleton().instances.get("content_safety") is not None + + +async def test_a_taken_scorer_name_is_a_conflict_only_when_saving(tmp_path: Path) -> None: + service = ScorerService() + await service.create_scorer_async(request=CreateScorerRequest(name="leak", type="SubStringScorer", params=_LEAK)) + + with pytest.raises(SavedEntryConflictError, match="already"): + await service.create_scorer_async( + request=_persist_scorer("leak", "SubStringScorer", _LEAK), recipes_source=str(tmp_path) + ) + + assert not (tmp_path / "scorers").exists() + + +async def test_a_saved_scorer_file_with_the_name_is_a_conflict_that_leaves_the_file(tmp_path: Path) -> None: + storage = RegistryRecipeStorage(kind=RegistryRecipeKind.SCORERS, source=str(tmp_path)) + storage.create_recipe(name="leak", recipe=ComponentRecipe(class_module="m", class_name="X")) + before = (tmp_path / "scorers" / "leak.json").read_bytes() + + with pytest.raises(SavedEntryConflictError, match="A saved scorer named 'leak' already exists."): + await ScorerService().create_scorer_async( + request=_persist_scorer("leak", "SubStringScorer", _LEAK), recipes_source=str(tmp_path) + ) + + assert ScorerRegistry.get_registry_singleton().instances.get("leak") is None + assert (tmp_path / "scorers" / "leak.json").read_bytes() == before + + +async def test_reports_scorer_storage_failures_as_unavailable(tmp_path: Path) -> None: + with ( + patch.object(RegistryRecipeStorage, "_save_local_conditional", side_effect=OSError("disk full")), + pytest.raises(SavedEntryStorageError, match="Saved scorers can't be written right now."), + ): + await ScorerService().create_scorer_async( + request=_persist_scorer("leak", "SubStringScorer", _LEAK), recipes_source=str(tmp_path) + ) + + assert ScorerRegistry.get_registry_singleton().instances.get("leak") is None + + +async def test_deletes_the_saved_file_when_the_scorer_cant_be_registered(tmp_path: Path) -> None: + registry = ScorerRegistry.get_registry_singleton() + + with ( + patch.object(registry.instances, "register", side_effect=RuntimeError("x")), + pytest.raises(RuntimeError, match="x"), + ): + await ScorerService().create_scorer_async( + request=_persist_scorer("leak", "SubStringScorer", _LEAK), recipes_source=str(tmp_path) + ) + + assert not (tmp_path / "scorers" / "leak.json").exists() + + +async def test_list_get_and_create_tell_where_each_scorer_comes_from(tmp_path: Path) -> None: + service = ScorerService() + instances = ScorerRegistry.get_registry_singleton().instances + with registration_origin(RegistryEntryOrigin.CONFIGURATION): + instances.register(SubStringScorer(substring="startup"), name="a_startup") + saved = await service.create_scorer_async( + request=_persist_scorer("b_saved", "SubStringScorer", _LEAK), recipes_source=str(tmp_path) + ) + temporary = await service.create_scorer_async( + request=CreateScorerRequest(name="c_temporary", type="SubStringScorer", params=_LEAK) + ) + + first_page = await service.list_scorers_async(limit=2) + second_page = await service.list_scorers_async(limit=2, cursor=first_page.pagination.next_cursor) + fetched = [ + await service.get_scorer_async(scorer_registry_name=name) for name in ("a_startup", "b_saved", "c_temporary") + ] + + expected = { + "a_startup": RegistryEntryOrigin.CONFIGURATION, + "b_saved": RegistryEntryOrigin.SAVED, + "c_temporary": RegistryEntryOrigin.TEMPORARY, + } + listed = [*first_page.items, *second_page.items] + assert {item.scorer_registry_name: item.origin for item in listed} == expected + assert {item.scorer_registry_name: item.origin for item in fetched if item is not None} == expected + assert (saved.origin, temporary.origin) == (RegistryEntryOrigin.SAVED, RegistryEntryOrigin.TEMPORARY) + + +async def test_a_reserved_scorer_name_is_refused_as_invalid_not_as_taken(tmp_path: Path) -> None: + service = ScorerService() + + with pytest.raises(ValueError, match="reserved") as saved: + await service.create_scorer_async( + request=_persist_scorer("types", "SubStringScorer", _LEAK), recipes_source=str(tmp_path) + ) + with pytest.raises(ValueError, match="reserved"): + await service.create_scorer_async( + request=CreateScorerRequest(name="types", type="SubStringScorer", params=_LEAK) + ) + + assert not isinstance(saved.value, (SavedEntryConflictError, NotSaveableError)) + assert not (tmp_path / "scorers").exists() + + +async def test_saving_an_unknown_scorer_type_is_an_invalid_request(tmp_path: Path) -> None: + with pytest.raises(ValueError, match="Scorer type 'NoSuchScorer' not found") as refusal: + await ScorerService().create_scorer_async( + request=_persist_scorer("missing", "NoSuchScorer", {}), recipes_source=str(tmp_path) + ) + + assert not isinstance(refusal.value, NotSaveableError) + + +async def test_a_scorer_save_finds_and_builds_the_scorer_off_the_event_loop(tmp_path: Path) -> None: + registry = ScorerRegistry.get_registry_singleton() + loop_thread = threading.current_thread() + threads: list[str] = [] + contains, find, build = ( + ScorerRegistry.__contains__, + registry.get_class, + registry.create_instance_from_external_input, + ) + + def contains_noting_thread(self: ScorerRegistry, name: str) -> bool: + threads.append("loop" if threading.current_thread() is loop_thread else "worker") + return contains(self, name) + + def find_noting_thread(*args: Any, **kwargs: Any) -> Any: + threads.append("loop" if threading.current_thread() is loop_thread else "worker") + return find(*args, **kwargs) + + def build_noting_thread(*args: Any, **kwargs: Any) -> Any: + threads.append("loop" if threading.current_thread() is loop_thread else "worker") + return build(*args, **kwargs) + + with ( + patch.object(ScorerRegistry, "__contains__", contains_noting_thread), + patch.object(registry, "get_class", side_effect=find_noting_thread), + patch.object(registry, "create_instance_from_external_input", side_effect=build_noting_thread), + ): + await ScorerService().create_scorer_async( + request=_persist_scorer("leak", "SubStringScorer", _LEAK), recipes_source=str(tmp_path) + ) + + assert len(threads) >= 3 + assert set(threads) == {"worker"} + + +def _register_default_composite_scorer(default: list[Any] | tuple[Any, ...]) -> None: + """Register a composite scorer class whose scorers come from a configured default.""" + + class DefaultCompositeScorer(TrueFalseCompositeScorer): + @apply_defaults + def __init__(self, *, scorers: list[TrueFalseScorer] = REQUIRED_VALUE) -> None: + super().__init__(aggregator=TrueFalseScoreAggregator.AND, scorers=scorers) + + ScorerRegistry.get_registry_singleton().register_class(DefaultCompositeScorer) + set_default_value(class_type=DefaultCompositeScorer, parameter_name="scorers", value=default) + + +@pytest.fixture +def startup_and_launch_scorers() -> Iterator[tuple[SubStringScorer, SubStringScorer, SubStringScorer]]: + scorers = ScorerRegistry.get_registry_singleton().instances + startup, other_startup = SubStringScorer(substring="startup"), SubStringScorer(substring="other") + launch = SubStringScorer(substring="launch") + with registration_origin(RegistryEntryOrigin.CONFIGURATION): + scorers.register(startup, name="startup_substring") + scorers.register(other_startup, name="other_startup_substring") + scorers.register(launch, name="launch_substring") + yield startup, other_startup, launch + reset_default_values() + + +@pytest.mark.parametrize("container", [list, tuple]) +async def test_a_saved_scorer_names_each_scorer_in_a_default_list( + tmp_path: Path, + startup_and_launch_scorers: tuple[SubStringScorer, SubStringScorer, SubStringScorer], + container: Callable[[list[Any]], list[Any] | tuple[Any, ...]], +) -> None: + startup, other_startup, _ = startup_and_launch_scorers + _register_default_composite_scorer(default=container([startup, other_startup, startup])) + + await ScorerService().create_scorer_async( + request=_persist_scorer("composite", "DefaultCompositeScorer", {}), recipes_source=str(tmp_path) + ) + + assert _saved_scorer(tmp_path, "composite")["params"] == { + "scorers": ["startup_substring", "other_startup_substring", "startup_substring"] + } + + +async def test_a_default_list_with_a_temporary_scorer_is_not_saved( + tmp_path: Path, startup_and_launch_scorers: tuple[SubStringScorer, SubStringScorer, SubStringScorer] +) -> None: + startup, _, launch = startup_and_launch_scorers + _register_default_composite_scorer(default=[startup, launch]) + + with pytest.raises(NotSaveableError) as refusal: + await ScorerService().create_scorer_async( + request=_persist_scorer("composite", "DefaultCompositeScorer", {}), recipes_source=str(tmp_path) + ) + + assert str(refusal.value) == ( + "Uses temporary scorer 'launch_substring', which won't exist after a restart. " + "It can still be created without saving it." + ) + assert not (tmp_path / "scorers").exists() diff --git a/tests/unit/backend/test_technique_edit_service.py b/tests/unit/backend/test_technique_edit_service.py index 0cb203eb2e..b00175a96e 100644 --- a/tests/unit/backend/test_technique_edit_service.py +++ b/tests/unit/backend/test_technique_edit_service.py @@ -239,7 +239,7 @@ async def test_creation_and_editing_share_strict_input_and_attack_validation_asy params={"max_attempts_on_failure": value}, ) if type(value) is int and value >= 0: - created = await TechniqueService().create_async(request) + created = await TechniqueService().create_async(request=request) admitted = TechniqueEditService.validate(specification) copied = TechniqueEditService.resolve(admitted.override) assert ( @@ -249,7 +249,7 @@ async def test_creation_and_editing_share_strict_input_and_attack_validation_asy else: revision = edit_catalog.catalog_revision with pytest.raises(ValueError): - await TechniqueService().create_async(request) + await TechniqueService().create_async(request=request) with pytest.raises(ValueError): TechniqueEditService.validate(specification) assert edit_catalog.catalog_revision == revision @@ -764,7 +764,7 @@ async def test_gui_created_technique_converts_both_history_roles_but_not_system_ edit_catalog: AttackTechniqueRegistry, ) -> None: created = await TechniqueService().create_async( - CreateTechniqueRequest(name="gui_replay", type="PromptSendingAttack", request_converters=["base64"]) + request=CreateTechniqueRequest(name="gui_replay", type="PromptSendingAttack", request_converters=["base64"]) ) factory = edit_catalog.instances.get(created.name) assert factory is not None @@ -838,7 +838,7 @@ async def test_gui_creation_without_request_converters_keeps_default_history_pol edit_catalog: AttackTechniqueRegistry, request_converters: list[str] | None ) -> None: created = await TechniqueService().create_async( - CreateTechniqueRequest( + request=CreateTechniqueRequest( name="without_requests", type="PromptSendingAttack", request_converters=request_converters, diff --git a/tests/unit/backend/test_technique_service.py b/tests/unit/backend/test_technique_service.py index c44391c7ae..83f8e8c3b4 100644 --- a/tests/unit/backend/test_technique_service.py +++ b/tests/unit/backend/test_technique_service.py @@ -5,22 +5,28 @@ import ast import asyncio +import json import threading from collections.abc import AsyncIterator, Iterator, Mapping from concurrent.futures import ThreadPoolExecutor from enum import Enum +from functools import partial +from pathlib import Path from typing import Any from unittest.mock import AsyncMock, patch import pytest from fastapi.testclient import TestClient +from pydantic import ValidationError from pyrit.backend.main import app from pyrit.backend.mappers.technique_mappers import technique_to_instance from pyrit.backend.models.techniques import CreateTechniqueRequest from pyrit.backend.services import ScenarioRunService, ScenarioService +from pyrit.backend.services.saved_entry_restore import build_saved_entry_async from pyrit.backend.services.service_lifecycle import close_services_async from pyrit.backend.services.technique_service import TechniqueService, get_technique_service +from pyrit.converter import Base64Converter, ROT13Converter from pyrit.executor.attack import PromptSendingAttack from pyrit.models import ( AttackSeedGroup, @@ -30,9 +36,32 @@ SeedPrompt, SeedSimulatedConversation, ) -from pyrit.models.catalog import RunScenarioRequest -from pyrit.prompt_target import OpenAIChatTarget -from pyrit.registry import AttackRegistry, AttackTechniqueRegistry, Registry, ScenarioRegistry, TargetRegistry +from pyrit.models.catalog import ( + RegistryEntryOrigin, + RegistryRecipeKind, + RunScenarioRequest, + SavedEntryOwner, + TechniqueRecipe, +) +from pyrit.prompt_target import OpenAIChatTarget, PromptTarget +from pyrit.registry import ( + AttackRegistry, + AttackTechniqueRegistry, + ConverterRegistry, + NotSaveableError, + Registry, + SavedEntryConflictError, + SavedEntryStorageError, + ScenarioRegistry, + TargetRegistry, +) +from pyrit.registry.components.attack_technique_registry import TechniqueSelectorConflictError +from pyrit.registry.instance_registry import ( + SAVED_ENTRY_METADATA_KEY, + registration_origin, +) +from pyrit.registry.registry_recipe_restore import RegistryRecipeRestorer +from pyrit.registry.registry_recipe_storage import RegistryRecipeStorage from pyrit.scenario import DatasetAttackConfiguration, Scenario, ScenarioTechnique from pyrit.scenario.core import AttackTechniqueFactory from pyrit.scenario.scenarios import airt @@ -76,7 +105,9 @@ def registry(patch_central_database: Any) -> Iterator[AttackTechniqueRegistry]: get_technique_service.cache_clear() with patch.dict(Registry._singletons, {}, clear=True): registry = AttackTechniqueRegistry.get_registry_singleton() - registry.register_from_factories(build_technique_factories()) + # The startup scripts register these, so they come back after a restart. + with registration_origin(RegistryEntryOrigin.CONFIGURATION): + registry.register_from_factories(build_technique_factories()) yield registry get_technique_service.cache_clear() @@ -97,6 +128,7 @@ async def test_catalog_real_factories_and_alias_metadata_async(registry: AttackT "uses_default_adversarial_target", "identifier", "creation_statement", + "origin", } assert await service.get_async("missing") is None AttackRegistry.get_registry_singleton().register_class(PromptSendingAttack, name="alias") @@ -110,7 +142,7 @@ async def test_catalog_real_factories_and_alias_metadata_async(registry: AttackT for parameter in entry.parameters ) assert metadata.model_dump_json() - created = await service.create_async(CreateTechniqueRequest(name="from_alias", type="alias")) + created = await service.create_async(request=CreateTechniqueRequest(name="from_alias", type="alias")) assert created.attack_type == "PromptSendingAttack" @@ -559,7 +591,9 @@ async def register_then_initialize_async( init_kwargs: dict[str, Any], initial_metadata: Mapping[str, Any] | None = None, ) -> Scenario: - await TechniqueService().create_async(CreateTechniqueRequest(name="during_launch", type="PromptSendingAttack")) + await TechniqueService().create_async( + request=CreateTechniqueRequest(name="during_launch", type="PromptSendingAttack") + ) return await initialize(request=request, init_kwargs=init_kwargs, initial_metadata=initial_metadata) try: @@ -621,7 +655,7 @@ async def test_rest_attack_constraints_reject_without_constructing_or_mutating_a with patch.object(attack_class, "__init__", autospec=True, side_effect=AssertionError("Must stay deferred")): with pytest.raises(ValueError): await TechniqueService().create_async( - CreateTechniqueRequest(name="bad_bounds", type=attack_type, params=params) + request=CreateTechniqueRequest(name="bad_bounds", type=attack_type, params=params) ) assert registry.catalog_revision == revision assert registry.instances.get("bad_bounds") is None @@ -632,13 +666,15 @@ async def test_rest_create_and_initialize_numeric_boundary_async(registry: Attac revision = registry.catalog_revision with pytest.raises(ValueError, match="non-negative"): await service.create_async( - CreateTechniqueRequest( + request=CreateTechniqueRequest( name="bad_attempts", type="PromptSendingAttack", params={"max_attempts_on_failure": -1} ) ) assert registry.catalog_revision == revision await service.create_async( - CreateTechniqueRequest(name="zero_attempts", type="PromptSendingAttack", params={"max_attempts_on_failure": 0}) + request=CreateTechniqueRequest( + name="zero_attempts", type="PromptSendingAttack", params={"max_attempts_on_failure": 0} + ) ) scorer = SubStringScorer(substring="yes") target = MockPromptTarget() @@ -710,7 +746,7 @@ async def test_warm_catalog_estimates_and_summaries_refresh_without_changing_sna scenario_name="airt.rapid_response", request=request ) await TechniqueService().create_async( - CreateTechniqueRequest(name="runtime_new", type="PromptSendingAttack", tags=["user_group"]) + request=CreateTechniqueRequest(name="runtime_new", type="PromptSendingAttack", tags=["user_group"]) ) after_metadata = scenario_registry.get_registered_class_metadata("airt.rapid_response") assert after_metadata is not None @@ -849,7 +885,7 @@ async def test_rest_parameter_checks_do_not_change_registry_async( before = registry.catalog_revision with pytest.raises(ValueError): await TechniqueService().create_async( - CreateTechniqueRequest(name="invalid", type="PromptSendingAttack", params=params) + request=CreateTechniqueRequest(name="invalid", type="PromptSendingAttack", params=params) ) assert registry.catalog_revision == before assert registry.instances.get("invalid") is None @@ -882,3 +918,369 @@ def test_request_rejects_invalid_selectors_and_removed_inputs( with pytest.raises(ValidationError): CreateTechniqueRequest.model_validate({"name": "new", "type": "PromptSendingAttack", **extra}) assert registry.catalog_revision == before + + +def test_request_refuses_to_save_a_private_technique() -> None: + with pytest.raises(ValidationError, match="A private technique can't be saved"): + CreateTechniqueRequest(name="mine", type="PromptSendingAttack", persist=True, private=True) + + +@pytest.fixture +def saving_catalog(registry: AttackTechniqueRegistry) -> AttackTechniqueRegistry: + """The startup techniques, with startup and Temporary converters and targets for saved techniques to use.""" + converters = ConverterRegistry.get_registry_singleton().instances + targets = TargetRegistry.get_registry_singleton().instances + with registration_origin(RegistryEntryOrigin.CONFIGURATION): + converters.register(Base64Converter(), name="base64") + targets.register(MockPromptTarget(), name="attacker") + converters.register(ROT13Converter(), name="rot13") + targets.register(MockPromptTarget(), name="temporary_attacker") + return registry + + +def _persist_technique(name: str, **fields: Any) -> CreateTechniqueRequest: + return CreateTechniqueRequest(name=name, type="PromptSendingAttack", persist=True, **fields) + + +def _saved_technique(source: Path, name: str) -> dict[str, Any]: + return json.loads((source / "techniques" / f"{name}.json").read_text()) + + +async def test_saves_a_technique_that_restore_rebuilds(saving_catalog: AttackTechniqueRegistry, tmp_path: Path) -> None: + owner = SavedEntryOwner(oid="00000000-0000-0000-0000-000000000001", name="Ada") + request = _persist_technique( + "base64_send", + description="Send the objective encoded.", + tags=["encoded"], + params={"max_attempts_on_failure": 2}, + request_converters=["base64"], + ) + + created = await TechniqueService().create_async(request=request, owner=owner, recipes_source=str(tmp_path)) + + assert created.origin is RegistryEntryOrigin.SAVED + assert _saved_technique(tmp_path, "base64_send") == { + "schema_version": 1, + "type": "PromptSendingAttack", + "params": {"max_attempts_on_failure": 2}, + "description": "Send the objective encoded.", + "tags": ["encoded"], + "request_converters": ["base64"], + "owner": {"oid": owner.oid, "name": "Ada"}, + } + entry = saving_catalog.instances.get_entry("base64_send") + assert entry is not None + assert entry.metadata == {SAVED_ENTRY_METADATA_KEY: "techniques"} + saved_hash = entry.instance.get_identifier().hash + + AttackTechniqueRegistry.reset_registry_singleton() + restarted = AttackTechniqueRegistry.get_registry_singleton() + with registration_origin(RegistryEntryOrigin.CONFIGURATION): + restarted.register_from_factories(build_technique_factories()) + get_technique_service.cache_clear() + build_async = partial(build_saved_entry_async, upload_directory=None) + report = await RegistryRecipeRestorer(source=str(tmp_path)).restore_async(build_async=build_async) + assert report.failures == [] + + restored = restarted.instances.get_entry("base64_send") + assert restored is not None + assert restored.metadata == {SAVED_ENTRY_METADATA_KEY: "techniques"} + assert restored.instance.get_identifier().hash == saved_hash + assert restored.instance.technique_tags == ["encoded"] + + +@pytest.mark.parametrize( + ("fields", "message"), + [ + ( + {"request_converters": ["base64", "rot13"]}, + ( + "Uses temporary converter 'rot13', which won't exist after a restart. It can still be created " + "without saving it." + ), + ), + ( + {"response_converters": ["rot13"]}, + ( + "Uses temporary converter 'rot13', which won't exist after a restart. It can still be created " + "without saving it." + ), + ), + ( + {"type": "RedTeamingAttack", "adversarial_chat": "temporary_attacker"}, + ( + "Uses temporary target 'temporary_attacker', which won't exist after a restart. It can still be " + "created without saving it." + ), + ), + ], +) +async def test_a_saved_technique_can_only_use_entries_that_come_back_after_a_restart( + saving_catalog: AttackTechniqueRegistry, tmp_path: Path, fields: dict[str, Any], message: str +) -> None: + request = CreateTechniqueRequest(name="uses_temporary", persist=True, **{"type": "PromptSendingAttack", **fields}) + + with pytest.raises(NotSaveableError) as refusal: + await TechniqueService().create_async(request=request, recipes_source=str(tmp_path)) + + assert str(refusal.value) == message + assert saving_catalog.instances.get("uses_temporary") is None + assert not (tmp_path / "techniques").exists() + + +async def test_saves_a_technique_whose_adversarial_target_comes_back_after_a_restart( + saving_catalog: AttackTechniqueRegistry, tmp_path: Path +) -> None: + request = CreateTechniqueRequest( + name="red_team", type="RedTeamingAttack", persist=True, adversarial_chat="attacker" + ) + + created = await TechniqueService().create_async(request=request, recipes_source=str(tmp_path)) + + assert created.origin is RegistryEntryOrigin.SAVED + assert _saved_technique(tmp_path, "red_team") == { + "schema_version": 1, + "type": "RedTeamingAttack", + "params": {}, + "tags": [], + "adversarial_chat": "attacker", + } + + +def test_a_saved_technique_needs_a_lowercase_name() -> None: + with pytest.raises(ValidationError, match="lowercase"): + _persist_technique("Base64Send") + + assert CreateTechniqueRequest(name="Base64Send", type="PromptSendingAttack").name == "Base64Send" + + +async def test_a_selector_clash_is_a_conflict_when_saving( + saving_catalog: AttackTechniqueRegistry, tmp_path: Path +) -> None: + startup_name = saving_catalog.instances.get_names()[0] + service = TechniqueService() + + for request in (_persist_technique(startup_name), _persist_technique("other_send", tags=[startup_name])): + with pytest.raises(SavedEntryConflictError): + await service.create_async(request=request, recipes_source=str(tmp_path)) + with pytest.raises(TechniqueSelectorConflictError): + await service.create_async(request=CreateTechniqueRequest(name=startup_name, type="PromptSendingAttack")) + + assert saving_catalog.instances.get("other_send") is None + assert not (tmp_path / "techniques").exists() + + +async def test_a_saved_technique_file_with_the_name_is_a_conflict_that_leaves_the_file( + saving_catalog: AttackTechniqueRegistry, tmp_path: Path +) -> None: + storage = RegistryRecipeStorage(kind=RegistryRecipeKind.TECHNIQUES, source=str(tmp_path)) + storage.create_recipe(name="base64_send", recipe=TechniqueRecipe(type="PromptSendingAttack")) + before = (tmp_path / "techniques" / "base64_send.json").read_bytes() + + with pytest.raises(SavedEntryConflictError, match="A saved technique named 'base64_send' already exists."): + await TechniqueService().create_async(request=_persist_technique("base64_send"), recipes_source=str(tmp_path)) + + assert saving_catalog.instances.get("base64_send") is None + assert (tmp_path / "techniques" / "base64_send.json").read_bytes() == before + + +async def test_reports_technique_storage_failures_as_unavailable( + saving_catalog: AttackTechniqueRegistry, tmp_path: Path +) -> None: + with ( + patch.object(RegistryRecipeStorage, "_save_local_conditional", side_effect=OSError("disk full")), + pytest.raises(SavedEntryStorageError, match="Saved techniques can't be written right now."), + ): + await TechniqueService().create_async(request=_persist_technique("base64_send"), recipes_source=str(tmp_path)) + + assert saving_catalog.instances.get("base64_send") is None + + +async def test_deletes_the_saved_file_when_another_technique_takes_the_name_first( + saving_catalog: AttackTechniqueRegistry, tmp_path: Path +) -> None: + register_runtime = saving_catalog.instances.register_runtime + + def register_another_first(factory: AttackTechniqueFactory, *, metadata: dict[str, Any] | None = None) -> None: + register_runtime(AttackTechniqueFactory(name="base64_send", attack_class=PromptSendingAttack)) + register_runtime(factory, metadata=metadata) + + with ( + patch.object(saving_catalog.instances, "register_runtime", side_effect=register_another_first), + pytest.raises(SavedEntryConflictError, match="already exists"), + ): + await TechniqueService().create_async(request=_persist_technique("base64_send"), recipes_source=str(tmp_path)) + + assert not (tmp_path / "techniques" / "base64_send.json").exists() + + +async def test_list_get_and_create_tell_where_each_technique_comes_from( + saving_catalog: AttackTechniqueRegistry, tmp_path: Path +) -> None: + service = TechniqueService() + startup_name = saving_catalog.instances.get_names()[0] + saved = await service.create_async(request=_persist_technique("saved_send"), recipes_source=str(tmp_path)) + temporary = await service.create_async( + request=CreateTechniqueRequest(name="temporary_send", type="PromptSendingAttack") + ) + + listed = {item.name: item.origin for item in (await service.list_async(limit=200)).items} + fetched = [await service.get_async(name) for name in (startup_name, "saved_send", "temporary_send")] + + assert (saved.origin, temporary.origin) == (RegistryEntryOrigin.SAVED, RegistryEntryOrigin.TEMPORARY) + assert {name: listed[name] for name in (startup_name, "saved_send", "temporary_send")} == { + startup_name: RegistryEntryOrigin.CONFIGURATION, + "saved_send": RegistryEntryOrigin.SAVED, + "temporary_send": RegistryEntryOrigin.TEMPORARY, + } + assert [item.origin for item in fetched if item] == [ + RegistryEntryOrigin.CONFIGURATION, + RegistryEntryOrigin.SAVED, + RegistryEntryOrigin.TEMPORARY, + ] + + +def test_rest_create_with_persist_saves_or_explains_why_it_cant( + saving_catalog: AttackTechniqueRegistry, compatibility_headers: dict[str, str], tmp_path: Path +) -> None: + client = TestClient(app, headers=compatibility_headers) + startup_name = saving_catalog.instances.get_names()[0] + body = {"name": "base64_send", "type": "PromptSendingAttack", "persist": True, "request_converters": ["base64"]} + + with patch.object(client.app.state, "registry_recipes_source", str(tmp_path), create=True): + created = client.post("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/api/techniques", json=body) + refused = client.post("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/api/techniques", json={**body, "name": "rot13_send", "request_converters": ["rot13"]}) + clashing = client.post("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/api/techniques", json={**body, "name": startup_name}) + invalid = client.post("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/api/techniques", json={**body, "name": "Base64Send"}) + listed = client.get("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/api/techniques", params={"limit": 200}) + + assert created.status_code == 201, created.text + assert created.json()["origin"] == "saved" + assert {item["name"]: item["origin"] for item in listed.json()["items"]}["base64_send"] == "saved" + assert _saved_technique(tmp_path, "base64_send")["request_converters"] == ["base64"] + assert refused.status_code == 400 + assert refused.json() == { + "type": "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/errors/not-saveable", + "title": "Can't be saved", + "status": 400, + "detail": ( + "Uses temporary converter 'rot13', which won't exist after a restart. It can still be created without " + "saving it." + ), + "instance": "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/api/techniques", + "not_saveable_reason": "Uses temporary converter 'rot13', which won't exist after a restart.", + } + assert clashing.status_code == 409 + assert invalid.status_code == 422 + assert sorted(path.name for path in (tmp_path / "techniques").glob("*.json")) == ["base64_send.json"] + + +@pytest.mark.parametrize( + ("error", "status_code"), + [ + (SavedEntryConflictError("A saved technique named 'base64_send' already exists."), 409), + (SavedEntryStorageError("Saved techniques can't be written right now."), 503), + ], +) +def test_rest_create_passes_the_owner_and_maps_save_errors( + compatibility_headers: dict[str, str], error: Exception, status_code: int +) -> None: + client = TestClient(app, headers=compatibility_headers) + owner = SavedEntryOwner(oid="user-oid", name="Ada") + with ( + patch("pyrit.backend.routes.techniques.get_technique_service") as get_service, + patch("pyrit.backend.routes.techniques.saved_entry_owner_from_request", return_value=owner), + patch.object(client.app.state, "registry_recipes_source", "/srv/registry-recipes", create=True), + ): + get_service.return_value.create_async = AsyncMock(side_effect=error) + + response = client.post( + "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/api/techniques", json={"name": "base64_send", "type": "PromptSendingAttack", "persist": True} + ) + + assert response.status_code == status_code + assert response.json()["detail"] == str(error) + kwargs = get_service.return_value.create_async.call_args.kwargs + assert (kwargs["owner"], kwargs["recipes_source"], kwargs["request"].persist) == ( + owner, + "/srv/registry-recipes", + True, + ) + + +def test_rest_create_records_no_owner_when_not_saving(compatibility_headers: dict[str, str]) -> None: + client = TestClient(app, headers=compatibility_headers) + with ( + patch("pyrit.backend.routes.techniques.get_technique_service") as get_service, + patch("pyrit.backend.routes.techniques.saved_entry_owner_from_request") as saved_entry_owner, + ): + get_service.return_value.create_async = AsyncMock(side_effect=ValueError("stop")) + + client.post("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/api/techniques", json={"name": "base64_send", "type": "PromptSendingAttack"}) + + assert get_service.return_value.create_async.call_args.kwargs["owner"] is None + saved_entry_owner.assert_not_called() + + +class _LaunchScriptAttack(PromptSendingAttack): + """An attack class that only a scan's launch script registers.""" + + +async def test_refuses_to_save_a_technique_whose_attack_type_a_launch_script_added( + saving_catalog: AttackTechniqueRegistry, tmp_path: Path +) -> None: + with registration_origin(RegistryEntryOrigin.TEMPORARY): + AttackRegistry.get_registry_singleton().register_class(_LaunchScriptAttack, name="launch_attack") + request = CreateTechniqueRequest(name="launch_send", type="launch_attack", persist=True) + + with pytest.raises(NotSaveableError) as refusal: + await TechniqueService().create_async(request=request, recipes_source=str(tmp_path)) + await TechniqueService().create_async(request=request.model_copy(update={"persist": False})) + + assert str(refusal.value) == ( + "'launch_attack' was added by a scan's launch script, so a saved entry of it couldn't be restored after a " + "restart. It can still be created without saving it." + ) + assert not (tmp_path / "techniques").exists() + assert saving_catalog.instances.get("launch_send") is not None + + +class _ServerFileAttack(PromptSendingAttack): + """An attack class that a saved technique can't rebuild.""" + + not_saveable_reason = "It reads a file only this server has." + + +class _KeyedAttack(PromptSendingAttack): + """An attack class that takes a key.""" + + def __init__(self, *, objective_target: PromptTarget, api_key: str | None = None) -> None: + super().__init__(objective_target=objective_target) + self.api_key = api_key + + +@pytest.mark.parametrize( + ("attack_class", "type_name", "params", "message"), + [ + (_ServerFileAttack, "server_file_attack", {}, "It reads a file only this server has. "), + (_KeyedAttack, "keyed_attack", {"api_key": "secret"}, "Saved entries can't hold credentials ('api_key')."), + ], +) +async def test_refuses_to_save_a_technique_that_restore_would_refuse( + saving_catalog: AttackTechniqueRegistry, + tmp_path: Path, + attack_class: type[PromptSendingAttack], + type_name: str, + params: dict[str, Any], + message: str, +) -> None: + AttackRegistry.get_registry_singleton().register_class(attack_class, name=type_name) + request = CreateTechniqueRequest(name="checked_send", type=type_name, params=params, persist=True) + + with pytest.raises(NotSaveableError) as refusal: + await TechniqueService().create_async(request=request, recipes_source=str(tmp_path)) + + assert str(refusal.value).startswith(message) + assert str(refusal.value).endswith("It can still be created without saving it.") + assert not (tmp_path / "techniques").exists() + assert saving_catalog.instances.get("checked_send") is None diff --git a/tests/unit/registry/test_attack_technique_registry.py b/tests/unit/registry/test_attack_technique_registry.py index 5821e7beea..e48eb95d41 100644 --- a/tests/unit/registry/test_attack_technique_registry.py +++ b/tests/unit/registry/test_attack_technique_registry.py @@ -5,6 +5,7 @@ import inspect from collections.abc import Iterator +from typing import Any from unittest.mock import MagicMock, patch import pytest @@ -388,6 +389,38 @@ def test_register_runtime_records_a_caught_clash_with_a_saved_technique(self): assert refusals == [("techniques", "formal")] assert self.registry.instances.get("formal") is saved + @pytest.mark.parametrize( + ("clash", "message"), + [ + ({"name": "custom"}, "conflicts with an aggregate tag"), + ({"name": "other", "technique_tags": ["formal"]}, "conflicts with a technique name"), + ({"name": "other", "technique_tags": ["Custom"]}, "conflicts with tag 'custom'"), + ], + ) + def test_register_runtime_records_a_caught_tag_clash_with_a_saved_technique( + self, clash: dict[str, Any], message: str + ) -> None: + saved = AttackTechniqueFactory(name="formal", attack_class=_StubAttack, technique_tags=["custom"]) + self.registry.instances.register_runtime(saved, metadata={SAVED_ENTRY_METADATA_KEY: "techniques"}) + + with record_saved_entry_refusals() as refusals: + with pytest.raises(ValueError, match=message): + self.registry.instances.register_runtime(AttackTechniqueFactory(attack_class=_StubAttack, **clash)) + + assert refusals == [("techniques", "formal")] + + def test_register_runtime_records_no_tag_clash_with_a_startup_technique(self) -> None: + startup = AttackTechniqueFactory(name="formal", attack_class=_StubAttack, technique_tags=["custom"]) + self.registry.instances.register_runtime(startup) + + with record_saved_entry_refusals() as refusals: + with pytest.raises(ValueError, match="conflicts with an aggregate tag"): + self.registry.instances.register_runtime( + AttackTechniqueFactory(name="custom", attack_class=_StubAttack) + ) + + assert refusals == [] + def test_register_from_factories_still_skips_an_existing_startup_technique(self): startup = AttackTechniqueFactory(name="startup", attack_class=_StubAttack) self.registry.register_from_factories([startup]) diff --git a/tests/unit/registry/test_instance_registry.py b/tests/unit/registry/test_instance_registry.py index 94a60cede2..84ddc305c6 100644 --- a/tests/unit/registry/test_instance_registry.py +++ b/tests/unit/registry/test_instance_registry.py @@ -317,6 +317,22 @@ def blocked_metadata(item: _TestItem) -> ComponentIdentifier: assert registry.list_metadata() is metadata +@pytest.mark.parametrize( + ("metadata", "origin"), + [ + ({SAVED_ENTRY_METADATA_KEY: "targets"}, RegistryEntryOrigin.SAVED), + ({SAVED_ENTRY_METADATA_KEY: "converters", CONFIGURATION_ENTRY_METADATA_KEY: True}, RegistryEntryOrigin.SAVED), + ({CONFIGURATION_ENTRY_METADATA_KEY: True}, RegistryEntryOrigin.CONFIGURATION), + ({}, RegistryEntryOrigin.TEMPORARY), + ({"supports_tool_calls": True}, RegistryEntryOrigin.TEMPORARY), + ], +) +def test_registry_entry_origin_tells_where_a_registered_entry_comes_from( + metadata: dict[str, object], origin: RegistryEntryOrigin +) -> None: + assert registry_entry_origin(metadata) is origin + + class TestInstanceTypeEnforcement: """Tests for the optional ``instance_type`` registration constraint.""" diff --git a/tests/unit/registry/test_registry_recipe_restore.py b/tests/unit/registry/test_registry_recipe_restore.py index dfe8cacbeb..ec19b529ed 100644 --- a/tests/unit/registry/test_registry_recipe_restore.py +++ b/tests/unit/registry/test_registry_recipe_restore.py @@ -113,7 +113,7 @@ async def _build_async(stored: StoredRecipe) -> None: recipe = stored.recipe if isinstance(recipe, TechniqueRecipe): techniques = AttackTechniqueRegistry.get_registry_singleton() - args = recipe.model_dump(exclude_unset=True, exclude={"schema_version", "type", "tags"}) + args = recipe.model_dump(exclude_unset=True, exclude={"schema_version", "type", "tags", "owner"}) factory = techniques.create_factory( name=stored.ref.name, attack_type=recipe.type, technique_tags=recipe.tags, strict_json=True, **args ) @@ -293,9 +293,9 @@ async def test_orders_entries_of_the_same_kind(self, tmp_path: Path) -> None: assert isinstance(TargetRegistry.get_registry_singleton().instances.get("a_pool"), RoundRobinTarget) def test_technique_recipe_matches_the_create_request(self) -> None: - recipe_fields = set(TechniqueRecipe.model_fields) - {"schema_version"} + recipe_fields = set(TechniqueRecipe.model_fields) - {"schema_version", "owner"} # A saved technique is never private: it has no creator. - request_fields = set(CreateTechniqueRequest.model_fields) - {"name", "private"} + request_fields = set(CreateTechniqueRequest.model_fields) - {"name", "persist", "private"} request = CreateTechniqueRequest.model_validate({"name": "formal_red_team", **_TECHNIQUE}) recipe = TechniqueRecipe.model_validate(_TECHNIQUE) @@ -308,7 +308,9 @@ def test_technique_recipe_defaults_match_the_create_request(self) -> None: recipe = TechniqueRecipe.model_validate({"type": "RedTeamingAttack"}) request = CreateTechniqueRequest.model_validate({"name": "formal_red_team", "type": "RedTeamingAttack"}) - assert recipe.model_dump(exclude={"schema_version"}) == request.model_dump(exclude={"name", "private"}) + assert recipe.model_dump(exclude={"schema_version", "owner"}) == request.model_dump( + exclude={"name", "persist", "private"} + ) @pytest.mark.parametrize( "changes", diff --git a/tests/unit/registry/test_registry_recipe_save.py b/tests/unit/registry/test_registry_recipe_save.py index b4a5183cab..f8c7d3ef42 100644 --- a/tests/unit/registry/test_registry_recipe_save.py +++ b/tests/unit/registry/test_registry_recipe_save.py @@ -13,31 +13,58 @@ import pytest from azure.core.exceptions import AzureError +from pyrit.converter import Base64Converter +from pyrit.models import ComponentType, Parameter, RegistryReference from pyrit.models.catalog import ComponentRecipe, RegistryEntryOrigin, RegistryRecipeKind from pyrit.prompt_target import OpenAIChatTarget, RoundRobinTarget, TextTarget from pyrit.registry import ( + ConverterRegistry, NotSaveableError, SavedEntryConflictError, SavedEntryStorageError, + ScorerRegistry, TargetRegistry, get_class_saveability, prepare_saved_params_async, + refuse_temporary_references, save_then_register_async, ) from pyrit.registry.instance_registry import RegistryNameTakenError, registration_origin, registry_entry_origin from pyrit.registry.registry_recipe_storage import RegistryRecipeStorage +from pyrit.score import SubStringScorer from unit.async_utils import TEST_WATCHDOG_SECONDS from unit.mocks import MockPromptTarget _AZURE_ENDPOINT = "https://contoso.openai.azure.com/openai/v1" _TEXT_RECIPE = ComponentRecipe(class_module="pyrit.prompt_target.text_target", class_name="TextTarget") +_REGISTRIES = (TargetRegistry, ConverterRegistry, ScorerRegistry) @pytest.fixture(autouse=True) -def isolated_targets() -> Iterator[None]: - TargetRegistry.reset_registry_singleton() +def isolated_registries() -> Iterator[None]: + for registry in _REGISTRIES: + registry.reset_registry_singleton() yield - TargetRegistry.reset_registry_singleton() + for registry in _REGISTRIES: + registry.reset_registry_singleton() + + +@pytest.fixture +def startup_and_temporary_entries() -> None: + targets = TargetRegistry.get_registry_singleton().instances + converters = ConverterRegistry.get_registry_singleton().instances + scorers = ScorerRegistry.get_registry_singleton().instances + with registration_origin(RegistryEntryOrigin.CONFIGURATION): + targets.register(MockPromptTarget(), name="startup_chat") + converters.register(Base64Converter(), name="startup_base64") + scorers.register(SubStringScorer(substring="x", categories=["leak"]), name="startup_leak") + targets.register(MockPromptTarget(), name="launch_chat") + converters.register(Base64Converter(), name="launch_base64") + scorers.register(SubStringScorer(substring="y", categories=["leak"]), name="launch_leak") + + +def _reference(name: str, component_type: ComponentType) -> Parameter: + return Parameter(name=name, description=name, reference=RegistryReference(component_type=component_type)) async def _prepare_openai_async(*, params: dict[str, Any], auth_mode: str = "identity") -> dict[str, Any]: @@ -304,3 +331,94 @@ def slow_create_recipe(storage: RegistryRecipeStorage, *, name: str, recipe: Com register.assert_called_once() assert (tmp_path / "targets" / "contoso_gpt4o.json").exists() is not registering_fails assert isinstance(cancelled.value.__cause__, RuntimeError) is registering_fails + + +@pytest.mark.usefixtures("patch_central_database", "startup_and_temporary_entries") +@pytest.mark.parametrize( + ("component_type", "value", "named"), + [ + (ComponentType.TARGET, "launch_chat", "target 'launch_chat'"), + (ComponentType.CONVERTER, "launch_base64", "converter 'launch_base64'"), + (ComponentType.SCORER, ["startup_leak", "launch_leak"], "scorer 'launch_leak'"), + ], +) +def test_refuse_temporary_references_refuses_an_entry_that_is_gone_after_a_restart( + component_type: ComponentType, value: object, named: str +) -> None: + with pytest.raises(NotSaveableError) as refusal: + refuse_temporary_references(parameters=[_reference("uses", component_type)], params={"uses": value}) + + assert str(refusal.value) == ( + f"Uses temporary {named}, which won't exist after a restart. It can still be created without saving it." + ) + + +@pytest.mark.usefixtures("patch_central_database", "startup_and_temporary_entries") +@pytest.mark.parametrize( + ("component_type", "value"), + [ + (ComponentType.TARGET, "startup_chat"), + (ComponentType.CONVERTER, ["startup_base64"]), + (ComponentType.SCORER, "startup_leak"), + (ComponentType.TARGET, "not_registered"), + (ComponentType.TARGET, None), + (ComponentType.TARGET, ""), + ], +) +def test_refuse_temporary_references_accepts_entries_that_come_back_or_a_reference_left_unset( + component_type: ComponentType, value: object +) -> None: + refuse_temporary_references(parameters=[_reference("uses", component_type)], params={"uses": value}) + + +def test_refuse_temporary_references_refuses_a_kind_that_saved_entries_cant_use() -> None: + with pytest.raises(NotSaveableError) as refusal: + refuse_temporary_references(parameters=[_reference("uses", ComponentType.SCENARIO)], params={"uses": "nightly"}) + + assert str(refusal.value) == ( + "Uses scenario 'nightly', which saved entries can't use yet. It can still be created without saving it." + ) + + +_TONE_RECIPE = ComponentRecipe( + class_module="pyrit.converter.tone_converter", + class_name="ToneConverter", + params={"converter_target": "saved_chat", "tone": "formal"}, +) + + +async def test_save_then_register_async_refuses_a_recipe_naming_an_entry_deleted_after_it_was_checked( + tmp_path: Path, +) -> None: + register = MagicMock() + + with pytest.raises(SavedEntryConflictError) as refusal: + await save_then_register_async( + kind=RegistryRecipeKind.CONVERTERS, + name="formal_tone", + recipe=_TONE_RECIPE, + register=register, + source=str(tmp_path), + ) + + assert str(refusal.value) == "Target 'saved_chat' was deleted while this was being saved, so it can't be saved now." + register.assert_not_called() + assert not (tmp_path / "converters" / "formal_tone.json").exists() + + +@pytest.mark.usefixtures("patch_central_database") +async def test_save_then_register_async_refuses_a_recipe_naming_a_temporary_entry_that_took_a_deleted_ones_name( + tmp_path: Path, +) -> None: + TargetRegistry.get_registry_singleton().instances.register(MockPromptTarget(), name="saved_chat") + + with pytest.raises(SavedEntryConflictError): + await save_then_register_async( + kind=RegistryRecipeKind.CONVERTERS, + name="formal_tone", + recipe=_TONE_RECIPE, + register=MagicMock(), + source=str(tmp_path), + ) + + assert not (tmp_path / "converters" / "formal_tone.json").exists()