diff --git a/.pyrit_conf_example b/.pyrit_conf_example index e9caefd896..6df431908e 100644 --- a/.pyrit_conf_example +++ b/.pyrit_conf_example @@ -179,6 +179,22 @@ allow_custom_initializers: false # blob prefix. # registry_recipes_source: https://account.blob.core.windows.net/container/registry_recipes +# Server Credentials Users Can Pick +# --------------------------------- +# Keys in this server's environment that users can pick by name for an OpenAI +# target instead of typing one. Users see each entry's name and endpoint, never the +# key or the variable. The key is only sent to the listed endpoint, and a saved +# target stores the entry's name, not the key, and reads the key again each time +# the backend starts. List a variable that holds only this key: a variable a +# target reads on its own, such as OPENAI_CHAT_KEY, can still reach any endpoint +# through a Temporary target created without a key. +# +# Default: none +# server_credentials: +# - name: contoso +# env_var: CONTOSO_OPENAI_KEY +# endpoint: https://contoso.openai.azure.com/openai/v1 + # Upload Folder for API-Created Targets # ------------------------------------- # Folder that targets created through the REST API may upload local files from diff --git a/doc/getting_started/pyrit_conf.md b/doc/getting_started/pyrit_conf.md index 326a8151de..b128dd6205 100644 --- a/doc/getting_started/pyrit_conf.md +++ b/doc/getting_started/pyrit_conf.md @@ -236,7 +236,7 @@ The backend restores saved entries at startup and after a live apply, once the c #### Saved entry requirements -A saved file never holds a credential: restore refuses a file that stores a value for a parameter its class marks as a credential, such as `api_key`. A saved target also can't use a key from this server: it signs in with Microsoft Entra ID (`"auth_mode": "identity"`), which uses this server's Azure identity for everyone using the app, or needs no key. Targets from the server's configuration that it uses, such as a round-robin's members, keep their own sign-in. Restore refuses a target file that breaks these rules: +A saved file never holds a credential: restore refuses a file that stores a value for a parameter its class marks as a credential, such as `api_key`. A saved target also can't use a key from this server unless it is listed in `server_credentials` (below): otherwise it signs in with Microsoft Entra ID (`"auth_mode": "identity"`), which uses this server's Azure identity for everyone using the app, or needs no key. Targets from the server's configuration that it uses, such as a round-robin's members, keep their own sign-in. Restore refuses a target file that breaks these rules: - It can't read an empty key from an environment variable or leave an address to this server's settings. An address the server would otherwise fill in must be a full http(s) or ws(s) address. - It sets each setting its target type would otherwise read from this server's environment, such as an OpenAI target's `model_name`, and only parameters the create API accepts, so no Python objects such as `httpx_client_kwargs`. @@ -244,6 +244,21 @@ A saved file never holds a credential: restore refuses a file that stores a valu - In identity mode, an OpenAI target file sets `"headers": "{}"` in its `params` so that the server's `OPENAI_ADDITIONAL_REQUEST_HEADERS` aren't added. The OpenAI SDK adds the headers in `OPENAI_CUSTOM_HEADERS` to every request, so while the server sets it, OpenAI targets can't be saved and saved ones aren't restored. The SDK's `OPENAI_ORG_ID` and `OPENAI_PROJECT_ID` still apply to every OpenAI target on this server. - GitHub Copilot, Hugging Face, HackAPrompt, LiteLLM, HTTP, and Copilot WebSocket targets can't be saved yet. +### `server_credentials` + +Keys in this server's environment that users can pick by name for an OpenAI target instead of typing one. Each entry has a `name` users pick, the `env_var` that holds the key, and the only `endpoint` the key is sent to: + +```yaml +server_credentials: + - name: contoso + env_var: CONTOSO_OPENAI_KEY + endpoint: https://contoso.openai.azure.com/openai/v1 +``` + +`GET /api/targets/types` lists each entry's name and endpoint for the types that can use it, never the key or the variable. A target that names an entry (`"server_credential": "contoso"` with `"auth_mode": "api_key"` in `POST /api/targets`) gets the key only when its endpoint is the entry's endpoint, compared with the scheme and host lowercased and a default port and trailing slash removed. A saved target stores the entry's name, never the key, and reads the key again each time the backend starts, so rotating the variable's value takes effect at the next start. Restore refuses a saved target whose entry is no longer listed or whose variable isn't set. + +List a variable that holds only this key. A variable a target reads on its own, such as `OPENAI_CHAT_KEY`, can still reach any endpoint through a Temporary target created without a key, so listing it doesn't limit where that key goes. Names are up to 64 lowercase letters, digits, and underscores, starting with a letter, and each name can be listed once. The default is none. + ### `initialization_scripts` Local paths to custom Python scripts containing `PyRITInitializer` subclasses. Paths can be absolute or relative to the current working directory. diff --git a/doc/gui/0_gui.md b/doc/gui/0_gui.md index 7280a9a8ad..09dbe48965 100644 --- a/doc/gui/0_gui.md +++ b/doc/gui/0_gui.md @@ -239,7 +239,10 @@ robin that uses the old name: restore finds its members by name, so it would otherwise send to the initializer's target in place of the saved one. Saved targets can't hold credentials yet, so choose Identity-based or No key -authentication when the target supports it. A target that needs an API key or +authentication when the target supports it. When the server lists keys for the +target type in `server_credentials`, you can also choose **Server credential** and +pick one by name: the key stays on the server, and the endpoint is set to the only +address that key is sent to. A target that needs an API key or another credential value, a type that can't be saved, a round robin that uses a Temporary target, or a target that only you can use or that allows credential updates is created as **Temporary** instead, and the dialog says why. diff --git a/frontend/e2e/registry.spec.ts b/frontend/e2e/registry.spec.ts index 06aab85e9b..70abf217d9 100644 --- a/frontend/e2e/registry.spec.ts +++ b/frontend/e2e/registry.spec.ts @@ -168,6 +168,46 @@ 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("saves a target that uses a server credential by its name, with no key @seeded", async ({ page, request }) => { + const name = `listed_chat_${Date.now()}`; + const sent: unknown[] = []; + page.on("request", (outgoing) => { + if (outgoing.method() === "POST" && new URL(outgoing.url()).pathname === "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/api/targets") { + sent.push(outgoing.postDataJSON()); + } + }); + await page.goto("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/registry/targets"); + await page.getByRole("button", { name: "New Target", exact: true }).click(); + const dialog = page.getByRole("dialog"); + const picker = dialog.getByRole("combobox", { name: "Target Type" }); + await expect(picker).toBeEnabled(); + await picker.click(); + await page.getByRole("option", { name: /Implementation: OpenAIChatTarget/ }).click(); + await dialog.getByRole("radio", { name: /^Server credential/ }).check(); + const endpoint = dialog.getByPlaceholder("https://your-resource.openai.azure.com/"); + await expect(endpoint).toHaveValue("https://e2e-listed.example.test/v1"); + await expect(endpoint).toHaveAttribute("readonly", ""); + await expect(dialog.getByPlaceholder("API key (stored in memory only)")).toHaveCount(0); + await dialog.getByPlaceholder("e.g. gpt-4o, my-deployment").fill("listed-model"); + await dialog.getByRole("textbox", { name: /Registry Name/ }).fill(name); + await dialog.getByRole("button", { name: "Save Target" }).click(); + await expect(dialog).toHaveCount(0); + + expect(sent).toEqual([{ + name, + type: "OpenAIChatTarget", + params: { endpoint: "https://e2e-listed.example.test/v1", model_name: "listed-model" }, + auth_mode: "api_key", + server_credential: "e2e_listed", + persist: true, + private: false, + }]); + await expect(page.getByTestId(`target-row-${name}`).getByText("Saved", { exact: true })).toBeVisible(); + const saved = await request.get(`/api/targets/${name}`, { headers: compatibilityHeaders() }); + expect(saved.ok(), await saved.text()).toBe(true); + expect(await saved.text()).not.toContain("e2e-listed-key"); +}); + interface RegisteredConverter { converter_id: string; identifier: { diff --git a/frontend/playwright.config.ts b/frontend/playwright.config.ts index 2eca3c0ecf..0e1543282d 100644 --- a/frontend/playwright.config.ts +++ b/frontend/playwright.config.ts @@ -140,7 +140,7 @@ 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" }, + env: { PYRIT_DEV_MODE: "true", PYRIT_E2E_LISTED_KEY: "e2e-listed-key" }, url: `${E2E_BACKEND_URL}/api/health`, reuseExistingServer: false, timeout: 120_000, diff --git a/frontend/src/components/Config/CreateTargetDialog.test.tsx b/frontend/src/components/Config/CreateTargetDialog.test.tsx index 463cc76774..ddcd4da201 100644 --- a/frontend/src/components/Config/CreateTargetDialog.test.tsx +++ b/frontend/src/components/Config/CreateTargetDialog.test.tsx @@ -3558,6 +3558,100 @@ describe("CreateTargetDialog saving", () => { }); }); + const SERVER_CREDENTIAL_TYPES: TargetTypeListResponse = { + items: SAVEABLE_TARGET_TYPES.items.map((entry) => ( + entry.target_type === "OpenAIChatTarget" + ? { + ...entry, + server_credentials: [ + { name: "contoso", endpoint: "https://api.contoso.com/v1" }, + { name: "fabrikam", endpoint: "https://fabrikam.openai.azure.com/openai/v1" }, + ], + } + : entry + )), + }; + + it("should save a target that uses a server credential by sending its name and no key", async () => { + const user = userEvent.setup(); + mockedTargetsApi.listTargetTypes.mockResolvedValue(SERVER_CREDENTIAL_TYPES); + render( + + + + ); + + await selectTargetType("OpenAIChatTarget"); + await user.click(screen.getByRole("radio", { name: /^Server credential/ })); + const endpointInput = screen.getByPlaceholderText("https://your-resource.openai.azure.com/"); + expect(endpointInput).toHaveValue("https://api.contoso.com/v1"); + expect(endpointInput).toHaveAttribute("readonly"); + expect(screen.queryByPlaceholderText("API key (stored in memory only)")).not.toBeInTheDocument(); + await user.selectOptions(screen.getByRole("combobox", { name: "Server credential" }), "fabrikam"); + expect(endpointInput).toHaveValue("https://fabrikam.openai.azure.com/openai/v1"); + await pasteInto(user, screen.getByRole("textbox", { name: /Model \/ Deployment Name/ }), "gpt-4o"); + await user.click(screen.getByRole("button", { name: "Save Target" })); + + await waitFor(() => expect(defaultProps.onCreated).toHaveBeenCalledTimes(1)); + expect(mockedTargetsApi.createTarget).toHaveBeenCalledWith({ + name: "openai_chat_gpt_4o", + type: "OpenAIChatTarget", + params: { endpoint: "https://fabrikam.openai.azure.com/openai/v1", model_name: "gpt-4o" }, + auth_mode: "api_key", + server_credential: "fabrikam", + private: false, + persist: true, + }); + }); + + it("should keep the server credential's endpoint, and drop its name, when a key is typed instead", async () => { + const user = userEvent.setup(); + mockedTargetsApi.listTargetTypes.mockResolvedValue(SERVER_CREDENTIAL_TYPES); + render( + + + + ); + + await selectTargetType("OpenAIChatTarget"); + await user.click(screen.getByRole("radio", { name: /^Server credential/ })); + await user.click(screen.getByRole("radio", { name: "API Key" })); + const endpointInput = screen.getByPlaceholderText("https://your-resource.openai.azure.com/"); + expect(endpointInput).toHaveValue("https://api.contoso.com/v1"); + expect(endpointInput).not.toHaveAttribute("readonly"); + await pasteInto(user, screen.getByRole("textbox", { name: /Model \/ Deployment Name/ }), "gpt-4o"); + await user.type(screen.getByPlaceholderText("API key (stored in memory only)"), "test-key"); + + expect(screen.getByRole("status", { name: "This target can't be saved" })).toHaveTextContent( + `Saved targets can't use an API key yet. ${TEMPORARY_NOTE}`, + ); + await user.click(screen.getByRole("button", { name: "Create as Temporary" })); + await waitFor(() => expect(defaultProps.onCreated).toHaveBeenCalledTimes(1)); + expect(mockedTargetsApi.createTarget).toHaveBeenCalledWith({ + name: "openai_chat_gpt_4o", + type: "OpenAIChatTarget", + params: { endpoint: "https://api.contoso.com/v1", model_name: "gpt-4o", api_key: "test-key" }, + private: false, + persist: false, + }); + }); + + it("should not offer a server credential for a type the server lists none for", async () => { + mockedTargetsApi.listTargetTypes.mockResolvedValue(SERVER_CREDENTIAL_TYPES); + render( + + + + ); + + await selectTargetType("OpenAIChatTarget"); + expect(screen.getByRole("radio", { name: /^Server credential/ })).toBeInTheDocument(); + await selectTargetType("GitHubCopilotTarget"); + + expect(screen.queryByRole("radio", { name: /^Server credential/ })).not.toBeInTheDocument(); + expect(screen.queryByRole("combobox", { name: "Server credential" })).not.toBeInTheDocument(); + }); + it("should offer Temporary with the reason when the target uses an API key", async () => { const user = userEvent.setup(); render( diff --git a/frontend/src/components/Config/CreateTargetDialog.tsx b/frontend/src/components/Config/CreateTargetDialog.tsx index d64a61235f..a1e80791a5 100644 --- a/frontend/src/components/Config/CreateTargetDialog.tsx +++ b/frontend/src/components/Config/CreateTargetDialog.tsx @@ -147,6 +147,11 @@ const AUTH_MODE_LABELS: Record = { none: 'No key', } +// A server credential is sent as an API key, but the key stays on the server, so a saved target can use it. +type AuthChoice = TargetAuthMode | 'server_credential' + +const SERVER_CREDENTIAL_LABEL = 'Server credential' + // A new target starts with the first of these that a saved target of its type can use. const SAVEABLE_AUTH_MODE_PREFERENCE: readonly TargetAuthMode[] = ['identity', 'none'] @@ -172,6 +177,7 @@ return 'Supported authentication: GitHub token' } const labels = authModes.map((mode) => AUTH_MODE_LABELS[mode]) + if (entry.server_credentials?.length) labels.push(SERVER_CREDENTIAL_LABEL) return `Supported authentication: ${labels.join(' or ')}` } @@ -316,7 +322,8 @@ export default function CreateTargetDialog({ open, onClose, onCreated, existingT const [hasDifferentUnderlying, setHasDifferentUnderlying] = useState(false) const [underlyingModel, setUnderlyingModel] = useState('') // The auth mode the user picked; until then the dialog uses the default for the selected type. - const [chosenAuthMode, setChosenAuthMode] = useState(null) + const [chosenAuthMode, setChosenAuthMode] = useState(null) + const [serverCredentialName, setServerCredentialName] = useState('') const [apiKey, setApiKey] = useState('') const [onlyMeChoice, setOnlyMeChoice] = useState(false) // Null follows the default: updates are allowed for a private target and not for a shared one. @@ -459,7 +466,9 @@ export default function CreateTargetDialog({ open, onClose, onCreated, existingT const supportsNoKey = targetTypeEntry ? targetTypeEntry.supported_auth_modes.includes('none') : defaultSupportsNoKey(targetType) - const showAuthField = targetType !== '' && (supportsIdentity || supportsNoKey) + const serverCredentials = targetTypeEntry?.server_credentials ?? [] + const supportsServerCredential = serverCredentials.length > 0 + const showAuthField = targetType !== '' && (supportsIdentity || supportsNoKey || supportsServerCredential) // Default to a mode a saved target of this type can use. It is derived, so it also applies when the type's // details arrive after the type was chosen. const defaultAuthMode = SAVEABLE_AUTH_MODE_PREFERENCE.find( @@ -468,9 +477,16 @@ export default function CreateTargetDialog({ open, onClose, onCreated, existingT const chosenAuthModeSupported = chosenAuthMode === 'api_key' || (chosenAuthMode === 'identity' && supportsIdentity) || (chosenAuthMode === 'none' && supportsNoKey) - const authMode = chosenAuthMode !== null && chosenAuthModeSupported ? chosenAuthMode : defaultAuthMode + || (chosenAuthMode === 'server_credential' && supportsServerCredential) + const authMode: AuthChoice = chosenAuthMode !== null && chosenAuthModeSupported ? chosenAuthMode : defaultAuthMode const isIdentity = showAuthField && authMode === 'identity' const isNoKey = showAuthField && authMode === 'none' + // The server only sends a credential's key to that credential's endpoint, so the endpoint follows the choice. + const serverCredential = showAuthField && authMode === 'server_credential' + ? serverCredentials.find((credential) => credential.name === serverCredentialName) ?? serverCredentials[0] + : undefined + const isServerCredential = serverCredential !== undefined + const requestEndpoint = serverCredential?.endpoint ?? endpoint const endpointRequired = Boolean(endpointParameter?.required) || (metadataUnavailableForSelection && hasEndpointField) // Without the type's details, still require the model every OpenAI type needs. The suggested name then includes // it, which keeps it off names such as `openai_chat` that startup initializers use. @@ -478,7 +494,7 @@ export default function CreateTargetDialog({ open, onClose, onCreated, existingT ? Boolean(modelNameParameter.required) : metadataUnavailableForSelection && isOpenAi const underlyingModelRequired = Boolean(underlyingModelParameter?.required) - const apiKeyRequired = Boolean(apiKeyParameter?.required) && !isIdentity && !isNoKey + const apiKeyRequired = Boolean(apiKeyParameter?.required) && !isIdentity && !isNoKey && !isServerCredential // Anything built on a private target is private too, so such a round robin can't be shared. const privateMemberName = isRoundRobin ? selectedInnerTargets.find((selected: SelectedInnerTarget) => availableTargets.some( @@ -569,7 +585,12 @@ export default function CreateTargetDialog({ open, onClose, onCreated, existingT if (!targetType) return null if (targetTypeEntry?.not_saveable_reason) return targetTypeEntry.not_saveable_reason const saveableAuthModes = targetTypeEntry?.saveable_auth_modes - if (showAuthField && saveableAuthModes && !saveableAuthModes.includes(authMode)) { + if ( + showAuthField + && saveableAuthModes + && authMode !== 'server_credential' + && !saveableAuthModes.includes(authMode) + ) { const current = authMode === 'api_key' ? 'an API key' : AUTH_MODE_LABELS[authMode] return `Saved targets can't use ${current} yet.` } @@ -583,7 +604,9 @@ export default function CreateTargetDialog({ open, onClose, onCreated, existingT if (allowCredentialUpdates) return "A saved target's credentials can't be updated." return null })() - const requestAuthMode: TargetAuthMode | undefined = isIdentity ? 'identity' : isNoKey ? 'none' : undefined + const requestAuthMode: TargetAuthMode | undefined = isIdentity + ? 'identity' + : isNoKey ? 'none' : serverCredential ? 'api_key' : undefined // The parameters a create request sends for the standard fields, or why the form can't give them. const buildFormParams = (): { ok: true, params: Record } | { ok: false, error: string } => { const metadataParams = buildParametersFromForm(metadataDrivenParameters, parameterValues) @@ -597,10 +620,12 @@ export default function CreateTargetDialog({ open, onClose, onCreated, existingT if (parameter.identity_conflicting) delete params[parameter.name] } } - if (hasEndpointField && endpoint) params.endpoint = endpoint + if (hasEndpointField && requestEndpoint) params.endpoint = requestEndpoint if (hasModelNameField && modelName) params.model_name = modelName // A pasted key often ends with a newline, which can't be sent in a request header. - if (hasApiKeyField && !isIdentity && !isNoKey && apiKey.trim()) params.api_key = apiKey.trim() + if (hasApiKeyField && !isIdentity && !isNoKey && !isServerCredential && apiKey.trim()) { + params.api_key = apiKey.trim() + } if ((underlyingModelRequired || hasDifferentUnderlying) && underlyingModel && hasUnderlyingModelField) { params[underlyingModelParameter?.name ?? 'underlying_model'] = underlyingModel } @@ -614,7 +639,12 @@ export default function CreateTargetDialog({ open, onClose, onCreated, existingT } const formParams = buildFormParams() if (!formParams.ok) return null - return { type: targetType, params: formParams.params, ...(requestAuthMode ? { auth_mode: requestAuthMode } : {}) } + return { + type: targetType, + params: formParams.params, + ...(requestAuthMode ? { auth_mode: requestAuthMode } : {}), + ...(serverCredential ? { server_credential: serverCredential.name } : {}), + } })() const checkedReason = useSaveability(saveabilityRequest, targetsApi.checkSaveability) // A refused save only applies to the values it was refused for, so any edit lets the user try saving again. @@ -625,6 +655,7 @@ export default function CreateTargetDialog({ open, onClose, onCreated, existingT hasDifferentUnderlying, underlyingModel, authMode, + serverCredential?.name, apiKey, parameterValues, selectedInnerTargets, @@ -725,6 +756,7 @@ export default function CreateTargetDialog({ open, onClose, onCreated, existingT setHasDifferentUnderlying(false) setUnderlyingModel('') setChosenAuthMode(null) + setServerCredentialName('') setApiKey('') setOnlyMeChoice(false) setCredentialUpdatesChoice(null) @@ -827,7 +859,7 @@ export default function CreateTargetDialog({ open, onClose, onCreated, existingT apiKey?: string } = {} if (!targetType) errors.targetType = 'Please select a target type' - if (endpointRequired && !endpoint) errors.endpoint = 'Please provide an endpoint URL' + if (endpointRequired && !requestEndpoint) errors.endpoint = 'Please provide an endpoint URL' if (modelNameRequired && !modelName) errors.modelName = 'Please provide a model name' if (underlyingModelRequired && !underlyingModel) { errors.underlyingModel = 'Please provide the underlying model' @@ -856,6 +888,7 @@ export default function CreateTargetDialog({ open, onClose, onCreated, existingT type: targetType, params: formParams.params, ...(requestAuthMode ? { auth_mode: requestAuthMode } : {}), + ...(serverCredential ? { server_credential: serverCredential.name } : {}), persist, private: onlyMe, // The server applies the same default, so the choice is sent only when the user changed it. @@ -1154,7 +1187,9 @@ export default function CreateTargetDialog({ open, onClose, onCreated, existingT {hasEndpointField && ( setEndpoint(data.value)} onFocus={() => setEndpointFocused(true)} onBlur={() => setEndpointFocused(false)} @@ -1268,11 +1304,22 @@ export default function CreateTargetDialog({ open, onClose, onCreated, existingT { - const next = data.value as TargetAuthMode + const next = data.value as AuthChoice setChosenAuthMode(next) if (next === 'none') { setApiKey('') } + if (next === 'server_credential') { + setApiKey('') + const picked = serverCredentials.find((credential) => ( + credential.name === serverCredentialName + )) ?? serverCredentials[0] + if (picked) { + setServerCredentialName(picked.name) + // Kept when the user switches back to typing a key for the same address. + setEndpoint(picked.endpoint) + } + } if (next === 'identity') { setApiKey('') setParameterValues((current) => { @@ -1292,11 +1339,38 @@ export default function CreateTargetDialog({ open, onClose, onCreated, existingT {supportsNoKey && ( )} + {supportsServerCredential && ( + + )} )} - {hasApiKeyField && !isIdentity && !isNoKey && ( + {serverCredential && ( + + + + )} + + {hasApiKeyField && !isIdentity && !isNoKey && !isServerCredential && ( auth_mode?: TargetAuthMode + /** A server credential from the type's list to use as the key, with `auth_mode` 'api_key'. */ + server_credential?: string /** Save the target so it comes back after a restart. */ persist?: boolean /** Makes the target visible to and usable by only its creator. */ @@ -568,6 +570,8 @@ export interface TargetSaveabilityRequest { type: string params: Record auth_mode?: TargetAuthMode + /** A server credential from the type's list to use as the key, with `auth_mode` 'api_key'. */ + server_credential?: string } /** Whether an entry could be saved as asked, decided by the checks saving it runs. */ @@ -855,6 +859,12 @@ export interface ConverterPreviewResponse { export type TargetAuthMode = 'api_key' | 'identity' | 'none' +/** A key kept on the server that users can pick for a target, and the only address it is sent to. */ +export interface ServerCredentialChoice { + name: string + endpoint: string +} + export interface TargetTypeEntry { target_type: string parameters: Parameter[] @@ -863,6 +873,8 @@ export interface TargetTypeEntry { saveable_auth_modes?: TargetAuthMode[] /** Why a target of this type can't be saved. */ not_saveable_reason?: string | null + /** Server credentials a target of this type can use instead of a typed key. */ + server_credentials?: ServerCredentialChoice[] description?: string | null } diff --git a/pyrit/backend/README.md b/pyrit/backend/README.md index 7f9fddc9fa..1e9e1a8014 100644 --- a/pyrit/backend/README.md +++ b/pyrit/backend/README.md @@ -61,8 +61,9 @@ its database collation. - `GET /api/targets` - List available prompt targets - `GET /api/targets/{id}` - Get target details - `GET /api/targets/types` - List the target types that can be created, with their parameters and auth - modes, the auth modes a saved target of each type can use (`saveable_auth_modes`), and why a type can't be saved - at all (`not_saveable_reason`) + modes, the auth modes a saved target of each type can use (`saveable_auth_modes`), why a type can't be saved + at all (`not_saveable_reason`), and the server credentials a target of each type can use + (`server_credentials`: each one's name and endpoint) - `POST /api/targets` - Create (and optionally register) a target - `POST /api/targets/saveability` - Say whether a target could be saved, without building or saving it. Send the create request's `type`, `params`, and `auth_mode`; the answer is `{"not_saveable_reason": ...}`, which gives only @@ -102,11 +103,13 @@ Per-send values use A created target is Temporary: a restart or a configuration apply removes it. With `"persist": true` (and `register` left on), the target is saved under `registry_recipes_source` and restored at every start, and the signed-in user is -recorded as the one who saved it. A saved target can't hold or use a key: it signs in with Microsoft Entra ID -(`"auth_mode": "identity"`, through this server's Azure identity) or needs no key. An OpenAI target's empty `headers` -is set to `"{}"` first, so a saved one doesn't send this server's `OPENAI_ADDITIONAL_REQUEST_HEADERS`. The save -itself is the registry library's `prepare_saved_params_async` and `save_then_register_async`, so Python code saves a -target the same way; the API adds the signed-in user, the configured source, and the responses below. +recorded as the one who saved it. A saved target can't hold a key: it signs in with Microsoft Entra ID +(`"auth_mode": "identity"`, through this server's Azure identity), needs no key, or names a key an administrator listed +in `server_credentials` (`"server_credential": ""` with `"auth_mode": "api_key"`). That key is read from this +server's environment, only sent to the credential's endpoint, and never saved. An OpenAI target's empty `headers` is +set to `"{}"` first, so a saved one doesn't send this server's `OPENAI_ADDITIONAL_REQUEST_HEADERS`. The save itself is +the registry library's `prepare_saved_params_async` and `save_then_register_async`, so Python code saves a target the +same way; the API adds the signed-in user, the configured source, and the responses below. | A request with `persist` that... | Gets | |---|---| @@ -118,14 +121,15 @@ target the same way; the API adds the signed-in user, the configured source, and | saves an OpenAI target while this server sets `OPENAI_CUSTOM_HEADERS`, whose headers the OpenAI SDK adds to every request | **400** not-saveable | | uses a Temporary target | **400** not-saveable | | gives an address that isn't a full http(s) or ws(s) address, where this server's address setting would apply | **400** | +| names a server credential that isn't listed or set, or an endpoint that isn't the credential's | **400** | | takes a name that a target or a saved file already has | **409** | | can't be written to storage | **503** | A not-saveable **400** has `"type": "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/errors/not-saveable"` and the cause alone in `not_saveable_reason`, and the -request can be sent again without `persist`. For any other **400**, fix what its `detail` names, such as the address -or a constructor parameter. A name that a registered target has is a **409** without a problem type, with or without -`persist`. `GET /api/targets/types` gives the same class-level answer before a request is sent, and -`POST /api/targets/saveability` the answer for the request's values. When storage can't be written, the +request can be sent again without `persist`. For any other **400**, fix what its `detail` names, such as the address, +a constructor parameter, or the server credential. A name that a registered target has is a **409** without a problem +type, with or without `persist`. `GET /api/targets/types` gives the same class-level answer before a request is sent, +and `POST /api/targets/saveability` the answer for the request's values. When storage can't be written, the server log names the target and its folder, since the target comes back at the next start if the write reached storage anyway. @@ -969,7 +973,8 @@ API callers are trusted operators, so these are intentional exceptions: server's environment, sent even to an endpoint the caller chose, or a token for the server's Azure identity, sent to the Azure endpoint or container the caller chose. For an OpenAI-compatible server that needs no key, set `auth_mode` to `none` so the target uses none - of these. + of these. A key listed in `server_credentials` is only sent to its listed endpoint, so list a + variable that holds only that key, not one a target reads on its own. - Registered targets, converters, and scorers are shared: any API caller can use them, whoever created them, except [private targets](#private-targets) and the components built on them. - Prompt content is not filtered; it is adversarial test data by design. diff --git a/pyrit/backend/models/targets.py b/pyrit/backend/models/targets.py index 5c5835170f..32cde95a39 100644 --- a/pyrit/backend/models/targets.py +++ b/pyrit/backend/models/targets.py @@ -32,6 +32,7 @@ __all__ = [ "CreateTargetRequest", "DetectTargetCapabilitiesRequest", + "ServerCredentialChoice", "TargetListResponse", "TargetTypeEntry", "TargetTypeResponse", @@ -49,6 +50,13 @@ def _default_auth_modes() -> list[AuthMode]: return ["api_key"] +class ServerCredentialChoice(BaseModel): + """A server credential users can pick, without the key or the variable that holds it.""" + + name: str = Field(..., description="The name to send as server_credential") + endpoint: str = Field(..., description="The only endpoint the credential is sent to") + + class TargetTypeEntry(BaseModel): """A target type available from the backend registry.""" @@ -72,6 +80,10 @@ class TargetTypeEntry(BaseModel): None, description="Why a target of this type can't be saved, or None when it can be with a saveable mode" ) description: str | None = Field(None, description="Short description of the target from its docstring") + server_credentials: list[ServerCredentialChoice] = Field( + default_factory=list, + description="Server credentials an administrator lets users pick for a target of this type", + ) class TargetTypeResponse(BaseModel): @@ -88,7 +100,7 @@ class TargetListResponse(BaseModel): class TargetParametersRequest(BaseModel): - """The target type, constructor parameters, and auth mode that a target is built from.""" + """The target type, constructor parameters, auth mode, and server credential that a target is built from.""" type: IdentifierStr = Field(..., description="Target type (e.g., 'OpenAIChatTarget')") params: dict[IdentifierStr, JSONValue] = Field( @@ -105,6 +117,24 @@ class TargetParametersRequest(BaseModel): "placeholder, for OpenAI-compatible servers that need no key; supported by OpenAI-family targets." ), ) + server_credential: str | None = Field( + None, + pattern=r"^[a-z][a-z0-9_]{0,63}$", + description=( + "A server credential from this server's list to use as the target's key, with auth_mode 'api_key'. " + "The target's endpoint must be the credential's; the key is never returned or saved" + ), + ) + + @model_validator(mode="after") + def _validate_server_credential(self) -> "TargetParametersRequest": + if self.server_credential is None: + return self + if self.auth_mode != "api_key": + raise ValueError("server_credential needs auth_mode 'api_key'") + if self.params.get("api_key") not in (None, ""): + raise ValueError("Send either an api_key or a server_credential, not both") + return self class CreateTargetRequest(TargetParametersRequest, RegistrationRequest): @@ -150,6 +180,8 @@ class CreateTargetRequest(TargetParametersRequest, RegistrationRequest): def _validate_source(self) -> "CreateTargetRequest": if self.source is None: return self + if self.server_credential is not None: + raise ValueError("server_credential can't be used with source") if self.register_instance: raise ValueError("source requires register=false") if self.params: diff --git a/pyrit/backend/routes/targets.py b/pyrit/backend/routes/targets.py index 9342673336..1d5aa80ac9 100644 --- a/pyrit/backend/routes/targets.py +++ b/pyrit/backend/routes/targets.py @@ -146,7 +146,10 @@ async def list_target_types(request: Request) -> TargetTypeResponse: # pyrit-as TargetTypeResponse: Available target types and build parameters. """ service = get_target_service() - return await service.list_target_types_async(upload_directory=_target_upload_directory(request)) + return await service.list_target_types_async( + upload_directory=_target_upload_directory(request), + server_credentials=getattr(request.app.state, "server_credentials", ()), + ) @router.post( @@ -180,6 +183,7 @@ async def check_target_saveability( # pyrit-async-suffix-exempt request=body, upload_directory=_target_upload_directory(request), is_admin=has_admin_access(request), + server_credentials=getattr(request.app.state, "server_credentials", ()), ) except PermissionError as e: raise HTTPException(status_code=status.HTTP_403_FORBIDDEN, detail=str(e)) from e @@ -241,6 +245,7 @@ async def create_target( is_admin=has_admin_access(request), owner=_saved_entry_owner(request) if body.persist else None, recipes_source=getattr(request.app.state, "registry_recipes_source", None), + server_credentials=getattr(request.app.state, "server_credentials", ()), ) except NotSaveableError as e: problem = NotSaveableProblemDetail( diff --git a/pyrit/backend/services/runtime_lifecycle.py b/pyrit/backend/services/runtime_lifecycle.py index 1c5a73a7ae..9a5fa95141 100644 --- a/pyrit/backend/services/runtime_lifecycle.py +++ b/pyrit/backend/services/runtime_lifecycle.py @@ -111,6 +111,7 @@ async def _management_async(self, config: ConfigurationLoader) -> None: self.app.state.allow_custom_initializers = config.allow_custom_initializers self.app.state.target_upload_directory = config.target_upload_directory self.app.state.registry_recipes_source = config.registry_recipes_source + self.app.state.server_credentials = list(config.server_credentials) registry = await asyncio.to_thread(InitializerRegistry.get_registry_singleton) registry.configure_custom_scripts_source(config.custom_initializers_source) preset_registry = ScenarioPresetRegistry.get_registry_singleton() @@ -148,14 +149,19 @@ async def _restore_saved_entries_async(self, config: ConfigurationLoader) -> boo Returns: bool: Whether every saved entry was restored. """ - restorer = RegistryRecipeRestorer(source=config.registry_recipes_source) + restorer = RegistryRecipeRestorer( + source=config.registry_recipes_source, server_credentials=config.server_credentials + ) # Reading can wait on storage, so it runs in a worker thread. Entries are built on this loop, through # the API's create for each kind, because a constructor such as HuggingFaceChatTarget's starts a task # on it; the target's create_async does its slow setup, such as importing torch, in a worker thread first. saved = await asyncio.to_thread(restorer.read) - report = await restorer.restore_async( - saved=saved, build_async=partial(build_saved_entry_async, upload_directory=config.target_upload_directory) + build_async = partial( + build_saved_entry_async, + upload_directory=config.target_upload_directory, + server_credentials=config.server_credentials, ) + report = await restorer.restore_async(saved=saved, build_async=build_async) self.restore_failures, self.restore_ignored = report.failures, report.ignored if not report.failures: return True @@ -185,6 +191,7 @@ async def startup_async(self) -> None: self.app.state.allow_custom_initializers = False self.app.state.target_upload_directory = None self.app.state.registry_recipes_source = None + self.app.state.server_credentials = [] self.app.state.environment_file_service = None self.app.state.configured_initializers = [] self.app.state.default_labels = {} diff --git a/pyrit/backend/services/saved_entry_restore.py b/pyrit/backend/services/saved_entry_restore.py index c2cda4a33e..96bebdae43 100644 --- a/pyrit/backend/services/saved_entry_restore.py +++ b/pyrit/backend/services/saved_entry_restore.py @@ -20,21 +20,28 @@ from pyrit.registry.registry_recipe_restore import RecipeRejectedError if TYPE_CHECKING: - from pyrit.models.catalog import StoredRecipe + from collections.abc import Sequence + from pyrit.models.catalog import ServerCredential, StoredRecipe -async def build_saved_entry_async(stored: StoredRecipe, *, upload_directory: str | None) -> None: + +async def build_saved_entry_async( + stored: StoredRecipe, *, upload_directory: str | None, server_credentials: Sequence[ServerCredential] = () +) -> None: """ Build one saved entry with the create the API uses for its kind, and register it under its name. The entry passes the same checks a create request does. Restore runs as the server and can't tell who wrote a saved file, so a target is built as an administrator would build it, for no caller: it sees only shared entries and has no owner. A target that uploads files gets this server's upload folder, as - it does through the API. + it does through the API, and a target that names a server credential gets its key from this server's + list, as it does through the API. Args: stored (StoredRecipe): The checked recipe to build. upload_directory (str | None): The folder this server lets targets upload files from, or None. + server_credentials (Sequence[ServerCredential]): The server credentials an administrator lets saved + targets use. Defaults to none. Raises: RecipeRejectedError: If the recipe doesn't make a valid create request. @@ -45,7 +52,10 @@ async def build_saved_entry_async(stored: StoredRecipe, *, upload_directory: str await get_technique_service().create_async(request) elif isinstance(request, CreateTargetRequest): await get_target_service().create_target_async( - request=request, upload_directory=upload_directory, is_admin=True + request=request, + upload_directory=upload_directory, + is_admin=True, + server_credentials=server_credentials, ) elif isinstance(request, CreateConverterRequest): await get_converter_service().create_converter_async(request=request) @@ -76,6 +86,8 @@ def _create_request( if stored.ref.kind is RegistryRecipeKind.TARGETS: if recipe.auth_mode is not None: fields["auth_mode"] = recipe.auth_mode + if recipe.server_credential is not None: + fields["server_credential"] = recipe.server_credential return CreateTargetRequest.model_validate(fields) if stored.ref.kind is RegistryRecipeKind.CONVERTERS: return CreateConverterRequest.model_validate(fields) diff --git a/pyrit/backend/services/target_service.py b/pyrit/backend/services/target_service.py index c1932b4244..f36d8cff5a 100644 --- a/pyrit/backend/services/target_service.py +++ b/pyrit/backend/services/target_service.py @@ -18,7 +18,7 @@ import asyncio import logging import uuid -from collections.abc import Generator, Mapping +from collections.abc import Generator, Mapping, Sequence from contextlib import contextmanager from functools import lru_cache from typing import Any @@ -34,6 +34,7 @@ ) from pyrit.backend.models.common import SaveabilityResponse from pyrit.backend.models.targets import ( + ServerCredentialChoice, TargetParametersRequest, TargetSaveabilityRequest, TargetTypeEntry, @@ -48,6 +49,7 @@ RegistryEntryOrigin, RegistryRecipeKind, SavedEntryOwner, + ServerCredential, TargetInstance, ) from pyrit.models.component_spec import SourceInstanceSpec, TargetBinding @@ -82,6 +84,7 @@ RegistryNameTakenError, registry_entry_origin, ) +from pyrit.registry.registry_recipe_rules import SavedEntryRefusedError, resolve_listed_credential logger = logging.getLogger(__name__) @@ -405,7 +408,9 @@ def _project_target_parameters(self, *, target_type: str, parameters: tuple[Para and parameter.is_allowed_external_input(allowed_path_params=target_cls.caller_path_parameters) ] - async def list_target_types_async(self, *, upload_directory: str | None = None) -> TargetTypeResponse: + async def list_target_types_async( + self, *, upload_directory: str | None = None, server_credentials: Sequence[ServerCredential] = () + ) -> TargetTypeResponse: """ List all available target types from the target class registry. @@ -422,6 +427,8 @@ async def list_target_types_async(self, *, upload_directory: str | None = None) Args: upload_directory (str | None): Folder the server lets API-created targets upload files from, or None when the server configures none. + server_credentials (Sequence[ServerCredential]): The server credentials an administrator lets + users pick; each type that can use one lists them by name and endpoint. Defaults to none. Returns: TargetTypeResponse containing all available target classes. @@ -449,6 +456,12 @@ async def list_target_types_async(self, *, upload_directory: str | None = None) saveable_auth_modes=saveable_auth_modes, not_saveable_reason=not_saveable_reason, description=metadata.class_description or None, + server_credentials=[ + ServerCredentialChoice(name=credential.name, endpoint=credential.endpoint) + for credential in server_credentials + ] + if self._registry.get_class(metadata.class_name).listed_credential_parameters + else [], ) ) return TargetTypeResponse(items=items) @@ -575,6 +588,7 @@ async def create_target_async( is_admin: bool = False, owner: SavedEntryOwner | None = None, recipes_source: str | None = None, + server_credentials: Sequence[ServerCredential] = (), ) -> TargetInstance | UnregisteredTarget: """ Create a new target instance from API request. @@ -610,6 +624,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. + server_credentials: The server credentials an administrator lets users pick. Returns: TargetInstance with the new target's details. @@ -638,6 +653,9 @@ async def create_target_async( target_cls, params = await self._requested_params_async( request=request, source=request.source, upload_directory=upload_directory, is_admin=is_admin ) + listed = self._listed_credential( + request=request, target_cls=target_cls, params=params, server_credentials=server_credentials + ) if request.persist: params = await prepare_saved_params_async( registry=self._registry, @@ -645,7 +663,10 @@ async def create_target_async( cls=target_cls, params=params, auth_mode=request.auth_mode, + listed_credential_parameter=listed[0] if listed is not None else None, ) + # The key reaches only the target being built; a saved recipe names the credential instead. + build_params = {**params, listed[0]: listed[1]} if listed is not None else params # LEGACY COMPATIBILITY: Only API callers that leave out the name reach this fallback; the GUI sends one. # Remove it when the name becomes required for registered targets. @@ -673,7 +694,7 @@ async def create_target_async( if request.source else await self._registry.create_instance_async( name=request.type, - params=params, + params=build_params, external_input=True, allowed_path_params=self._allowed_path_params(target_cls=target_cls), ) @@ -701,6 +722,7 @@ async def create_target_async( target_obj=target_obj, auth_mode=request.auth_mode, params=params, + server_credential=request.server_credential, owner=owner, recipes_source=recipes_source, creator=creator, @@ -725,6 +747,7 @@ async def check_saveability_async( request: TargetSaveabilityRequest, upload_directory: str | None = None, is_admin: bool = False, + server_credentials: Sequence[ServerCredential] = (), ) -> SaveabilityResponse: """ Say whether a target could be saved as asked, without building or saving it. @@ -740,6 +763,7 @@ async def check_saveability_async( or None when the server configures none. is_admin: Whether the caller may create a target that runs model repository code or authenticates with this server's stored credentials. + server_credentials: The server credentials an administrator lets users pick. Returns: SaveabilityResponse: Why the target can't be saved, or no reason when the save checks pass. @@ -751,6 +775,9 @@ async def check_saveability_async( target_cls, params = await self._requested_params_async( request=request, source=None, upload_directory=upload_directory, is_admin=is_admin ) + listed = self._listed_credential( + request=request, target_cls=target_cls, params=params, server_credentials=server_credentials + ) try: await prepare_saved_params_async( registry=self._registry, @@ -758,11 +785,41 @@ async def check_saveability_async( cls=target_cls, params=params, auth_mode=request.auth_mode, + listed_credential_parameter=listed[0] if listed is not None else None, ) except NotSaveableError as error: return SaveabilityResponse(not_saveable_reason=error.cause) return SaveabilityResponse() + @staticmethod + def _listed_credential( + *, + request: TargetParametersRequest, + target_cls: type[PromptTarget], + params: dict[str, Any], + server_credentials: Sequence[ServerCredential], + ) -> tuple[str, str] | None: + """ + Find the server credential a request picked, as the parameter that takes it and its key. + + Returns: + tuple[str, str] | None: The parameter and the key, or None when the request picked none. + + Raises: + ValueError: If the credential isn't listed or set, or the endpoint isn't the credential's. + """ + if request.server_credential is None: + return None + try: + return resolve_listed_credential( + cls=target_cls, + params=params, + name=request.server_credential, + server_credentials=server_credentials, + ) + except SavedEntryRefusedError as error: + raise ValueError(str(error)) from error + async def _requested_params_async( self, *, @@ -965,6 +1022,7 @@ async def _save_and_register_async( target_obj: PromptTarget, auth_mode: AuthMode, params: dict[str, Any], + server_credential: str | None, owner: SavedEntryOwner | None, recipes_source: str | None, creator: Mapping[str, Any], @@ -992,6 +1050,7 @@ async def _save_and_register_async( class_name=type_name, auth_mode=auth_mode, params={key: value for key, value in params.items() if key not in auth_parameters}, + server_credential=server_credential, owner=owner, ) await save_then_register_async( diff --git a/pyrit/models/catalog/__init__.py b/pyrit/models/catalog/__init__.py index a1f0c4575a..9e219c5149 100644 --- a/pyrit/models/catalog/__init__.py +++ b/pyrit/models/catalog/__init__.py @@ -68,6 +68,7 @@ StoredScenarioSuite, ) from pyrit.models.catalog.scorer import ScorerInstance + from pyrit.models.catalog.server_credential import ServerCredential, normalized_endpoint from pyrit.models.catalog.target import TargetInstance _LAZY_EXPORTS: dict[str, str] = { @@ -86,6 +87,8 @@ "SavedEntryOwner": "pyrit.models.catalog.registry_recipe", "SavedEntryRef": "pyrit.models.catalog.registry_recipe", "ScorerInstance": "pyrit.models.catalog.scorer", + "ServerCredential": "pyrit.models.catalog.server_credential", + "normalized_endpoint": "pyrit.models.catalog.server_credential", "RegisteredScenario": "pyrit.models.catalog.scenario", "RunScenarioRequest": "pyrit.models.catalog.scenario", "ScenarioLaunchConfiguration": "pyrit.models.catalog.scenario", diff --git a/pyrit/models/catalog/registry_recipe.py b/pyrit/models/catalog/registry_recipe.py index 2e197252dd..c95ea17402 100644 --- a/pyrit/models/catalog/registry_recipe.py +++ b/pyrit/models/catalog/registry_recipe.py @@ -70,6 +70,10 @@ class ComponentRecipe(_RegistryRecipe): max_length=MAX_ITEMS, description="Constructor parameters as the API accepted them; other entries are named, never embedded", ) + server_credential: _Identifier | None = Field( + None, + description="The server credential from this server's list that supplies the key; the key isn't stored", + ) owner: SavedEntryOwner | None = Field(None, description="Who saved the entry; None when sign-in is off") diff --git a/pyrit/models/catalog/server_credential.py b/pyrit/models/catalog/server_credential.py new file mode 100644 index 0000000000..ab3ef2b89e --- /dev/null +++ b/pyrit/models/catalog/server_credential.py @@ -0,0 +1,64 @@ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT license. + +"""Keys on this server that an administrator lets users pick for targets.""" + +from urllib.parse import urlsplit + +from pydantic import BaseModel, ConfigDict, Field, field_validator + +_DEFAULT_PORTS = {"http": 80, "https": 443} + + +def normalized_endpoint(url: str) -> str: + """ + Return an address in the form two addresses are compared in. + + The scheme and host are lowercased, and a default port and a trailing slash are dropped. Everything else is kept, + so an address with a user name, query, or fragment never matches a server credential's endpoint, which can't + have one. + + Args: + url (str): The address. + + Returns: + str: The address to compare. + """ + parts = urlsplit(url.strip()) + scheme = parts.scheme.lower() + host = (parts.hostname or "").lower() + # An IPv6 address keeps its brackets, so its last group can't be taken for the port. + if ":" in host: + host = f"[{host}]" + port = f":{parts.port}" if parts.port is not None and parts.port != _DEFAULT_PORTS.get(scheme) else "" + user_info = parts.netloc.rpartition("@")[0] + user = f"{user_info}@" if user_info else "" + query = f"?{parts.query}" if parts.query else "" + fragment = f"#{parts.fragment}" if parts.fragment else "" + return f"{scheme}://{user}{host}{port}{parts.path.rstrip('/')}{query}{fragment}" + + +class ServerCredential(BaseModel): + """A key in this server's environment that users can pick for targets that send requests to its endpoint.""" + + model_config = ConfigDict(extra="forbid", frozen=True) + + name: str = Field(..., pattern=r"^[a-z][a-z0-9_]{0,63}$", description="The name users pick") + env_var: str = Field( + ..., pattern=r"^[A-Za-z_][A-Za-z0-9_]{0,127}$", description="The environment variable that holds the key" + ) + endpoint: str = Field(..., min_length=1, max_length=2048, description="The only address the key is sent to") + + @field_validator("endpoint") + @classmethod + def _validate_endpoint(cls, value: str) -> str: + parts = urlsplit(value) + try: + port = parts.port + except ValueError as error: + raise ValueError("A server credential's endpoint has a port that isn't from 1 to 65535.") from error + if parts.scheme not in ("http", "https") or not parts.hostname or port == 0: + raise ValueError("A server credential's endpoint must be a full http or https address.") + if parts.username or parts.password or parts.query or parts.fragment: + raise ValueError("A server credential's endpoint can't hold a user name, password, query, or fragment.") + return value diff --git a/pyrit/prompt_target/common/prompt_target.py b/pyrit/prompt_target/common/prompt_target.py index 14b38a75d7..c0d8dd15c8 100644 --- a/pyrit/prompt_target/common/prompt_target.py +++ b/pyrit/prompt_target/common/prompt_target.py @@ -191,6 +191,10 @@ class PromptTarget(Identifiable): # Why this target type can't be saved even without a credential, or None when it can. not_saveable_reason: ClassVar[str | None] = None + # The parameter a server credential from the administrator's list fills with its key, and the parameter + # whose address must be the credential's endpoint; None when the target can't use one. + listed_credential_parameters: ClassVar[tuple[str, str] | None] = None + # Constructor parameters that choose where requests go or how they authenticate. A private # copy built from API input keeps its source's values for these, so a credential stays # with the endpoint it was configured for. diff --git a/pyrit/prompt_target/openai/openai_target.py b/pyrit/prompt_target/openai/openai_target.py index 9e6d58b62e..58f34789a0 100644 --- a/pyrit/prompt_target/openai/openai_target.py +++ b/pyrit/prompt_target/openai/openai_target.py @@ -166,14 +166,16 @@ class OpenAITarget(PromptTarget): {"api_key": None, "headers": "{}"} ) destination_parameters: ClassVar[Mapping[str, bool]] = MappingProxyType({"endpoint": True}) + listed_credential_parameters: ClassVar[tuple[str, str] | None] = ("api_key", "endpoint") environment_backed_parameters: ClassVar[frozenset[str]] = frozenset({"endpoint", "model_name"}) - # The OpenAI SDK adds these headers to every client it creates. - server_header_variables: ClassVar[tuple[str, ...]] = ("OPENAI_CUSTOM_HEADERS",) COPY_LOCKED_PARAMETER_NAMES: ClassVar[frozenset[str]] = frozenset( {"endpoint", "auth_mode", "api_key", "headers", "httpx_client_kwargs"} ) + # The OpenAI SDK adds these headers to every client it creates. + server_header_variables: ClassVar[tuple[str, ...]] = ("OPENAI_CUSTOM_HEADERS",) + model_name_environment_variable: str endpoint_environment_variable: str api_key_environment_variable: str diff --git a/pyrit/registry/registry_recipe_restore.py b/pyrit/registry/registry_recipe_restore.py index 03acbc0189..9668180629 100644 --- a/pyrit/registry/registry_recipe_restore.py +++ b/pyrit/registry/registry_recipe_restore.py @@ -27,13 +27,18 @@ ) from pyrit.registry.file_document_storage import DocumentStorageUnavailableError from pyrit.registry.instance_registry import RegistryNameTakenError, saved_entry_registration -from pyrit.registry.registry_recipe_rules import SavedEntryRefusedError, check_saved_entry_params +from pyrit.registry.registry_recipe_rules import ( + SavedEntryRefusedError, + check_saved_entry_params, + resolve_listed_credential, +) from pyrit.registry.registry_recipe_storage import RecipeListing, RegistryRecipeStorage, safe_failure_text if TYPE_CHECKING: from collections.abc import Mapping, Sequence from pyrit.models import Parameter + from pyrit.models.catalog import ServerCredential from pyrit.registry.registry import InstanceHoldingRegistry, Registry from pyrit.registry.registry_metadata import RegistryMetadata @@ -90,19 +95,22 @@ class RegistryRecipeRestorer: } _KIND_ORDER: ClassVar[tuple[RegistryRecipeKind, ...]] = tuple(RegistryRecipeKind) - def __init__(self, *, source: str | None = None) -> None: + def __init__(self, *, source: str | None = None, server_credentials: Sequence[ServerCredential] = ()) -> None: """ Initialize the restorer. Args: source (str | None): Local directory or Azure Blob URI holding the per-registry folders. Defaults to ``registry_recipes`` under the PyRIT configuration directory. + server_credentials (Sequence[ServerCredential]): The server credentials an administrator lets + saved targets use. Defaults to 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 self._storages = {kind: RegistryRecipeStorage(kind=kind, source=source) for kind in RegistryRecipeKind} + self._server_credentials = tuple(server_credentials) self._registry_types: dict[RegistryRecipeKind, Any] = { RegistryRecipeKind.TARGETS: TargetRegistry, RegistryRecipeKind.CONVERTERS: ConverterRegistry, @@ -290,7 +298,21 @@ def _component_references(self, *, ref: SavedEntryRef, recipe: ComponentRecipe) ) raise RecipeRejectedError(reason=RestoreFailureReason.MODULE_MISMATCH, message=message) parameters = self._class_parameters(registry=registry, name=recipe.class_name, cls=cls) - check_saved_entry_params(cls=cls, parameters=parameters, params=recipe.params, auth_mode=recipe.auth_mode) + listed_parameter = None + if recipe.server_credential is not None: + listed_parameter, _ = resolve_listed_credential( + cls=cls, + params=recipe.params, + name=recipe.server_credential, + server_credentials=self._server_credentials, + ) + check_saved_entry_params( + cls=cls, + parameters=parameters, + params=recipe.params, + auth_mode=recipe.auth_mode, + listed_credential_parameter=listed_parameter, + ) # As in the target API, a target may let callers set some path parameters, such as a working folder. allowed_paths = ( getattr(cls, "caller_path_parameters", frozenset()) diff --git a/pyrit/registry/registry_recipe_rules.py b/pyrit/registry/registry_recipe_rules.py index 7eaeaa21f0..e33e1b0ab2 100644 --- a/pyrit/registry/registry_recipe_rules.py +++ b/pyrit/registry/registry_recipe_rules.py @@ -11,12 +11,13 @@ from typing import TYPE_CHECKING, Any from urllib.parse import unquote, urlsplit -from pyrit.models.catalog import RestoreFailureReason +from pyrit.models.catalog import RestoreFailureReason, normalized_endpoint if TYPE_CHECKING: from collections.abc import Mapping, Sequence from pyrit.models import Parameter + from pyrit.models.catalog import ServerCredential _URL_SCHEMES = frozenset({"http", "https", "ws", "wss"}) _URL_QUERY_KEYS = frozenset({"api-version"}) @@ -42,7 +43,12 @@ def __init__(self, *, reason: RestoreFailureReason, message: str) -> None: def check_saved_entry_params( - *, cls: type, parameters: Sequence[Parameter], params: Mapping[str, Any], auth_mode: str | None = None + *, + cls: type, + parameters: Sequence[Parameter], + params: Mapping[str, Any], + auth_mode: str | None = None, + listed_credential_parameter: str | None = None, ) -> None: """ Refuse a recipe that a saved entry of ``cls`` can't hold. @@ -51,13 +57,15 @@ def check_saved_entry_params( and can't leave the entry to use one from this server: an empty key the class would read from the server's settings or identity, extra headers the server adds, a destination the server's settings choose, or a credential inside a URL. A saved target authenticates with Microsoft Entra ID - (``auth_mode`` ``"identity"``) or needs no key. + (``auth_mode`` ``"identity"``), needs no key, or names a server credential from the administrator's list. Args: cls (type): The class the recipe builds. parameters (Sequence[Parameter]): The class's constructor parameters. params (Mapping[str, Any]): The recipe's parameter values. auth_mode (str | None): The target recipe's auth mode. None means the API's default, ``"api_key"``. + listed_credential_parameter (str | None): The parameter a listed server credential fills at every + start, which isn't left to this server's own settings. Defaults to None. Raises: SavedEntryRefusedError: If the class can't be saved, or the values hold or would use a credential. @@ -65,10 +73,60 @@ def check_saved_entry_params( _check_class(cls) _check_server_headers(cls) _check_stored_credentials(parameters=parameters, params=params) - _check_server_fallbacks(cls=cls, params=params, auth_mode=auth_mode) + _check_server_fallbacks(cls=cls, params=params, auth_mode=auth_mode, provided=listed_credential_parameter) _check_destinations(cls=cls, params=params) +def resolve_listed_credential( + *, cls: type, params: Mapping[str, Any], name: str, server_credentials: Sequence[ServerCredential] +) -> tuple[str, str]: + """ + Find the server credential an entry names in the administrator's list, and the key it holds. + + Args: + cls (type): The class the entry is built from. + params (Mapping[str, Any]): The entry's parameter values. + name (str): The server credential's name. + server_credentials (Sequence[ServerCredential]): The administrator's list. + + Returns: + tuple[str, str]: The parameter that takes the key, and the key. + + Raises: + SavedEntryRefusedError: If the class can't use a server credential, the list has no such entry, the + entry's endpoint isn't the one the entry sends requests to, or the key isn't set on this server. + """ + declared: tuple[str, str] | None = getattr(cls, "listed_credential_parameters", None) + if declared is None: + raise SavedEntryRefusedError( + reason=RestoreFailureReason.UNSUPPORTED_CREDENTIAL, + message=f"'{cls.__name__}' can't use a server credential.", + ) + key_parameter, address_parameter = declared + credential = next((entry for entry in server_credentials if entry.name == name), None) + if credential is None: + raise SavedEntryRefusedError( + reason=RestoreFailureReason.UNSUPPORTED_CREDENTIAL, + message=f"This server has no server credential named '{name}'.", + ) + address = params.get(address_parameter) + if not isinstance(address, str) or normalized_endpoint(address) != normalized_endpoint(credential.endpoint): + raise SavedEntryRefusedError( + reason=RestoreFailureReason.UNSUPPORTED_CREDENTIAL, + message=( + f"Server credential '{name}' is only sent to {credential.endpoint}, so '{address_parameter}' " + "must be that address." + ), + ) + key = os.environ.get(credential.env_var) + if not key: + raise SavedEntryRefusedError( + reason=RestoreFailureReason.UNSUPPORTED_CREDENTIAL, + message=f"Server credential '{name}' isn't set on this server.", + ) + return key_parameter, key + + def check_saveable_class(cls: type) -> tuple[str, ...]: """ Return the auth modes a saved entry of ``cls`` can use, before any of its values are known. @@ -157,7 +215,9 @@ def _check_stored_credentials(*, parameters: Sequence[Parameter], params: Mappin ) -def _check_server_fallbacks(*, cls: type, params: Mapping[str, Any], auth_mode: str | None) -> None: +def _check_server_fallbacks( + *, cls: type, params: Mapping[str, Any], auth_mode: str | None, provided: str | None = None +) -> None: """ Refuse values that would let the entry use a credential from this server. @@ -182,7 +242,7 @@ def _check_server_fallbacks(*, cls: type, params: Mapping[str, Any], auth_mode: for name, turned_off in fallbacks.items(): value = params.get(name) if value in (None, ""): - if auth_mode == "none" or (auth_mode == "identity" and turned_off is None): + if name == provided or auth_mode == "none" or (auth_mode == "identity" and turned_off is None): continue message = f"'{name}' is empty, so '{cls.__name__}' can use this server's credential instead." if turned_off is not None: diff --git a/pyrit/registry/registry_recipe_save.py b/pyrit/registry/registry_recipe_save.py index 372beb8197..9eefaf7e47 100644 --- a/pyrit/registry/registry_recipe_save.py +++ b/pyrit/registry/registry_recipe_save.py @@ -103,6 +103,7 @@ async def prepare_saved_params_async( cls: type, params: Mapping[str, Any], auth_mode: str | None = None, + listed_credential_parameter: str | None = None, ) -> dict[str, Any]: """ Turn off the server values an entry to save would read, then refuse what it still can't hold. @@ -115,6 +116,8 @@ async def prepare_saved_params_async( 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. + listed_credential_parameter (str | None): The credential parameter a server credential the user picked + fills, which the recipe names instead of holding the key, or None. Returns: dict[str, Any]: The parameters to build and save the entry with. @@ -139,7 +142,13 @@ async def prepare_saved_params_async( metadata = await asyncio.to_thread(registry.get_class_metadata, cls) parameters = metadata.parameters try: - check_saved_entry_params(cls=cls, parameters=parameters, params=saved_params, auth_mode=auth_mode) + check_saved_entry_params( + cls=cls, + parameters=parameters, + params=saved_params, + auth_mode=auth_mode, + listed_credential_parameter=listed_credential_parameter, + ) except SavedEntryRefusedError as error: # The address needs fixing; creating the entry without saving it wouldn't make it usable. if error.reason is RestoreFailureReason.INVALID_RECIPE: diff --git a/pyrit/setup/configuration_loader.py b/pyrit/setup/configuration_loader.py index facf89522d..b78acdd009 100644 --- a/pyrit/setup/configuration_loader.py +++ b/pyrit/setup/configuration_loader.py @@ -24,6 +24,7 @@ from pyrit.common.text_helper import is_non_empty_string from pyrit.common.yaml_helper import safe_load_yaml from pyrit.models import class_name_to_snake_case +from pyrit.models.catalog import ServerCredential from pyrit.setup.environment_loading import validate_env_akv_strict from pyrit.setup.initialization import AZURE_SQL, IN_MEMORY, SQLITE, initialize_pyrit_async, reinitialize_pyrit_async @@ -117,6 +118,8 @@ class ConfigurationLoader(YamlLoadable): followed by a blob prefix, used to persist scenario suites. registry_recipes_source: Local directory or Azure Blob container URI, optionally followed by a blob prefix, used to persist saved targets, converters, scorers, and techniques. + server_credentials: Keys in this server's environment that users can pick for targets, each with a + name users see, the environment variable that holds it, and the only endpoint it's sent to. silent: Whether to suppress initialization messages. seed: Optional root seed for deterministic converter operations. operator: Name for the current operator, e.g. a team or username. @@ -173,6 +176,7 @@ class ConfigurationLoader(YamlLoadable): scenario_presets_source: str | None = None scenario_suites_source: str | None = None registry_recipes_source: str | None = None + server_credentials: list[ServerCredential] = field(default_factory=list) target_upload_directory: str | None = None server: dict[str, Any] | None = None extensions: dict[str, Any] = field(default_factory=dict) @@ -206,6 +210,7 @@ def __post_init__(self) -> None: self._validate_scenario_presets_source() self._validate_scenario_suites_source() self._validate_registry_recipes_source() + self._normalize_server_credentials() self._validate_target_upload_directory() self._normalize_server() @@ -255,6 +260,23 @@ def _validate_registry_recipes_source(self) -> None: """ self._validate_document_source(name="registry_recipes_source", value=self.registry_recipes_source) + def _normalize_server_credentials(self) -> None: + """ + Validate the server credentials users can pick, and turn each entry into a ``ServerCredential``. + + Raises: + ValueError: If the list or an entry is malformed, or two entries share a name. + """ + # The YAML gives plain mappings, which become ``ServerCredential`` entries here. + entries: Any = self.server_credentials + if not isinstance(entries, list): + raise ValueError("server_credentials must be a list of entries with name, env_var, and endpoint.") + credentials = [ServerCredential.model_validate(entry) for entry in entries] + names = [credential.name for credential in credentials] + if len(set(names)) != len(names): + raise ValueError("Each server credential needs its own name.") + self.server_credentials = credentials + @staticmethod def _validate_document_source(*, name: str, value: Any) -> None: """ diff --git a/tests/end_to_end/browser_config.yaml b/tests/end_to_end/browser_config.yaml index 0f6955398f..625a57dff7 100644 --- a/tests/end_to_end/browser_config.yaml +++ b/tests/end_to_end/browser_config.yaml @@ -11,3 +11,8 @@ initializers: initialization_scripts: - tests/end_to_end/browser_initializer.py operation: browser_proposed +# A key users can pick by name for OpenAI targets. The value set in playwright.config.ts is never sent anywhere. +server_credentials: + - name: e2e_listed + env_var: PYRIT_E2E_LISTED_KEY + endpoint: https://e2e-listed.example.test/v1 diff --git a/tests/unit/backend/test_api_routes.py b/tests/unit/backend/test_api_routes.py index d32e897e97..5d3133c129 100644 --- a/tests/unit/backend/test_api_routes.py +++ b/tests/unit/backend/test_api_routes.py @@ -60,7 +60,7 @@ from pyrit.memory import MemoryInterface from pyrit.memory.memory_interface import AttackStateConflictError from pyrit.models import AttackOutcome, ConverterIdentifier, MessagePiece, Score, TargetCapabilities, TargetIdentifier -from pyrit.models.catalog import SavedEntryOwner, TargetInstance +from pyrit.models.catalog import SavedEntryOwner, ServerCredential, TargetInstance from pyrit.registry import NotSaveableError, SavedEntryConflictError, SavedEntryStorageError @@ -1647,6 +1647,26 @@ def test_saved_entry_owner_is_the_signed_in_user(self, name: str, expected: str) assert _saved_entry_owner(request) == SavedEntryOwner(oid="user-oid", name=expected) assert _saved_entry_owner(Request({"type": "http"})) is None + def test_types_and_create_pass_the_server_credentials_users_can_pick(self, client: TestClient) -> None: + credentials = [ServerCredential(name="contoso", env_var="CONTOSO_KEY", endpoint="https://api.contoso.com/v1")] + with ( + patch("pyrit.backend.routes.targets.get_target_service") as mock_get_service, + patch.object(client.app.state, "server_credentials", credentials, create=True), + ): + service = mock_get_service.return_value + service.list_target_types_async = AsyncMock(return_value=TargetTypeResponse(items=[])) + service.create_target_async = AsyncMock(side_effect=ValueError("stop")) + + client.get("/api/targets/types") + client.post( + "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/api/targets", + json={"name": "contoso_chat", "type": "OpenAIChatTarget", "params": {}, "server_credential": "contoso"}, + ) + + assert service.list_target_types_async.call_args.kwargs["server_credentials"] == credentials + assert service.create_target_async.call_args.kwargs["server_credentials"] == credentials + assert service.create_target_async.call_args.kwargs["request"].server_credential == "contoso" + def test_create_target_passes_admin_flag_from_request(self, client: TestClient) -> None: """The route resolves administrator access and forwards it to the service.""" with ( diff --git a/tests/unit/backend/test_runtime_lifecycle.py b/tests/unit/backend/test_runtime_lifecycle.py index 933a1b0c8b..5a19312b80 100644 --- a/tests/unit/backend/test_runtime_lifecycle.py +++ b/tests/unit/backend/test_runtime_lifecycle.py @@ -35,7 +35,7 @@ from pyrit.backend.services.technique_service import get_technique_service from pyrit.memory import CentralMemory, MemoryInterface from pyrit.models import ScenarioRunState -from pyrit.models.catalog import ComponentRecipe, RunScenarioRequest +from pyrit.models.catalog import ComponentRecipe, RunScenarioRequest, ServerCredential 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 @@ -738,12 +738,16 @@ async def test_management_publishes_target_upload_directory(tmp_path: Path) -> N env_files=[], target_upload_directory=str(tmp_path), registry_recipes_source=str(tmp_path / "recipes"), + server_credentials=[{"name": "contoso", "env_var": "CONTOSO_KEY", "endpoint": "https://api.contoso.com/v1"}], ) await service._management_async(config) assert app.state.target_upload_directory == str(tmp_path) assert app.state.registry_recipes_source == str(tmp_path / "recipes") + assert app.state.server_credentials == [ + ServerCredential(name="contoso", env_var="CONTOSO_KEY", endpoint="https://api.contoso.com/v1") + ] async def test_invalid_cold_configuration_requires_restart_but_retains_raw_repair(tmp_path: Path) -> None: @@ -757,6 +761,7 @@ async def test_invalid_cold_configuration_requires_restart_but_retains_raw_repai assert not app.state.allow_custom_initializers assert app.state.target_upload_directory is None assert app.state.registry_recipes_source is None + assert app.state.server_credentials == [] assert app.state.environment_file_service is None content, version = await source.read_with_version_async() assert content == "broken: [" @@ -1057,10 +1062,15 @@ def _save_recipe(root: Path, *, kind: str, name: str, document: dict[str, object async def _start_with_recipes_async( - runtime: RuntimeLifecycle, *, recipes: Path, initialize: Callable[..., object] | None = None + runtime: RuntimeLifecycle, + *, + recipes: Path, + initialize: Callable[..., object] | None = None, + server_credentials: list[ServerCredential] | None = None, ) -> None: config = await runtime._load_async() config.registry_recipes_source = str(recipes) + config.server_credentials = server_credentials or [] with ( patch.object(config, "initialize_pyrit_async", AsyncMock(side_effect=initialize)), patch.object(lifecycle_module, "get_scenario_run_service", return_value=MagicMock(spec=ScenarioRunService)), @@ -1130,6 +1140,33 @@ 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_restores_a_target_that_names_a_server_credential_async( + runtime: RuntimeLifecycle, tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + monkeypatch.setenv("CONTOSO_TEST_KEY", "listed-key") + credentials = [ServerCredential(name="contoso", env_var="CONTOSO_TEST_KEY", endpoint="https://api.contoso.com/v1")] + recipes = tmp_path / "recipes" + _save_recipe( + recipes, + kind="targets", + name="contoso_chat", + document={ + "class_module": OpenAIChatTarget.__module__, + "class_name": "OpenAIChatTarget", + "params": {"endpoint": "https://api.contoso.com/v1", "model_name": "gpt-4o", "headers": "{}"}, + "server_credential": "contoso", + }, + ) + + await _start_with_recipes_async(runtime, recipes=recipes, server_credentials=credentials) + + assert (runtime.state, runtime.outcome) == ("ready", "success") + restored = TargetRegistry.get_registry_singleton().instances.get("contoso_chat") + assert restored is not None + assert restored._api_key == "listed-key" # type: ignore[attr-defined] + + class _LoopBoundTarget(MockPromptTarget): """A target whose constructor needs the running event loop, as HuggingFaceChatTarget's does.""" diff --git a/tests/unit/backend/test_target_service.py b/tests/unit/backend/test_target_service.py index a8fd452df4..4ddcd511d1 100644 --- a/tests/unit/backend/test_target_service.py +++ b/tests/unit/backend/test_target_service.py @@ -15,6 +15,7 @@ from unittest.mock import AsyncMock, MagicMock, patch import pytest +from pydantic import ValidationError from pyrit.backend.models import CreateTargetRequest from pyrit.backend.models.targets import TargetSaveabilityRequest @@ -26,7 +27,9 @@ RegistryEntryOrigin, RegistryRecipeKind, RegistryRestoreReport, + RestoreFailureReason, SavedEntryOwner, + ServerCredential, TargetInstance, ) from pyrit.models.component_spec import SourceInstanceSpec @@ -1813,11 +1816,13 @@ def _saved_document(source: Path, name: str) -> dict[str, Any]: return json.loads((source / "targets" / f"{name}.json").read_text()) -async def _restore(source: Path) -> RegistryRestoreReport: +async def _restore(source: Path, *, server_credentials: list[ServerCredential] | None = None) -> RegistryRestoreReport: """Restore the saved targets through the API's create, as startup does.""" get_target_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) + credentials = server_credentials or [] + build_async = partial(build_saved_entry_async, upload_directory=None, server_credentials=credentials) + restorer = RegistryRecipeRestorer(source=str(source), server_credentials=credentials) + return await restorer.restore_async(build_async=build_async) @pytest.mark.usefixtures("sqlite_instance") @@ -2063,6 +2068,171 @@ async def test_lists_where_each_target_comes_from(self, tmp_path: Path) -> None: assert fetched.origin is RegistryEntryOrigin.TEMPORARY +_CONTOSO = ServerCredential(name="contoso", env_var="CONTOSO_TEST_KEY", endpoint="https://api.contoso.com/v1") + + +def _listed_request( + *, persist: bool = False, endpoint: str = "https://api.contoso.com/v1", target_type: str = "OpenAIChatTarget" +) -> CreateTargetRequest: + return CreateTargetRequest( + name="contoso_chat", + type=target_type, + params={"endpoint": endpoint, "model_name": "gpt-4o"} if target_type == "OpenAIChatTarget" else {}, + server_credential="contoso", + persist=persist, + ) + + +@pytest.mark.usefixtures("sqlite_instance") +class TestServerCredentials: + async def test_builds_a_target_with_a_listed_key_without_returning_it( + self, monkeypatch: pytest.MonkeyPatch + ) -> None: + monkeypatch.setenv("CONTOSO_TEST_KEY", "listed-key") + service = TargetService() + + target = await service.create_target_async(request=_listed_request(), server_credentials=[_CONTOSO]) + + target_obj = service.get_target_object(target_registry_name="contoso_chat") + assert target_obj._api_key == "listed-key" # type: ignore[attr-defined] + assert target.origin is RegistryEntryOrigin.TEMPORARY + assert "listed-key" not in target.model_dump_json() + + async def test_saves_the_credential_name_and_restore_reads_the_key_again( + self, monkeypatch: pytest.MonkeyPatch, tmp_path: Path + ) -> None: + monkeypatch.setenv("CONTOSO_TEST_KEY", "listed-key") + service = TargetService() + + target = await service.create_target_async( + request=_listed_request(persist=True), recipes_source=str(tmp_path), server_credentials=[_CONTOSO] + ) + + assert target.origin is RegistryEntryOrigin.SAVED + assert _saved_document(tmp_path, "contoso_chat") == { + "schema_version": 1, + "class_module": "pyrit.prompt_target.openai.openai_chat_target", + "class_name": "OpenAIChatTarget", + "auth_mode": "api_key", + "params": {"endpoint": "https://api.contoso.com/v1", "model_name": "gpt-4o", "headers": "{}"}, + "server_credential": "contoso", + } + monkeypatch.setenv("CONTOSO_TEST_KEY", "rotated-key") + TargetRegistry.reset_registry_singleton() + assert (await _restore(tmp_path, server_credentials=[_CONTOSO])).failures == [] + restored = TargetRegistry.get_registry_singleton().instances.get("contoso_chat") + assert restored is not None + assert restored._api_key == "rotated-key" # type: ignore[attr-defined] + + @pytest.mark.parametrize( + ("changes", "message"), + [ + ({"credentials": []}, "This server has no server credential named 'contoso'."), + ( + {"endpoint": "https://api.contoso.com.evil.example/v1"}, + ( + "Server credential 'contoso' is only sent to https://api.contoso.com/v1, so 'endpoint' must be " + "that address." + ), + ), + ({"unset": True}, "Server credential 'contoso' isn't set on this server."), + ({"target_type": "TextTarget"}, "'TextTarget' can't use a server credential."), + ], + ) + async def test_refuses_a_credential_it_cant_use_for_this_target( + self, monkeypatch: pytest.MonkeyPatch, tmp_path: Path, changes: dict[str, Any], message: str + ) -> None: + if changes.get("unset"): + monkeypatch.delenv("CONTOSO_TEST_KEY", raising=False) + else: + monkeypatch.setenv("CONTOSO_TEST_KEY", "listed-key") + request = _listed_request( + persist=True, + endpoint=changes.get("endpoint", "https://api.contoso.com/v1"), + target_type=changes.get("target_type", "OpenAIChatTarget"), + ) + + with pytest.raises(ValueError) as refusal: + await TargetService().create_target_async( + request=request, recipes_source=str(tmp_path), server_credentials=changes.get("credentials", [_CONTOSO]) + ) + + assert str(refusal.value) == message + assert TargetRegistry.get_registry_singleton().instances.get("contoso_chat") is None + assert not (tmp_path / "targets").exists() + + @pytest.mark.parametrize( + ("credentials", "unset", "message"), + [ + ([], False, "This server has no server credential named 'contoso'."), + ([_CONTOSO], True, "Server credential 'contoso' isn't set on this server."), + ], + ) + async def test_a_saved_target_doesnt_restore_without_its_listed_key( + self, + monkeypatch: pytest.MonkeyPatch, + tmp_path: Path, + credentials: list[ServerCredential], + unset: bool, + message: str, + ) -> None: + monkeypatch.setenv("CONTOSO_TEST_KEY", "listed-key") + await TargetService().create_target_async( + request=_listed_request(persist=True), recipes_source=str(tmp_path), server_credentials=[_CONTOSO] + ) + if unset: + monkeypatch.delenv("CONTOSO_TEST_KEY") + TargetRegistry.reset_registry_singleton() + + failures = (await _restore(tmp_path, server_credentials=credentials)).failures + + assert [(failure.name, failure.reason, failure.message) for failure in failures] == [ + ("contoso_chat", RestoreFailureReason.UNSUPPORTED_CREDENTIAL, message) + ] + assert "contoso_chat" not in TargetRegistry.get_registry_singleton().instances.get_names() + + async def test_types_list_the_credentials_each_type_can_use(self) -> None: + response = await TargetService().list_target_types_async(server_credentials=[_CONTOSO]) + + choices = {item.target_type: [(c.name, c.endpoint) for c in item.server_credentials] for item in response.items} + assert choices["OpenAIChatTarget"] == [("contoso", "https://api.contoso.com/v1")] + assert choices["TextTarget"] == [] + assert "CONTOSO_TEST_KEY" not in response.model_dump_json() + + +@pytest.mark.parametrize( + ("fields", "message"), + [ + ({"params": {"api_key": "typed-key"}}, "Send either an api_key or a server_credential, not both"), + ({"auth_mode": "identity"}, "server_credential needs auth_mode 'api_key'"), + ({"server_credential": "Contoso"}, "server_credential"), + ( + {"register": False, "source": {"source_name": "startup_chat", "source_hash": "abc123", "params": {}}}, + "server_credential can't be used with source", + ), + ], +) +def test_a_request_with_a_server_credential_sends_no_key_of_its_own(fields: dict[str, Any], message: str) -> None: + with pytest.raises(ValidationError, match=message): + CreateTargetRequest.model_validate( + {"name": "contoso_chat", "type": "OpenAIChatTarget", "params": {}, "server_credential": "contoso", **fields} + ) + + +@pytest.mark.parametrize( + ("fields", "message"), + [ + ({"params": {"api_key": "typed-key"}}, "Send either an api_key or a server_credential, not both"), + ({"auth_mode": "identity"}, "server_credential needs auth_mode 'api_key'"), + ], +) +def test_a_saveability_check_refuses_a_server_credential_as_create_does(fields: dict[str, Any], message: str) -> None: + with pytest.raises(ValidationError, match=message): + TargetSaveabilityRequest.model_validate( + {"type": "OpenAIChatTarget", "params": {}, "server_credential": "contoso", **fields} + ) + + @pytest.mark.usefixtures("sqlite_instance") class TestCheckSaveability: async def test_answers_as_saving_would_without_building_anything(self) -> None: @@ -2097,3 +2267,14 @@ async def test_refuses_a_request_that_creating_would_refuse(self) -> None: type="OpenAIChatTarget", params={"endpoint": _AZURE_ENDPOINT}, auth_mode="identity" ) ) + + async def test_answers_that_a_picked_server_credential_can_be_saved(self, monkeypatch: pytest.MonkeyPatch) -> None: + monkeypatch.setenv("CONTOSO_TEST_KEY", "listed-key") + params = {"endpoint": "https://api.contoso.com/v1", "model_name": "gpt-4o"} + + answer = await TargetService().check_saveability_async( + request=TargetSaveabilityRequest(type="OpenAIChatTarget", params=params, server_credential="contoso"), + server_credentials=[_CONTOSO], + ) + + assert answer.not_saveable_reason is None diff --git a/tests/unit/models/catalog/test_server_credential.py b/tests/unit/models/catalog/test_server_credential.py new file mode 100644 index 0000000000..229a49f8b3 --- /dev/null +++ b/tests/unit/models/catalog/test_server_credential.py @@ -0,0 +1,72 @@ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT license. + +import pytest +from pydantic import ValidationError + +from pyrit.models.catalog import ServerCredential, normalized_endpoint + + +@pytest.mark.parametrize( + ("left", "right"), + [ + ("https://API.Contoso.com/v1", "https://api.contoso.com/v1/"), + ("https://api.contoso.com:443/v1", "https://api.contoso.com/v1"), + ("http://localhost:80/v1", "http://LOCALHOST/v1"), + ("https://[2001:DB8::1]:443/v1", "https://[2001:db8::1]/v1/"), + ], +) +def test_normalized_endpoint_treats_the_same_address_alike(left: str, right: str) -> None: + assert normalized_endpoint(left) == normalized_endpoint(right) + + +@pytest.mark.parametrize( + ("left", "right"), + [ + ("https://api.contoso.com/v1", "https://api.contoso.com/v2"), + ("https://api.contoso.com/V1", "https://api.contoso.com/v1"), + ("https://api.contoso.com:8443/v1", "https://api.contoso.com/v1"), + ("http://api.contoso.com/v1", "https://api.contoso.com/v1"), + ("https://api.contoso.com.evil.example/v1", "https://api.contoso.com/v1"), + ("https://[2001:db8::1:444]/v1", "https://[2001:db8::1]:444/v1"), + ("https://api.contoso.com/v1?api-version=1", "https://api.contoso.com/v1"), + ("https://api.contoso.com/v1#part", "https://api.contoso.com/v1"), + ("https://someone@api.contoso.com/v1", "https://api.contoso.com/v1"), + ("https://evil.example\\@api.contoso.com/v1", "https://api.contoso.com/v1"), + ], +) +def test_normalized_endpoint_tells_different_addresses_apart(left: str, right: str) -> None: + assert normalized_endpoint(left) != normalized_endpoint(right) + + +def test_a_server_credential_names_a_variable_and_one_endpoint() -> None: + credential = ServerCredential(name="contoso", env_var="CONTOSO_KEY", endpoint="https://api.contoso.com/v1") + + assert (credential.name, credential.env_var, credential.endpoint) == ( + "contoso", + "CONTOSO_KEY", + "https://api.contoso.com/v1", + ) + + +@pytest.mark.parametrize( + "fields", + [ + {"name": "Contoso"}, + {"env_var": "CONTOSO-KEY"}, + {"endpoint": "api.contoso.com/v1"}, + {"endpoint": "ftp://api.contoso.com/v1"}, + {"endpoint": "https://user:pass@api.contoso.com/v1"}, + {"endpoint": "https://api.contoso.com/v1?key=secret"}, + {"endpoint": "https://api.contoso.com/v1#key"}, + {"endpoint": "https://api.contoso.com:99999/v1"}, + {"endpoint": "https://api.contoso.com:port/v1"}, + {"endpoint": "https://api.contoso.com:0/v1"}, + {"extra": "field"}, + ], +) +def test_a_server_credential_refuses_a_bad_entry(fields: dict[str, str]) -> None: + with pytest.raises(ValidationError): + ServerCredential.model_validate( + {"name": "contoso", "env_var": "CONTOSO_KEY", "endpoint": "https://api.contoso.com/v1", **fields} + ) diff --git a/tests/unit/registry/test_registry_recipe_rules.py b/tests/unit/registry/test_registry_recipe_rules.py index be82ad5704..5dcbfd3110 100644 --- a/tests/unit/registry/test_registry_recipe_rules.py +++ b/tests/unit/registry/test_registry_recipe_rules.py @@ -7,12 +7,13 @@ import pytest -from pyrit.models.catalog import RestoreFailureReason +from pyrit.models.catalog import RestoreFailureReason, ServerCredential from pyrit.registry import ConverterRegistry, TargetRegistry from pyrit.registry.registry_recipe_rules import ( SavedEntryRefusedError, check_saveable_class, check_saved_entry_params, + resolve_listed_credential, ) _ENDPOINT = "https://contoso.openai.azure.com/openai/v1" @@ -451,6 +452,136 @@ def test_check_saveable_class_agrees_with_the_check_a_save_runs() -> None: ) +_LISTED = ServerCredential(name="contoso", env_var="CONTOSO_TEST_KEY", endpoint="https://api.contoso.com/v1") +_MISMATCH = ( + "Server credential 'contoso' is only sent to https://api.contoso.com/v1, so 'endpoint' must be that address." +) + + +def _check_with_listed_key(params: dict[str, Any]) -> None: + registry = TargetRegistry.get_registry_singleton() + cls = registry.get_class("OpenAIChatTarget") + check_saved_entry_params( + cls=cls, + parameters=registry.get_class_metadata(cls).parameters, + params=params, + listed_credential_parameter="api_key", + ) + + +def test_check_saved_entry_params_accepts_an_empty_key_a_server_credential_fills() -> None: + _check_with_listed_key({"auth_mode": "api_key", "endpoint": "https://api.contoso.com/v1", "headers": "{}"}) + + +@pytest.mark.parametrize( + ("params", "message"), + [ + ( + {"auth_mode": "api_key", "endpoint": "https://api.contoso.com/v1", "headers": "{}", "api_key": "typed"}, + "Saved entries can't hold credentials ('api_key').", + ), + ( + {"auth_mode": "api_key", "endpoint": "https://api.contoso.com/v1"}, + ( + "'headers' is empty, so 'OpenAIChatTarget' can use this server's credential instead. " + "Saved entries set it to '{}'." + ), + ), + ], +) +def test_check_saved_entry_params_still_refuses_what_a_server_credential_doesnt_fill( + params: dict[str, Any], message: str +) -> None: + with pytest.raises(SavedEntryRefusedError) as refusal: + _check_with_listed_key(params) + + assert str(refusal.value) == message + + +@pytest.mark.parametrize("class_name", _OPENAI_CLASSES) +def test_openai_targets_take_a_server_credential_as_their_key_for_their_endpoint(class_name: str) -> None: + cls = TargetRegistry.get_registry_singleton().get_class(class_name) + + assert cls.listed_credential_parameters == ("api_key", "endpoint") + + +@pytest.mark.parametrize("endpoint", ["https://api.contoso.com/v1", "HTTPS://API.Contoso.com:443/v1/"]) +def test_resolve_listed_credential_returns_the_key_for_its_endpoint( + monkeypatch: pytest.MonkeyPatch, endpoint: str +) -> None: + monkeypatch.setenv("CONTOSO_TEST_KEY", "listed-key") + cls = TargetRegistry.get_registry_singleton().get_class("OpenAIChatTarget") + + resolved = resolve_listed_credential( + cls=cls, params={"endpoint": endpoint}, name="contoso", server_credentials=[_LISTED] + ) + + assert resolved == ("api_key", "listed-key") + + +@pytest.mark.parametrize( + ("class_name", "params", "credentials", "message"), + [ + ("TextTarget", {}, [_LISTED], "'TextTarget' can't use a server credential."), + ( + "OpenAIChatTarget", + {"endpoint": "https://api.contoso.com/v1"}, + [ServerCredential(name="fabrikam", env_var="CONTOSO_TEST_KEY", endpoint="https://api.contoso.com/v1")], + "This server has no server credential named 'contoso'.", + ), + ("OpenAIChatTarget", {"endpoint": "https://api.contoso.com/v2"}, [_LISTED], _MISMATCH), + ("OpenAIChatTarget", {"endpoint": "http://api.contoso.com/v1"}, [_LISTED], _MISMATCH), + ("OpenAIChatTarget", {"endpoint": "https://api.contoso.com:8443/v1"}, [_LISTED], _MISMATCH), + ("OpenAIChatTarget", {"endpoint": "https://api.contoso.com.example.test/v1"}, [_LISTED], _MISMATCH), + ("OpenAIChatTarget", {"endpoint": "https://api.contoso.com/v1?api-version=1"}, [_LISTED], _MISMATCH), + ( + "OpenAIChatTarget", + {"endpoint": "https://[2001:db8::1:444]/v1"}, + [ServerCredential(name="contoso", env_var="CONTOSO_TEST_KEY", endpoint="https://[2001:db8::1]:444/v1")], + ( + "Server credential 'contoso' is only sent to https://[2001:db8::1]:444/v1, so 'endpoint' must be " + "that address." + ), + ), + ("OpenAIChatTarget", {}, [_LISTED], _MISMATCH), + ], +) +def test_resolve_listed_credential_refuses_a_credential_this_entry_cant_use( + monkeypatch: pytest.MonkeyPatch, + class_name: str, + params: dict[str, Any], + credentials: list[ServerCredential], + message: str, +) -> None: + monkeypatch.setenv("CONTOSO_TEST_KEY", "listed-key") + cls = TargetRegistry.get_registry_singleton().get_class(class_name) + + with pytest.raises(SavedEntryRefusedError) as refusal: + resolve_listed_credential(cls=cls, params=params, name="contoso", server_credentials=credentials) + + assert refusal.value.reason is RestoreFailureReason.UNSUPPORTED_CREDENTIAL + assert str(refusal.value) == message + + +@pytest.mark.parametrize("value", [None, ""]) +def test_resolve_listed_credential_refuses_a_key_that_isnt_set( + monkeypatch: pytest.MonkeyPatch, value: str | None +) -> None: + if value is None: + monkeypatch.delenv("CONTOSO_TEST_KEY", raising=False) + else: + monkeypatch.setenv("CONTOSO_TEST_KEY", value) + cls = TargetRegistry.get_registry_singleton().get_class("OpenAIChatTarget") + + with pytest.raises(SavedEntryRefusedError) as refusal: + resolve_listed_credential( + cls=cls, params={"endpoint": "https://api.contoso.com/v1"}, name="contoso", server_credentials=[_LISTED] + ) + + assert refusal.value.reason is RestoreFailureReason.UNSUPPORTED_CREDENTIAL + assert str(refusal.value) == "Server credential 'contoso' isn't set on this server." + + @pytest.mark.parametrize("class_name", _OPENAI_CLASSES) def test_check_saveable_class_refuses_an_openai_class_while_the_server_sets_sdk_headers( class_name: str, monkeypatch: pytest.MonkeyPatch diff --git a/tests/unit/setup/test_configuration_loader.py b/tests/unit/setup/test_configuration_loader.py index ffb95896c4..614c39989a 100644 --- a/tests/unit/setup/test_configuration_loader.py +++ b/tests/unit/setup/test_configuration_loader.py @@ -110,6 +110,43 @@ def test_registry_recipes_source_loads_from_yaml(self, tmp_path: pathlib.Path) - assert config.registry_recipes_source == "https://account.blob.core.windows.net/pyrit-storage/registry-recipes" assert ConfigurationLoader().registry_recipes_source is None + def test_server_credentials_load_from_yaml(self, tmp_path: pathlib.Path) -> None: + """Test loading the server credentials users can pick, by name, variable, and endpoint.""" + config_path = tmp_path / "config.yaml" + config_path.write_text( + "server_credentials:\n" + " - name: contoso\n" + " env_var: CONTOSO_KEY\n" + " endpoint: https://api.contoso.com/v1\n", + encoding="utf-8", + ) + + config = ConfigurationLoader.from_yaml_file(config_path) + + assert [(entry.name, entry.env_var, entry.endpoint) for entry in config.server_credentials] == [ + ("contoso", "CONTOSO_KEY", "https://api.contoso.com/v1") + ] + assert ConfigurationLoader().server_credentials == [] + + @pytest.mark.parametrize( + ("entries", "message"), + [ + ({"name": "contoso"}, "server_credentials must be a list"), + ( + [ + {"name": "contoso", "env_var": "A_KEY", "endpoint": "https://a.example/v1"}, + {"name": "contoso", "env_var": "B_KEY", "endpoint": "https://b.example/v1"}, + ], + "Each server credential needs its own name", + ), + ([{"name": "contoso", "env_var": "A_KEY", "endpoint": "https://user:pw@a.example/v1"}], "endpoint"), + ], + ) + def test_server_credentials_refuse_a_bad_list(self, entries: object, message: str) -> None: + """Test refusing a malformed list, a repeated name, and an endpoint that can carry a credential.""" + with pytest.raises(ValueError, match=message): + ConfigurationLoader(server_credentials=entries) # type: ignore[arg-type] + @pytest.mark.parametrize("invalid_value", ["", " ", 42]) def test_registry_recipes_source_rejects_invalid_value(self, invalid_value: object) -> None: """Test rejecting empty or non-string sources for saved registry entries."""