diff --git a/.github/instructions/output.instructions.md b/.github/instructions/output.instructions.md index dcd227e52b..639dd1010d 100644 --- a/.github/instructions/output.instructions.md +++ b/.github/instructions/output.instructions.md @@ -68,3 +68,14 @@ await output_attack_async(result, format="pretty") `helpers.py` resolves `format` → printer class, `sink` → Sink, and calls `write_async`. When reviewing: if a new domain printer is added without a helper function, request one. + +## Publishers + +Finding publishers (`pyrit/output/finding_publisher/`) write findings to another system and return what they created. They aren't printers: they have no sink and no `helpers.py` function, and they never touch `CentralMemory`. Callers pass a `FindingSelection` from `build_finding_selection_async`, and pass `publish_async` a `link_for` when evidence should link back. The planner lays the selection out with `build_finding_report`, so each item's evidence matches the exports. + +- Subclass `FindingPublisher` and implement `_open_destination_async` and `_create_item_async`. The base class owns planning, value checks, the plan digest, the create loop, outcome accounting and the run summary; don't rebuild them in a subclass. +- Use async I/O, and keep every request within a timeout and the caller's `deadline`. +- Once the base calls `_create_item_async`, every outcome goes in the result and only cancellation escapes. Raise `FindingPublishCreateError` with `outcome_unknown=False` only when nothing was sent or the response proves nothing was created, and never retry a create that might have succeeded. +- Never log tokens, names, emails, titles, field values or the service's message text. + +When reviewing: reject a subclass that overrides `preview_async`, `publish_async` or the create loop. diff --git a/doc/code/output/0_output.ipynb b/doc/code/output/0_output.ipynb index e828edaa7d..e49d56d676 100644 --- a/doc/code/output/0_output.ipynb +++ b/doc/code/output/0_output.ipynb @@ -763,6 +763,226 @@ "scenario result ID) to a printer in `pyrit.output.scenario_suite_result`." ] }, + { + "cell_type": "markdown", + "id": "printing-finding-reports", + "metadata": {}, + "source": [ + "## Printing Finding Reports\n", + "\n", + "`build_finding_selection_async` reads an Operation's selected findings from memory, each with all\n", + "of its sub-findings and evidence, as CoPyRIT's findings export does. `build_finding_report` lays\n", + "the selection out as a report, and `output_finding_report_async` prints it.\n", + "\n", + "Pass `link_for` to `build_finding_report` to link each piece of evidence whose conversation can be\n", + "opened, for example to your dashboard. Without it, the report lists evidence without links. Pass\n", + "`max_findings` to `build_finding_selection_async` to cap the selection, counting sub-findings." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "printing-finding-reports-code", + "metadata": {}, + "outputs": [ + { + "data": { + "text/markdown": [ + "# Findings - Output guide\n", + "\n", + "Evidence is listed as references; transcripts are not included.\n", + "\n", + "## 1 Joke ranks people by height\n", + "\n", + "**Severity:** Low\n", + "\n", + "**Evidence:** none attached\n" + ], + "text/plain": [ + "" + ] + }, + "metadata": {}, + "output_type": "display_data" + } + ], + "source": [ + "from pyrit.models import Finding, Operation\n", + "from pyrit.output import build_finding_report, build_finding_selection_async, output_finding_report_async\n", + "from pyrit.setup.finding_fields import get_active_finding_fields\n", + "\n", + "operation = await memory.add_operation_async(Operation(name=\"Output guide\"))\n", + "finding = await memory.add_finding_async(\n", + " finding=Finding(operation_id=operation.id, title=\"Joke ranks people by height\", severity=\"low\")\n", + ")\n", + "\n", + "fields = get_active_finding_fields()\n", + "selection = await build_finding_selection_async(operation_id=operation.id, finding_ids=[finding.id], fields=fields)\n", + "await output_finding_report_async(build_finding_report(selection=selection, fields=fields))" + ] + }, + { + "cell_type": "markdown", + "id": "publishing-findings", + "metadata": {}, + "source": [ + "## Publishing Findings\n", + "\n", + "A finding publisher creates an item for each selected finding in another system, under an existing\n", + "item that you name, such as a parent work item. `preview_async` shows where every finding would go\n", + "and writes nothing. `publish_async` creates the items, parents first, and reports every finding's\n", + "outcome: created, skipped because it wasn't demonstrated, failed (saying whether the item might\n", + "exist anyway), or not attempted. Each publish has a run ID that the created items record, and\n", + "publishing again creates new items.\n", + "\n", + "```python\n", + "from pyrit.output import build_finding_selection_async\n", + "from pyrit.setup.finding_fields import get_active_finding_fields\n", + "\n", + "fields = get_active_finding_fields()\n", + "selection = await build_finding_selection_async(operation_id=operation_id, finding_ids=finding_ids, fields=fields)\n", + "preview = await publisher.preview_async(selection=selection, fields=fields, destination=\"12345\")\n", + "result = await publisher.publish_async(\n", + " selection=selection, fields=fields, destination=\"12345\", link_for=link_for, expected_plan_digest=preview.plan_digest\n", + ")\n", + "```\n", + "\n", + "Pass the preview's `plan_digest` so the publish creates only what the preview showed; if the findings\n", + "or the destination changed, it raises `FindingPublishPlanChangedError` before writing anything. Pass\n", + "`link_for` to `publish_async` to link each piece of evidence, as `build_finding_report` does. Links\n", + "don't change the digest, so the preview takes none.\n", + "\n", + "To offer a publisher in CoPyRIT, register it from an initializer with\n", + "`FindingPublisherRegistry.get_registry_singleton().instances.register(publisher, name=...)`. The operation\n", + "page then shows **Publish findings**, and the backend links evidence to `PYRIT_PUBLIC_ORIGIN`.\n", + "\n", + "`AzureDevOpsFindingPublisher` creates Azure DevOps work items under an existing work item, with a\n", + "token from `DefaultAzureCredential` unless you pass `token_provider`. Map each finding field and level\n", + "key, including `severity`, to an Azure DevOps field, or list it in `unmapped_keys`. A `choice` value\n", + "is sent as its option key, so the keys must equal the Azure DevOps values, and a choice field that\n", + "takes Other text can't be mapped. `check_fields` reports every key that breaks a rule:\n", + "\n", + "```python\n", + "from pyrit.output import AzureDevOpsField, AzureDevOpsFieldKind, AzureDevOpsFindingPublisher\n", + "\n", + "publisher = AzureDevOpsFindingPublisher(\n", + " organization_url=\"https://dev.azure.com/contoso\",\n", + " project=\"Red Team\",\n", + " work_item_type=\"Finding\",\n", + " destination_work_item_types=[\"Operation\"],\n", + " field_map={\n", + " \"severity\": AzureDevOpsField(reference_name=\"Custom.Severity\", kind=AzureDevOpsFieldKind.CHOICE),\n", + " \"summary\": AzureDevOpsField(reference_name=\"Custom.Summary\", kind=AzureDevOpsFieldKind.TEXT),\n", + " \"description\": AzureDevOpsField(reference_name=\"System.Description\", kind=AzureDevOpsFieldKind.HTML),\n", + " },\n", + " evidence_field=\"Custom.Evidence\",\n", + " unmapped_keys=[\"internal_notes\"],\n", + " fixed_fields={\"Custom.Source\": \"PyRIT\"},\n", + ")\n", + "publisher.check_fields(fields=fields)\n", + "```\n", + "\n", + "This example assumes a deployment's configured finding fields. PyRIT's default fields let `severity`\n", + "and `harm_type` take Other text, so with the defaults, list both in `unmapped_keys`.\n", + "\n", + "Each work item copies its Area and Iteration from the destination, is assigned to the email of\n", + "`requested_by`, and notes the requester, the run ID, and the finding ID in its History. Titles and\n", + "`text` values must fit on one line of at most 255 characters as Azure DevOps counts them; the preview\n", + "lists any that don't, and nothing is shortened.\n", + "\n", + "To publish somewhere else, subclass `FindingPublisher` and implement `_open_destination_async`, which\n", + "reads the destination, and `_create_item_async`, which creates one item. The base class plans the\n", + "items, checks the values, and accounts for every outcome. This publisher keeps its items in memory:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "publishing-findings-example", + "metadata": {}, + "outputs": [ + { + "name": "stderr", + "output_type": "stream", + "text": [ + "Finding publish run 5dd45f9822e94ddfa4ef44ca643ec6ea to destination inbox by InMemoryFindingPublisher: created 2 (1, 2), skipped 1, not attempted 0; no failure; stopped: no.\n" + ] + }, + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Created item 1 under inbox: Encoded instructions bypass refusals\n", + "Created item 2 under 1: The model decodes Base64 input\n", + "Skipped: Role-play jailbreak (Not demonstrated)\n" + ] + } + ], + "source": [ + "from uuid import uuid4\n", + "\n", + "from pyrit.models import (\n", + " DEFAULT_FINDING_FIELDS,\n", + " ComponentIdentifier,\n", + " Finding,\n", + " FindingPublishDestination,\n", + " FindingPublishedItem,\n", + " FindingPublisherInfo,\n", + ")\n", + "from pyrit.output import FindingPublisher, FindingSelection\n", + "\n", + "\n", + "class InMemoryFindingPublisher(FindingPublisher):\n", + " def __init__(self) -> None:\n", + " self.items: dict[str, str] = {}\n", + "\n", + " @property\n", + " def info(self) -> FindingPublisherInfo:\n", + " return FindingPublisherInfo(destination_label=\"Folder\", destination_hint=\"Name a folder.\")\n", + "\n", + " def _build_identifier(self) -> ComponentIdentifier:\n", + " return ComponentIdentifier.of(self)\n", + "\n", + " async def _open_destination_async(self, *, destination, deadline):\n", + " folder = FindingPublishDestination(id=destination, title=destination, url=\"\", location=\"memory\")\n", + " return folder, None\n", + "\n", + " async def _create_item_async(self, *, item, parent_external_id, context, run_id, requested_by, deadline):\n", + " external_id = str(len(self.items) + 1)\n", + " self.items[external_id] = item.finding.title\n", + " return FindingPublishedItem(\n", + " finding_id=item.finding.id,\n", + " title=item.finding.title,\n", + " external_id=external_id,\n", + " url=\"\",\n", + " parent_external_id=parent_external_id,\n", + " )\n", + "\n", + "\n", + "operation_id = uuid4()\n", + "finding = Finding(operation_id=operation_id, title=\"Encoded instructions bypass refusals\", severity=\"important\")\n", + "step = Finding(\n", + " operation_id=operation_id, title=\"The model decodes Base64 input\", severity=\"moderate\", parent_finding_id=finding.id\n", + ")\n", + "draft = Finding(operation_id=operation_id, title=\"Role-play jailbreak\", severity=\"low\", demonstrated=False)\n", + "selection = FindingSelection(\n", + " operation_id=operation_id, operation_name=\"Demo operation\", findings=(finding, step, draft), evidence={}, part_of={}\n", + ")\n", + "\n", + "publisher = InMemoryFindingPublisher()\n", + "preview = await publisher.preview_async( # type: ignore\n", + " selection=selection, fields=DEFAULT_FINDING_FIELDS, destination=\"inbox\"\n", + ")\n", + "result = await publisher.publish_async( # type: ignore\n", + " selection=selection, fields=DEFAULT_FINDING_FIELDS, destination=\"inbox\", expected_plan_digest=preview.plan_digest\n", + ")\n", + "\n", + "for item in result.created:\n", + " print(f\"Created item {item.external_id} under {item.parent_external_id}: {item.title}\")\n", + "for skip in result.skipped:\n", + " print(f\"Skipped: {skip.title} ({skip.reason})\")" + ] + }, { "cell_type": "markdown", "id": "19", diff --git a/doc/code/output/0_output.py b/doc/code/output/0_output.py index cafafaef5c..5c163a91a3 100644 --- a/doc/code/output/0_output.py +++ b/doc/code/output/0_output.py @@ -247,6 +247,164 @@ # no suite-wide rate. To render results you already hold, pass them as `results=` (keyed by # scenario result ID) to a printer in `pyrit.output.scenario_suite_result`. +# %% [markdown] +# ## Printing Finding Reports +# +# `build_finding_selection_async` reads an Operation's selected findings from memory, each with all +# of its sub-findings and evidence, as CoPyRIT's findings export does. `build_finding_report` lays +# the selection out as a report, and `output_finding_report_async` prints it. +# +# Pass `link_for` to `build_finding_report` to link each piece of evidence whose conversation can be +# opened, for example to your dashboard. Without it, the report lists evidence without links. Pass +# `max_findings` to `build_finding_selection_async` to cap the selection, counting sub-findings. + +# %% +from pyrit.models import Finding, Operation +from pyrit.output import build_finding_report, build_finding_selection_async, output_finding_report_async +from pyrit.setup.finding_fields import get_active_finding_fields + +operation = await memory.add_operation_async(Operation(name="Output guide")) +finding = await memory.add_finding_async( + finding=Finding(operation_id=operation.id, title="Joke ranks people by height", severity="low") +) + +fields = get_active_finding_fields() +selection = await build_finding_selection_async(operation_id=operation.id, finding_ids=[finding.id], fields=fields) +await output_finding_report_async(build_finding_report(selection=selection, fields=fields)) + +# %% [markdown] +# ## Publishing Findings +# +# A finding publisher creates an item for each selected finding in another system, under an existing +# item that you name, such as a parent work item. `preview_async` shows where every finding would go +# and writes nothing. `publish_async` creates the items, parents first, and reports every finding's +# outcome: created, skipped because it wasn't demonstrated, failed (saying whether the item might +# exist anyway), or not attempted. Each publish has a run ID that the created items record, and +# publishing again creates new items. +# +# ```python +# from pyrit.output import build_finding_selection_async +# from pyrit.setup.finding_fields import get_active_finding_fields +# +# fields = get_active_finding_fields() +# selection = await build_finding_selection_async(operation_id=operation_id, finding_ids=finding_ids, fields=fields) +# preview = await publisher.preview_async(selection=selection, fields=fields, destination="12345") +# result = await publisher.publish_async( +# selection=selection, fields=fields, destination="12345", link_for=link_for, expected_plan_digest=preview.plan_digest +# ) +# ``` +# +# Pass the preview's `plan_digest` so the publish creates only what the preview showed; if the findings +# or the destination changed, it raises `FindingPublishPlanChangedError` before writing anything. Pass +# `link_for` to `publish_async` to link each piece of evidence, as `build_finding_report` does. Links +# don't change the digest, so the preview takes none. +# +# To offer a publisher in CoPyRIT, register it from an initializer with +# `FindingPublisherRegistry.get_registry_singleton().instances.register(publisher, name=...)`. The operation +# page then shows **Publish findings**, and the backend links evidence to `PYRIT_PUBLIC_ORIGIN`. +# +# `AzureDevOpsFindingPublisher` creates Azure DevOps work items under an existing work item, with a +# token from `DefaultAzureCredential` unless you pass `token_provider`. Map each finding field and level +# key, including `severity`, to an Azure DevOps field, or list it in `unmapped_keys`. A `choice` value +# is sent as its option key, so the keys must equal the Azure DevOps values, and a choice field that +# takes Other text can't be mapped. `check_fields` reports every key that breaks a rule: +# +# ```python +# from pyrit.output import AzureDevOpsField, AzureDevOpsFieldKind, AzureDevOpsFindingPublisher +# +# publisher = AzureDevOpsFindingPublisher( +# organization_url="https://dev.azure.com/contoso", +# project="Red Team", +# work_item_type="Finding", +# destination_work_item_types=["Operation"], +# field_map={ +# "severity": AzureDevOpsField(reference_name="Custom.Severity", kind=AzureDevOpsFieldKind.CHOICE), +# "summary": AzureDevOpsField(reference_name="Custom.Summary", kind=AzureDevOpsFieldKind.TEXT), +# "description": AzureDevOpsField(reference_name="System.Description", kind=AzureDevOpsFieldKind.HTML), +# }, +# evidence_field="Custom.Evidence", +# unmapped_keys=["internal_notes"], +# fixed_fields={"Custom.Source": "PyRIT"}, +# ) +# publisher.check_fields(fields=fields) +# ``` +# +# This example assumes a deployment's configured finding fields. PyRIT's default fields let `severity` +# and `harm_type` take Other text, so with the defaults, list both in `unmapped_keys`. +# +# Each work item copies its Area and Iteration from the destination, is assigned to the email of +# `requested_by`, and notes the requester, the run ID, and the finding ID in its History. Titles and +# `text` values must fit on one line of at most 255 characters as Azure DevOps counts them; the preview +# lists any that don't, and nothing is shortened. +# +# To publish somewhere else, subclass `FindingPublisher` and implement `_open_destination_async`, which +# reads the destination, and `_create_item_async`, which creates one item. The base class plans the +# items, checks the values, and accounts for every outcome. This publisher keeps its items in memory: + +# %% +from uuid import uuid4 + +from pyrit.models import ( + DEFAULT_FINDING_FIELDS, + ComponentIdentifier, + Finding, + FindingPublishDestination, + FindingPublishedItem, + FindingPublisherInfo, +) +from pyrit.output import FindingPublisher, FindingSelection + + +class InMemoryFindingPublisher(FindingPublisher): + def __init__(self) -> None: + self.items: dict[str, str] = {} + + @property + def info(self) -> FindingPublisherInfo: + return FindingPublisherInfo(destination_label="Folder", destination_hint="Name a folder.") + + def _build_identifier(self) -> ComponentIdentifier: + return ComponentIdentifier.of(self) + + async def _open_destination_async(self, *, destination, deadline): + folder = FindingPublishDestination(id=destination, title=destination, url="", location="memory") + return folder, None + + async def _create_item_async(self, *, item, parent_external_id, context, run_id, requested_by, deadline): + external_id = str(len(self.items) + 1) + self.items[external_id] = item.finding.title + return FindingPublishedItem( + finding_id=item.finding.id, + title=item.finding.title, + external_id=external_id, + url="", + parent_external_id=parent_external_id, + ) + + +operation_id = uuid4() +finding = Finding(operation_id=operation_id, title="Encoded instructions bypass refusals", severity="important") +step = Finding( + operation_id=operation_id, title="The model decodes Base64 input", severity="moderate", parent_finding_id=finding.id +) +draft = Finding(operation_id=operation_id, title="Role-play jailbreak", severity="low", demonstrated=False) +selection = FindingSelection( + operation_id=operation_id, operation_name="Demo operation", findings=(finding, step, draft), evidence={}, part_of={} +) + +publisher = InMemoryFindingPublisher() +preview = await publisher.preview_async( # type: ignore + selection=selection, fields=DEFAULT_FINDING_FIELDS, destination="inbox" +) +result = await publisher.publish_async( # type: ignore + selection=selection, fields=DEFAULT_FINDING_FIELDS, destination="inbox", expected_plan_digest=preview.plan_digest +) + +for item in result.created: + print(f"Created item {item.external_id} under {item.parent_external_id}: {item.title}") +for skip in result.skipped: + print(f"Skipped: {skip.title} ({skip.reason})") + # %% [markdown] # ## Sinks — Redirecting Output # diff --git a/doc/gui/0_gui.md b/doc/gui/0_gui.md index 0214b0201d..68a22af7f6 100644 --- a/doc/gui/0_gui.md +++ b/doc/gui/0_gui.md @@ -434,6 +434,17 @@ includes its sub-findings, numbered under it in the order they were added (1, demonstrated. Evidence appears as links to the attacks in PyRIT, without transcripts or media. Nothing is redacted, so store and share exported files with care. +**Publish findings** appears when the deployment registers a [finding +publisher](../code/output/0_output.ipynb), such as one that creates Azure DevOps +work items. Select findings, name the existing item they go under, and select +**Check** to see where each one will go: its parent, any finding it is part of, +the findings skipped because they weren't demonstrated, and any problems to fix +first. **Publish** then creates exactly what the Check showed, with evidence +links back to PyRIT, and lists every finding's outcome with the run ID that the +new items record. If a finding's outcome is unknown, its item might exist +anyway, so look before publishing it again; publishing again always creates +new items. + ![Operations page with a test operation](images/operations.png) ## Configuration diff --git a/frontend/e2e/operations.spec.ts b/frontend/e2e/operations.spec.ts index 6848286aef..f43e172b4a 100644 --- a/frontend/e2e/operations.spec.ts +++ b/frontend/e2e/operations.spec.ts @@ -1,6 +1,6 @@ import { readFileSync } from 'node:fs' -import { test, expect } from '@playwright/test' +import { test, expect, type Locator } from '@playwright/test' import type { CreateAttackResponse, Finding, FindingEvidenceAttachResponse, FindingExportFormat, FindingFields, @@ -636,3 +636,63 @@ test.describe('finding dialog on a touch screen', () => { } }) }) + +test('checks, then publishes findings with the registered publisher @seeded', async ({ page, request }) => { + const version = await (await request.get('/api/version')).json() + const headers = { 'PyRIT-Compatibility-ID': version.compatibility_id } + const operationResponse = await request.post('/api/operations', { + headers, data: { name: `Publish ${Date.now()}` }, + }) + expect(operationResponse.status()).toBe(201) + const operation: Operation = await operationResponse.json() + const create = async (data: Record): Promise => { + const response = await request.post(`/api/operations/${operation.id}/findings`, { + headers, data: { severity: 'moderate', ...data }, + }) + expect(response.status()).toBe(201) + return response.json() + } + const parent = await create({ title: 'Publish parent' }) + await create({ title: 'Publish step', parent_finding_id: parent.id }) + await create({ title: 'Publish draft', demonstrated: false }) + + await page.goto(`/operations/${operation.id}`) + await waitForAppReady(page) + await page.getByRole('button', { name: 'Publish findings', exact: true }).click() + const dialog = page.getByRole('dialog', { name: 'Publish findings' }) + await expect(dialog.getByRole('checkbox', { name: 'Select all', exact: true })).toBeChecked() + const publish = dialog.getByRole('button', { name: 'Publish', exact: true }) + await expect(publish).toBeDisabled() + const destination = dialog.getByRole('textbox', { name: 'Offline folder' }) + const hint = dialog.getByText('Name any folder.', { exact: true }) + const box = async (locator: Locator): Promise<{ x: number; y: number; width: number; height: number }> => { + const found = await locator.boundingBox() + if (!found) throw new Error('Expected a visible element.') + return found + } + // Check sits level with the input, and the hint directly under the input, at desktop width and on a phone. + const checkButton = dialog.getByRole('button', { name: 'Check', exact: true }) + expect(Math.abs((await box(checkButton)).y - (await box(destination)).y)).toBeLessThanOrEqual(2) + await page.setViewportSize({ width: 390, height: 844 }) + const input = await box(destination) + expect((await box(hint)).y - (input.y + input.height)).toBeLessThanOrEqual(8) + expect((await box(checkButton)).y).toBeGreaterThan((await box(hint)).y) + await page.setViewportSize({ width: 1280, height: 720 }) + await destination.fill('inbox') + // Enter runs Check and focus stays in the dialog, not on the page behind it. + await destination.press('Enter') + + const check = dialog.getByRole('region', { name: 'Check' }) + await expect(check).toBeVisible() + await expect(destination).toBeFocused() + await expect(check.getByText('Publish parent → under Folder inbox', { exact: true })).toBeVisible() + await expect(check.getByText('Publish step → under Publish parent', { exact: true })).toBeVisible() + await expect(check.getByText('Publish draft · Not demonstrated', { exact: true })).toBeVisible() + await publish.click() + + await expect(dialog.getByText(/^Published\. Created 2 items\./)).toBeVisible() + await expect(dialog.getByText(/^Publish parent · offline-/)).toBeVisible() + await expect(dialog.getByText(/^Publish step · offline-/)).toBeVisible() + await dialog.getByRole('button', { name: 'Close', exact: true }).click() + await expect(dialog).toHaveCount(0) +}) diff --git a/frontend/playwright.config.ts b/frontend/playwright.config.ts index 2eca3c0ecf..be64a2a53f 100644 --- a/frontend/playwright.config.ts +++ b/frontend/playwright.config.ts @@ -140,7 +140,8 @@ export default defineConfig({ `cd .. && uv run --no-sync python -m pyrit.backend.pyrit_backend ` + `--auth-mode local --host 127.0.0.1 --port ${E2E_BACKEND_PORT} --log-level warning ` + `--config-file "${SEEDED_BACKEND_CONFIG_FILE}"`, - env: { PYRIT_DEV_MODE: "true" }, + // Published findings link their evidence to the dashboard the tests open. + env: { PYRIT_DEV_MODE: "true", PYRIT_PUBLIC_ORIGIN: E2E_FRONTEND_URL }, url: `${E2E_BACKEND_URL}/api/health`, reuseExistingServer: false, timeout: 120_000, diff --git a/frontend/src/components/Operations/FindingExportDialog.styles.ts b/frontend/src/components/Operations/FindingExportDialog.styles.ts index f208cb580c..c5dbe2ba1c 100644 --- a/frontend/src/components/Operations/FindingExportDialog.styles.ts +++ b/frontend/src/components/Operations/FindingExportDialog.styles.ts @@ -1,45 +1,9 @@ -import type { CSSProperties } from 'react' - import { makeStyles, tokens } from '@fluentui/react-components' -import { mobileTouchTargetHeight, NARROW_VIEWPORT_QUERY } from '@/styles/touchTargets' - -// Fluent's medium Checkbox indicator. With its inline margins and the label's padding, a row's title starts after it. -const CHECKBOX_INDICATOR_SIZE = '16px' -const TITLE_INDENT = `calc(${tokens.spacingHorizontalS} * 2 + ${CHECKBOX_INDICATOR_SIZE} + ${tokens.spacingHorizontalXS})` -// Deeper sub-findings share the deepest indent so a long decomposition still fits a narrow dialog; each row names -// its parent for screen readers. -const MAX_INDENT_LEVELS = 4 - -/** A sub-finding row's indent, lining it up with its parent's title. */ -export function findingIndent(depth: number): CSSProperties | undefined { - if (depth <= 0) return undefined - return { paddingInlineStart: `calc(${TITLE_INDENT} * ${Math.min(depth, MAX_INDENT_LEVELS)})` } -} +import { mobileTouchTargetHeight } from '@/styles/touchTargets' export const useFindingExportDialogStyles = makeStyles({ content: { display: 'flex', flexDirection: 'column', gap: tokens.spacingVerticalM }, messageBar: { flexShrink: 0 }, - list: { margin: 0, padding: 0, listStyleType: 'none' }, - // Read to screen readers; the indent and the locked check already show it on screen. - visuallyHidden: { - position: 'absolute', - width: '1px', - height: '1px', - padding: 0, - margin: '-1px', - overflow: 'hidden', - clip: 'rect(0, 0, 0, 0)', - whiteSpace: 'nowrap', - border: 0, - }, - row: { display: 'flex', flexWrap: 'wrap', alignItems: 'center', columnGap: tokens.spacingHorizontalS, minWidth: 0 }, - checkbox: { flex: '1 1 12rem', minWidth: 0 }, - label: { minWidth: 0, overflowWrap: 'anywhere' }, - created: { - color: tokens.colorNeutralForeground3, - // On narrow screens the time gets its own line, lined up under the title. - [NARROW_VIEWPORT_QUERY]: { flexBasis: '100%', paddingInlineStart: TITLE_INDENT }, - }, button: { ...mobileTouchTargetHeight }, }) diff --git a/frontend/src/components/Operations/FindingExportDialog.tsx b/frontend/src/components/Operations/FindingExportDialog.tsx index 190251f7cf..2b6cdb6244 100644 --- a/frontend/src/components/Operations/FindingExportDialog.tsx +++ b/frontend/src/components/Operations/FindingExportDialog.tsx @@ -1,24 +1,24 @@ -import { useEffect, useId, useRef, useState } from 'react' +import { useEffect, useRef, useState } from 'react' import { - Button, Checkbox, Dialog, DialogActions, DialogBody, DialogContent, DialogSurface, DialogTitle, DialogTrigger, + Button, Dialog, DialogActions, DialogBody, DialogContent, DialogSurface, DialogTitle, DialogTrigger, Field, MessageBar, MessageBarBody, Select, Spinner, Text, } from '@fluentui/react-components' import { ArrowDownloadRegular } from '@fluentui/react-icons' +import { loadAllOperationFindingsAsync } from '@/hooks/useAllOperationFindings' import { operationsApi } from '@/services/api' import { toApiError } from '@/services/errors' import type { FindingExportFormat, FindingFields, FindingListItem, Operation } from '@/types' import { downloadFile } from '@/utils/downloadFile' import { findingExportFilename } from '@/utils/findingExportFilename' -import { findingChildren, findingDescendantIds, flattenFindingTree } from '@/utils/findingTree' +import { findingChildren, findingDescendantIds, findingTreeSelection } from '@/utils/findingTree' -import { findingIndent, useFindingExportDialogStyles } from './FindingExportDialog.styles' -import FindingSeverityBadge from './FindingSeverityBadge' +import { useFindingExportDialogStyles } from './FindingExportDialog.styles' import { MAX_EXPORT_FINDINGS } from './findingExportLimits' +import FindingSelectionTree from './FindingSelectionTree' import { fluentRef } from '@/utils/fluentRef' -const PAGE_SIZE = 100 const FORMATS: Record = { docx: { option: 'Word (.docx)', name: 'Word', extension: 'docx' }, markdown: { option: 'Markdown (.md)', name: 'Markdown', extension: 'md' }, @@ -68,7 +68,6 @@ export default function FindingExportDialog({ operation, fields, fieldsRevision // The IDs of the last list loaded since the dialog opened. A reload ticks every row only if all of these were ticked. const shown = useRef | null>(null) const triggerRef = useRef(null) - const rowId = useId() // Aborted when the dialog closes or unmounts, so a late export never downloads into a later view. const session = useRef(null) @@ -76,17 +75,7 @@ export default function FindingExportDialog({ operation, fields, fieldsRevision const reloadingForFields = loadState.status !== 'loading' && loadState.fieldsRevision !== fieldsRevision const load: FindingsLoad = reloadingForFields ? { status: 'loading' } : loadState const findings = load.status === 'loaded' ? load.findings : [] - const children = findingChildren(findings) - const roots = children.get(null) ?? [] - // A selected finding includes all of its sub-findings, so they show as checked and cannot be unchecked alone. - const implied = new Set(findings.filter(finding => selected.has(finding.id)) - .flatMap(finding => findingDescendantIds(children, finding.id))) - const included = findings.filter(finding => selected.has(finding.id) || implied.has(finding.id)) - const selectedIds = flattenFindingTree(findings) - .map(({ finding }) => finding.id) - .filter(findingId => selected.has(findingId) && !implied.has(findingId)) - const allSelected = included.length === findings.length - const selectAllChecked = allSelected ? true : included.length === 0 ? false : 'mixed' + const { included, selectedIds } = findingTreeSelection(findings, selected) const tooMany = included.length > MAX_EXPORT_FINDINGS // A natively disabled button drops keyboard focus out of the dialog, so while an export runs, while the list reloads, // and while it shows nothing selected after a deleted finding, Download stays focusable but unavailable. @@ -109,25 +98,9 @@ export default function FindingExportDialog({ operation, fields, fieldsRevision if (!open) return let ignore = false const loadAllPages = async (): Promise => { - const loaded = new Map() - const seenOffsets = new Set() - let offset: number | null = 0 - while (offset !== null) { - // A repeated offset means the server is not advancing the page, and - // fetching it again would loop forever, so stop with an error the - // same way the shared pagination helper treats a cyclic cursor. - if (seenOffsets.has(offset)) { - throw new Error('The findings page offset did not advance.') - } - seenOffsets.add(offset) - const page = await operationsApi.listFindings(operation.id, { limit: PAGE_SIZE, offset }) - if (ignore) return - // A finding created while pages load shifts later pages, so a page can repeat an earlier row. - for (const finding of page.items) { - if (!loaded.has(finding.id)) loaded.set(finding.id, finding) - } - offset = page.has_more ? page.next_offset : null - } + const findings = await loadAllOperationFindingsAsync(operation.id, () => ignore) + if (findings === null) return + const loaded = new Map(findings.map(finding => [finding.id, finding])) setLoad({ status: 'loaded', findings: [...loaded.values()], fieldsRevision }) setRecovering(false) const kept = recovery.current @@ -175,20 +148,6 @@ export default function FindingExportDialog({ operation, fields, fieldsRevision setOpen(true) } - const toggle = (findingId: string, checked: boolean): void => { - setSelected(current => { - const next = new Set(current) - if (checked) { - next.add(findingId) - // Its sub-findings are now included with it, so they no longer need their own selection. - for (const descendant of findingDescendantIds(children, findingId)) next.delete(descendant) - } else { - next.delete(findingId) - } - return next - }) - } - const download = async (): Promise => { const controller = session.current if (controller === null || controller.signal.aborted || submitting.current || selectedIds.length === 0 || tooMany) { @@ -245,38 +204,9 @@ export default function FindingExportDialog({ operation, fields, fieldsRevision ) } if (findings.length === 0) return This operation has no findings to export. - const titles = new Map(findings.map(finding => [finding.id, finding.title])) - // One flat list in tree order: nesting elements per level would recurse once per level of a deep decomposition. return ( - <> - { setSelected(allSelected ? NO_SELECTION : new Set(roots.map(finding => finding.id))) }} /> -
    - {flattenFindingTree(findings).map(({ finding, depth }) => { - const createdId = `${rowId}-${finding.id}-created` - const relationId = `${rowId}-${finding.id}-relation` - const isImplied = implied.has(finding.id) - const parentTitle = depth > 0 && finding.parent_finding_id ? titles.get(finding.parent_finding_id) : undefined - return ( -
  • - { toggle(finding.id, data.checked === true) }} /> - - {parentTitle !== undefined && - {isImplied ? 'Included with' : 'Sub-finding of'} “{parentTitle}” - } - - - -
  • - ) - })} -
- + ) } diff --git a/frontend/src/components/Operations/FindingPublishDialog.styles.ts b/frontend/src/components/Operations/FindingPublishDialog.styles.ts new file mode 100644 index 0000000000..bba409ff95 --- /dev/null +++ b/frontend/src/components/Operations/FindingPublishDialog.styles.ts @@ -0,0 +1,52 @@ +import { makeStyles, tokens } from '@fluentui/react-components' + +import { mobileTouchTargetHeight, NARROW_VIEWPORT_QUERY } from '@/styles/touchTargets' + +export const useFindingPublishDialogStyles = makeStyles({ + content: { display: 'flex', flexDirection: 'column', gap: tokens.spacingVerticalM }, + messageBar: { flexShrink: 0 }, + button: { ...mobileTouchTargetHeight }, + // The destination field (label, input, hint) beside Check; on narrow screens Check goes below the hint. + destinationRow: { + display: 'grid', + gridTemplateColumns: 'minmax(0, 1fr) auto', + alignItems: 'start', + columnGap: tokens.spacingHorizontalM, + rowGap: tokens.spacingVerticalS, + [NARROW_VIEWPORT_QUERY]: { gridTemplateColumns: 'minmax(0, 1fr)' }, + }, + // Level with the input: below the field's medium label, its line plus its padding and margin. + checkButton: { + marginTop: `calc(${tokens.lineHeightBase300} + 3 * ${tokens.spacingVerticalXXS})`, + [NARROW_VIEWPORT_QUERY]: { marginTop: 0, justifySelf: 'start' }, + }, + // Read to screen readers only; the Check summary already shows the same on screen. + visuallyHidden: { + position: 'absolute', + width: '1px', + height: '1px', + padding: 0, + margin: '-1px', + overflow: 'hidden', + clip: 'rect(0, 0, 0, 0)', + whiteSpace: 'nowrap', + border: 0, + }, + summary: { + display: 'grid', + gridTemplateColumns: 'max-content minmax(0, 1fr)', + columnGap: tokens.spacingHorizontalL, + rowGap: tokens.spacingVerticalS, + margin: 0, + padding: tokens.spacingHorizontalM, + border: `${tokens.strokeWidthThin} solid ${tokens.colorNeutralStroke2}`, + borderRadius: tokens.borderRadiusMedium, + // On narrow screens each label sits above its value. + [NARROW_VIEWPORT_QUERY]: { gridTemplateColumns: 'minmax(0, 1fr)' }, + }, + term: { fontWeight: tokens.fontWeightSemibold }, + definition: { margin: 0, minWidth: 0, overflowWrap: 'anywhere' }, + list: { margin: 0, padding: 0, listStyleType: 'none' }, + note: { color: tokens.colorNeutralForeground3 }, + warning: { color: tokens.colorPaletteDarkOrangeForeground1 }, +}) diff --git a/frontend/src/components/Operations/FindingPublishDialog.test.tsx b/frontend/src/components/Operations/FindingPublishDialog.test.tsx new file mode 100644 index 0000000000..eaa622af0e --- /dev/null +++ b/frontend/src/components/Operations/FindingPublishDialog.test.tsx @@ -0,0 +1,477 @@ +import { act, render, screen, within } from '@testing-library/react' +import userEvent from '@testing-library/user-event' +import { FluentProvider, webLightTheme } from '@fluentui/react-components' + +import { operationsApi } from '@/services/api' +import { deferred } from '@/test-utils/deferred' +import { DEFAULT_FINDING_FIELDS_FIXTURE } from '@/test-utils/findingFieldsFixtures' +import type { + FindingListItem, FindingPublisherListItem, FindingPublishPreview, FindingPublishResult, Operation, +} from '@/types' +import FindingPublishDialog from './FindingPublishDialog' +// The backend's tests build the same responses from its models, so these follow the API's types. +import contract from './findingPublish.contract.json' + +jest.mock('@/services/api', () => ({ + operationsApi: { listFindings: jest.fn(), previewFindingPublish: jest.fn(), publishFindings: jest.fn() }, +})) + +const OPERATION: Operation = { id: 'operation-1', name: 'Contoso', created_at: '2026-12-01T12:00:00Z' } +const PUBLISHER: FindingPublisherListItem = { + name: 'azure_devops', + info: { destination_label: 'Operation work item', destination_hint: "Paste the Operation's work item ID or URL." }, +} +const PREVIEW: FindingPublishPreview = contract.preview +const RESULT: FindingPublishResult = contract.result +const DESTINATION_LABEL = 'Operation work item' + +function finding(index: number, overrides: Partial = {}): FindingListItem { + return { + id: `00000000-0000-0000-0000-00000000000${index}`, operation_id: OPERATION.id, title: `Finding ${index}`, + severity: 'moderate', field_values: {}, created_at: '2026-12-01T12:00:00Z', evidence_count: 0, rows: [], + retired: [], parent_finding_id: null, demonstrated: true, paths: [], child_count: 0, ...overrides, + } +} + +const PARENT = finding(1, { title: 'Leaks the system prompt', child_count: 1 }) +const CHILD = finding(2, { title: 'Decodes Base64', parent_finding_id: PARENT.id }) +const OTHER = finding(3, { title: 'Writes the payload' }) + +function apiError( + status: number, type: string | undefined, detail: string, errors?: Array<{ field: string; message: string }>, +): unknown { + return { isAxiosError: true, response: { status, data: { type, detail, ...(errors ? { errors } : {}) } } } +} + +function dialogElement(fieldsRevision: number): React.ReactElement { + return ( + + + + ) +} + +function renderDialog(): void { + render(dialogElement(0)) +} + +async function openDialog(user: ReturnType): Promise { + await user.click(screen.getByRole('button', { name: 'Publish findings' })) + const dialog = screen.getByRole('dialog', { name: 'Publish findings' }) + await within(dialog).findByRole('checkbox', { name: 'Select all' }) + return dialog +} + +/** Opens the dialog, names the destination and runs Check, which answers with `preview`. */ +async function checkFindings( + user: ReturnType, preview: FindingPublishPreview = PREVIEW, opened?: HTMLElement, +): Promise { + jest.mocked(operationsApi.previewFindingPublish).mockResolvedValue(preview) + const dialog = opened ?? await openDialog(user) + await user.type(within(dialog).getByRole('textbox', { name: DESTINATION_LABEL }), '12345') + await user.click(within(dialog).getByRole('button', { name: 'Check' })) + await within(dialog).findByRole('region', { name: 'Check' }) + return dialog +} + +beforeEach(() => { + jest.clearAllMocks() + jest.mocked(operationsApi.listFindings).mockResolvedValue({ + items: [PARENT, OTHER, CHILD], has_more: false, next_offset: null, + }) +}) + +describe('FindingPublishDialog', () => { + it('labels the destination input from the publisher', async () => { + const user = userEvent.setup() + renderDialog() + // A closed dialog reads nothing. + expect(operationsApi.listFindings).not.toHaveBeenCalled() + const dialog = await openDialog(user) + + expect(within(dialog).getByRole('textbox', { name: DESTINATION_LABEL })) + .toHaveAccessibleDescription("Paste the Operation's work item ID or URL.") + expect(within(dialog).getByRole('button', { name: 'Check' })).toBeDisabled() + expect(within(dialog).getByRole('button', { name: 'Publish' })).toBeDisabled() + }) + + it('checks the selected findings and shows where the server will put each one', async () => { + const user = userEvent.setup() + renderDialog() + const dialog = await checkFindings(user) + + expect(operationsApi.previewFindingPublish).toHaveBeenCalledWith(OPERATION.id, { + finding_ids: [PARENT.id, OTHER.id], publisher_name: 'azure_devops', destination: '12345', + }, expect.any(AbortSignal)) + const check = within(dialog).getByRole('region', { name: 'Check' }) + expect(within(check).getByRole('link', { name: '12345 · Operation Contoso' })) + .toHaveAttribute('href', 'https://tracker.example.test/12345') + expect(within(check).getByText('Example / Red Team')).toBeInTheDocument() + expect(within(check).getByText('Leaks the system prompt → under Operation Contoso')).toBeInTheDocument() + expect(within(check).getByText('Decodes Base64 → under Leaks the system prompt')).toBeInTheDocument() + expect(within(check).getByText('Writes the payload → under Operation Contoso · Part of: Earlier finding')) + .toBeInTheDocument() + expect(within(check).getByText('Role-play · Not demonstrated')).toBeInTheDocument() + expect(within(check).getByText('None')).toBeInTheDocument() + expect(within(check).getByText('Publishing again creates new work items.')).toBeInTheDocument() + expect(within(dialog).getByRole('button', { name: 'Publish' })).toBeEnabled() + }) + + it('announces what a Check found to screen readers', async () => { + const user = userEvent.setup() + renderDialog() + const dialog = await openDialog(user) + // The live region is there before the Check, so the announcement is read when it fills in. + const status = within(dialog).getByRole('status') + expect(status).toBeEmptyDOMElement() + + await checkFindings(user, PREVIEW, dialog) + + expect(status).toHaveTextContent('Check found 3 findings to publish, 1 skipped.') + }) + + it('keeps focus in the destination while the Check that Enter started runs', async () => { + const user = userEvent.setup() + const pending = deferred() + jest.mocked(operationsApi.previewFindingPublish).mockReturnValue(pending.promise) + renderDialog() + const dialog = await openDialog(user) + const destination = within(dialog).getByRole('textbox', { name: DESTINATION_LABEL }) + + await user.type(destination, '12345{Enter}') + + expect(within(dialog).getByRole('button', { name: 'Checking…' })).toBeInTheDocument() + // A disabled input would drop focus, which the modal then restores to the page behind it. + expect(destination).toBeEnabled() + expect(destination).toHaveFocus() + expect(dialog.closest('[aria-hidden="true"]')).toBeNull() + await act(async () => { pending.resolve(PREVIEW) }) + expect(destination).toHaveFocus() + expect(within(dialog).getByRole('status')).toHaveTextContent('Check found 3 findings to publish, 1 skipped.') + }) + + it('runs Check, never Publish, when Enter is pressed in the destination', async () => { + const user = userEvent.setup() + renderDialog() + const dialog = await checkFindings(user) + expect(within(dialog).getByRole('button', { name: 'Publish' })).toBeEnabled() + + await user.type(within(dialog).getByRole('textbox', { name: DESTINATION_LABEL }), '{Enter}') + + await within(dialog).findByRole('region', { name: 'Check' }) + expect(operationsApi.previewFindingPublish).toHaveBeenCalledTimes(2) + expect(operationsApi.publishFindings).not.toHaveBeenCalled() + }) + + it.each([ + ['problems', { + ...PREVIEW, + problems: [{ finding_id: PARENT.id, title: 'Leaks the system prompt', message: 'Severity is required.' }], + }], + ['nothing planned', { ...PREVIEW, planned: [] }], + ])('keeps Publish disabled after a Check with %s', async (_, preview: FindingPublishPreview) => { + const user = userEvent.setup() + renderDialog() + const dialog = await checkFindings(user, preview) + + expect(within(dialog).getByRole('button', { name: 'Publish' })).toBeDisabled() + if (preview.problems.length > 0) { + expect(within(dialog).getByText('Leaks the system prompt: Severity is required.')).toBeInTheDocument() + } + }) + + it('tells the user to fix the problems instead of warning about publishing again', async () => { + const user = userEvent.setup() + renderDialog() + const problem = { title: 'Leaks the system prompt', message: 'Severity is required.' } + const dialog = await checkFindings(user, { + ...PREVIEW, + problems: [{ finding_id: PARENT.id, ...problem }, { finding_id: OTHER.id, ...problem, title: 'Other' }], + }) + const check = within(dialog).getByRole('region', { name: 'Check' }) + + expect(within(check).getByText('Fix 2 problems, then check again.')).toBeInTheDocument() + expect(within(check).queryByText('Publishing again creates new work items.')).not.toBeInTheDocument() + expect(within(dialog).getByRole('status')) + .toHaveTextContent('Check found 3 findings to publish, 1 skipped. Fix 2 problems, then check again.') + }) + + it('clears the Check when the selection changes', async () => { + const user = userEvent.setup() + renderDialog() + const dialog = await checkFindings(user) + + await user.click(within(dialog).getByRole('checkbox', { name: 'Writes the payload' })) + + expect(within(dialog).queryByRole('region', { name: 'Check' })).not.toBeInTheDocument() + expect(within(dialog).getByRole('button', { name: 'Publish' })).toBeDisabled() + }) + + it('needs a new Check after the selection changes and changes back', async () => { + const user = userEvent.setup() + renderDialog() + const dialog = await checkFindings(user) + const row = within(dialog).getByRole('checkbox', { name: 'Writes the payload' }) + + await user.click(row) + await user.click(row) + + expect(row).toBeChecked() + expect(within(dialog).queryByRole('region', { name: 'Check' })).not.toBeInTheDocument() + expect(within(dialog).getByRole('button', { name: 'Publish' })).toBeDisabled() + }) + + it('drops the Check when changed finding fields reload a different list', async () => { + const user = userEvent.setup() + const { rerender } = render(dialogElement(0)) + const dialog = await checkFindings(user) + // A teammate deleted a selected finding; the reload for changed fields no longer lists it. + jest.mocked(operationsApi.listFindings).mockResolvedValue({ + items: [PARENT, CHILD], has_more: false, next_offset: null, + }) + + rerender(dialogElement(1)) + + await within(dialog).findByRole('checkbox', { name: 'Select all' }) + expect(within(dialog).queryByRole('region', { name: 'Check' })).not.toBeInTheDocument() + expect(within(dialog).getByRole('button', { name: 'Publish' })).toBeDisabled() + }) + + it('clears the Check when the destination changes', async () => { + const user = userEvent.setup() + renderDialog() + const dialog = await checkFindings(user) + + await user.type(within(dialog).getByRole('textbox', { name: DESTINATION_LABEL }), '6') + + expect(within(dialog).queryByRole('region', { name: 'Check' })).not.toBeInTheDocument() + expect(within(dialog).getByRole('button', { name: 'Publish' })).toBeDisabled() + }) + + it('publishes with the Check’s plan digest and shows every outcome', async () => { + const user = userEvent.setup() + jest.mocked(operationsApi.publishFindings).mockResolvedValue(RESULT) + renderDialog() + const dialog = await checkFindings(user) + + await user.click(within(dialog).getByRole('button', { name: 'Publish' })) + + expect(await within(dialog).findByText(RESULT.run_id)).toBeInTheDocument() + expect(operationsApi.publishFindings).toHaveBeenCalledWith(OPERATION.id, { + finding_ids: [PARENT.id, OTHER.id], publisher_name: 'azure_devops', destination: '12345', + plan_digest: PREVIEW.plan_digest, + }) + expect(within(dialog).getByRole('link', { name: 'Leaks the system prompt · 101' })) + .toHaveAttribute('href', 'https://tracker.example.test/101') + expect(within(dialog).getByText('Role-play · Not demonstrated')).toBeInTheDocument() + expect(within(dialog).getByText("Decodes Base64: The service didn't answer.")).toBeInTheDocument() + // The publisher's message gives the advice; the dialog only marks the outcome as unknown. + expect(within(dialog).getByText('Outcome unknown')).toBeInTheDocument() + expect(within(dialog).getByText('Writes the payload')).toBeInTheDocument() + expect(within(dialog).getByText(/The run stopped before every finding was published/)).toBeInTheDocument() + expect(within(dialog).queryByRole('button', { name: 'Publish' })).not.toBeInTheDocument() + }) + + it('marks a failure as unknown only when its item might exist', async () => { + const user = userEvent.setup() + const failure = { ...RESULT.failure, message: 'Azure DevOps rejected the item (HTTP 400).', outcome_unknown: false } + jest.mocked(operationsApi.publishFindings).mockResolvedValue({ ...RESULT, failure }) + renderDialog() + const dialog = await checkFindings(user) + + await user.click(within(dialog).getByRole('button', { name: 'Publish' })) + + expect(await within(dialog).findByText('Decodes Base64: Azure DevOps rejected the item (HTTP 400).')) + .toBeInTheDocument() + expect(within(dialog).queryByText('Outcome unknown')).not.toBeInTheDocument() + }) + + it('shows why a run stopped', async () => { + const user = userEvent.setup() + jest.mocked(operationsApi.publishFindings).mockResolvedValue({ + ...RESULT, failure: null, stopped_reason: 'Stopped to stay within the time limit.', + }) + renderDialog() + const dialog = await checkFindings(user) + + await user.click(within(dialog).getByRole('button', { name: 'Publish' })) + + expect(await within(dialog).findByText('Stopped to stay within the time limit.')).toBeInTheDocument() + expect(within(dialog).queryByText('Outcome unknown')).not.toBeInTheDocument() + }) + + it('reports a complete run', async () => { + const user = userEvent.setup() + jest.mocked(operationsApi.publishFindings).mockResolvedValue({ ...RESULT, failure: null, not_attempted: [] }) + renderDialog() + const dialog = await checkFindings(user) + + await user.click(within(dialog).getByRole('button', { name: 'Publish' })) + + expect(await within(dialog).findByText(/Published\. Created 1 item\./)).toBeInTheDocument() + }) + + it.each([ + [409, '/errors/publish-plan-changed', 'The findings changed since Check; check again.', undefined], + [422, '/errors/publish-problems', 'Fix these problems, then check again', + [{ field: 'Decodes Base64', message: 'The title is too long.' }]], + [422, '/errors/publish-too-many', 'Publish at most 100 findings at a time, counting sub-findings.', undefined], + [422, '/errors/validation-error', 'Request validation failed', undefined], + ])('clears the Check after a %i %s from Publish', async (status, type, detail, errors) => { + const user = userEvent.setup() + jest.mocked(operationsApi.publishFindings).mockRejectedValue(apiError(status, type, detail, errors)) + renderDialog() + const dialog = await checkFindings(user) + + await user.click(within(dialog).getByRole('button', { name: 'Publish' })) + + expect(await within(dialog).findByText(new RegExp(`Could not publish findings: ${detail}`))).toBeInTheDocument() + if (errors) expect(within(dialog).getByText(/Decodes Base64: The title is too long\./)).toBeInTheDocument() + expect(within(dialog).queryByText(/might have been created/)).not.toBeInTheDocument() + expect(within(dialog).queryByRole('region', { name: 'Check' })).not.toBeInTheDocument() + expect(within(dialog).getByRole('button', { name: 'Publish' })).toBeDisabled() + }) + + it.each([ + ['no response', { isAxiosError: true, message: 'Network Error' }], + ['a gateway timeout', apiError(504, undefined, 'Gateway Timeout')], + ['a gateway’s 502', apiError(502, undefined, 'Bad Gateway')], + // The backend's catch-all handlers: an unexpected error could follow a create. + ['an unexpected error', apiError(500, '/errors/internal-error', 'An unexpected error occurred')], + ['an unexpected bad request', apiError(400, '/errors/bad-request', 'Invalid value')], + ])('clears the Check and warns that items might exist after %s', async (_, failure) => { + const user = userEvent.setup() + jest.mocked(operationsApi.publishFindings).mockRejectedValue(failure) + renderDialog() + const dialog = await checkFindings(user) + + await user.click(within(dialog).getByRole('button', { name: 'Publish' })) + + expect(await within(dialog).findByText(/Items might have been created anyway/)).toBeInTheDocument() + expect(within(dialog).queryByRole('region', { name: 'Check' })).not.toBeInTheDocument() + expect(within(dialog).getByRole('button', { name: 'Publish' })).toBeDisabled() + }) + + it.each(contract.problem_types.nothing_created)( + 'keeps the Check without warning after %s, which the backend returns before creating anything', + async (type) => { + const user = userEvent.setup() + jest.mocked(operationsApi.publishFindings).mockRejectedValue(apiError(503, type, 'Try again later.')) + renderDialog() + const dialog = await checkFindings(user) + + await user.click(within(dialog).getByRole('button', { name: 'Publish' })) + + expect(await within(dialog).findByText(/Could not publish findings: Try again later\./)).toBeInTheDocument() + expect(within(dialog).queryByText(/might have been created/)).not.toBeInTheDocument() + expect(within(dialog).getByRole('region', { name: 'Check' })).toBeInTheDocument() + }, + ) + + it('needs a new Check after the destination changes and changes back', async () => { + const user = userEvent.setup() + renderDialog() + const dialog = await checkFindings(user) + const destination = within(dialog).getByRole('textbox', { name: DESTINATION_LABEL }) + + await user.type(destination, '6') + await user.type(destination, '{Backspace}') + + expect(destination).toHaveValue('12345') + expect(within(dialog).queryByRole('region', { name: 'Check' })).not.toBeInTheDocument() + expect(within(dialog).getByRole('button', { name: 'Publish' })).toBeDisabled() + }) + + it('keeps the Check after the destination’s service is unavailable, so Publish can be tried again', async () => { + const user = userEvent.setup() + jest.mocked(operationsApi.publishFindings).mockRejectedValue( + apiError(502, '/errors/publisher-unavailable', 'Azure DevOps is unavailable.'), + ) + renderDialog() + const dialog = await checkFindings(user) + + await user.click(within(dialog).getByRole('button', { name: 'Publish' })) + + expect(await within(dialog).findByText(/Could not publish findings: Azure DevOps is unavailable\./)) + .toBeInTheDocument() + expect(within(dialog).getByRole('region', { name: 'Check' })).toBeInTheDocument() + expect(within(dialog).getByRole('button', { name: 'Publish' })).toBeEnabled() + }) + + it('shows why a Check failed', async () => { + const user = userEvent.setup() + jest.mocked(operationsApi.previewFindingPublish).mockRejectedValue( + apiError(400, '/errors/publish-destination', + "Work item 12345 doesn't exist, or the publishing identity can't see it."), + ) + renderDialog() + const dialog = await openDialog(user) + await user.type(within(dialog).getByRole('textbox', { name: DESTINATION_LABEL }), '12345') + + await user.click(within(dialog).getByRole('button', { name: 'Check' })) + + expect(await within(dialog).findByText(/Could not check findings: Work item 12345 doesn't exist/)) + .toBeInTheDocument() + expect(within(dialog).getByRole('button', { name: 'Publish' })).toBeDisabled() + }) + + it('stays open with its controls disabled while publishing', async () => { + const user = userEvent.setup() + const pending = deferred() + jest.mocked(operationsApi.publishFindings).mockReturnValue(pending.promise) + renderDialog() + const dialog = await checkFindings(user) + + await user.click(within(dialog).getByRole('button', { name: 'Publish' })) + await user.keyboard('{Escape}') + + expect(screen.getByRole('dialog', { name: 'Publish findings' })).toBeInTheDocument() + expect(within(dialog).getByRole('button', { name: 'Publishing…' })).toHaveAttribute('aria-disabled', 'true') + expect(within(dialog).getByRole('button', { name: 'Cancel' })).toBeDisabled() + expect(within(dialog).getByRole('textbox', { name: DESTINATION_LABEL })).toBeDisabled() + expect(within(dialog).getByRole('checkbox', { name: 'Select all' })).toBeDisabled() + await act(async () => { pending.resolve(RESULT) }) + expect(await within(dialog).findByText(RESULT.run_id)).toBeInTheDocument() + }) + + it('starts over each time it opens', async () => { + const user = userEvent.setup() + jest.mocked(operationsApi.publishFindings).mockResolvedValue(RESULT) + renderDialog() + const dialog = await checkFindings(user) + await user.click(within(dialog).getByRole('button', { name: 'Publish' })) + await within(dialog).findByText(RESULT.run_id) + + await user.click(within(dialog).getByRole('button', { name: 'Close' })) + const reopened = await openDialog(user) + + expect(within(reopened).queryByText(RESULT.run_id)).not.toBeInTheDocument() + expect(within(reopened).getByRole('textbox', { name: DESTINATION_LABEL })).toHaveValue('') + expect(within(reopened).getByRole('button', { name: 'Publish' })).toBeDisabled() + }) + + it('says when the operation has no findings to publish', async () => { + const user = userEvent.setup() + jest.mocked(operationsApi.listFindings).mockResolvedValue({ items: [], has_more: false, next_offset: null }) + renderDialog() + await user.click(screen.getByRole('button', { name: 'Publish findings' })) + const dialog = screen.getByRole('dialog', { name: 'Publish findings' }) + + expect(await within(dialog).findByText('This operation has no findings to publish.')).toBeInTheDocument() + await user.type(within(dialog).getByRole('textbox', { name: DESTINATION_LABEL }), '12345') + expect(within(dialog).getByRole('button', { name: 'Check' })).toBeDisabled() + }) + + it('offers to load the findings again after a failure', async () => { + const user = userEvent.setup() + jest.mocked(operationsApi.listFindings).mockRejectedValueOnce(new Error('Storage unavailable')) + renderDialog() + await user.click(screen.getByRole('button', { name: 'Publish findings' })) + const dialog = screen.getByRole('dialog', { name: 'Publish findings' }) + + expect(await within(dialog).findByText(/Could not load findings: Storage unavailable/)).toBeInTheDocument() + await user.click(within(dialog).getByRole('button', { name: 'Retry' })) + expect(await within(dialog).findByRole('checkbox', { name: 'Select all' })).toBeInTheDocument() + }) +}) diff --git a/frontend/src/components/Operations/FindingPublishDialog.tsx b/frontend/src/components/Operations/FindingPublishDialog.tsx new file mode 100644 index 0000000000..0dab6bd2ee --- /dev/null +++ b/frontend/src/components/Operations/FindingPublishDialog.tsx @@ -0,0 +1,344 @@ +import { useEffect, useRef, useState, type MutableRefObject, type SetStateAction } from 'react' + +import { + Button, Dialog, DialogActions, DialogBody, DialogContent, DialogSurface, DialogTitle, DialogTrigger, + Field, Input, Link, mergeClasses, MessageBar, MessageBarBody, Spinner, Text, +} from '@fluentui/react-components' +import { CloudArrowUpRegular } from '@fluentui/react-icons' + +import { useAllOperationFindings } from '@/hooks/useAllOperationFindings' +import { useFindingPublish, type FindingPublishCheck } from '@/hooks/useFindingPublish' +import type { + FindingFields, FindingListItem, FindingPublishDestination, FindingPublisherListItem, FindingPublishPreview, + FindingPublishPreviewRequest, FindingPublishReference, FindingPublishResult, Operation, +} from '@/types' +import { findingChildren, findingTreeSelection } from '@/utils/findingTree' +import { fluentRef } from '@/utils/fluentRef' + +import { useFindingPublishDialogStyles } from './FindingPublishDialog.styles' +import FindingSelectionTree from './FindingSelectionTree' + +const NO_FINDINGS: readonly FindingListItem[] = [] +const WEB_URL = /^https?:\/\//i + +interface FindingPublishDialogProps { + operation: Operation + /** The active finding fields, which decide the severity badges. */ + fields: FindingFields + /** Changes when the active fields change, which loads the findings again with the new labels. */ + fieldsRevision: number + /** The publisher to check and publish with, which also labels the destination input. */ + publisher: FindingPublisherListItem +} + +/** + * Publishes selected findings to another system. **Check** shows where each finding will go; **Publish** then + * creates exactly that and shows every finding's outcome. + */ +export default function FindingPublishDialog({ operation, fields, fieldsRevision, publisher }: FindingPublishDialogProps) { + const styles = useFindingPublishDialogStyles() + const [open, setOpen] = useState(false) + // Each opening starts a new session, with nothing selected, checked or published yet. + const [session, setSession] = useState(0) + // The dialog stays open while a publish runs, so its result is never lost. + const publishingRef = useRef(false) + const triggerRef = useRef(null) + + useEffect(() => { + if (!open) return + const trigger = triggerRef.current + // Tabster's restore depends on the browser reporting focus loss from the removed dialog; don't rely on it. + return () => { trigger?.focus() } + }, [open]) + + return ( + { + if (data.open) { + setSession(value => value + 1) + setOpen(true) + } else if (!publishingRef.current) { + setOpen(false) + } + }}> + + + + + + + + ) +} + +interface FindingPublishSessionProps extends FindingPublishDialogProps { + /** True while a publish runs, so the dialog stays open until its result arrives. */ + publishingRef: MutableRefObject +} + +function FindingPublishSession({ + operation, fields, fieldsRevision, publisher, publishingRef, +}: FindingPublishSessionProps) { + const styles = useFindingPublishDialogStyles() + const { load, retry } = useAllOperationFindings(operation.id, fieldsRevision) + const { check, result, error, busy, runCheck, publish, clearCheck } = useFindingPublish(operation.id) + // Null until the user changes it: every top-level finding, with all of its sub-findings. + const [chosen, setChosen] = useState | null>(null) + const [destination, setDestination] = useState('') + const findings = load.status === 'loaded' ? load.findings : NO_FINDINGS + const everyFinding = new Set((findingChildren(findings).get(null) ?? []).map(finding => finding.id)) + const selected = chosen ?? everyFinding + const { selectedIds } = findingTreeSelection(findings, selected) + const request: FindingPublishPreviewRequest = { + finding_ids: selectedIds, publisher_name: publisher.name, destination, + } + // Changing the selection or the destination clears the Check. A reload for changed fields can change the selection + // too, so a Check also holds only for the request it answered. + const current = check !== null && sameRequest(check.request, request) ? check : null + const preview = current?.preview ?? null + const canCheck = busy === null && selectedIds.length > 0 && destination.trim() !== '' + const canPublish = busy === null && preview !== null && preview.problems.length === 0 && preview.planned.length > 0 + + const changeSelection = (update: SetStateAction>): void => { + setChosen(previous => typeof update === 'function' ? update(previous ?? everyFinding) : update) + clearCheck() + } + + const publishChecked = async (checked: FindingPublishCheck): Promise => { + publishingRef.current = true + try { + await publish(checked) + } finally { + publishingRef.current = false + } + } + + const renderFindings = (): React.ReactNode => { + if (load.status === 'loading') return + if (load.status === 'error') { + return ( + + Could not load findings: {load.error}{' '} + + + ) + } + if (findings.length === 0) return This operation has no findings to publish. + return ( + + ) + } + + if (result !== null) { + return ( + + Publish findings + + + + + + + + + + ) + } + + return ( + + Publish findings + + {error && + Could not {error.action} findings: {error.message} + } + {renderFindings()} + {/* Enter in the destination runs Check, never Publish, which is outside this form. */} +
{ + event.preventDefault() + if (canCheck) void runCheck(request) + }}> +
+ + {/* Stays focusable during a Check, which Enter here starts, so focus never leaves the dialog. Typing + drops a Check still running. */} + { + setDestination(data.value) + clearCheck() + }} /> + + +
+
+
{checkAnnouncement(preview)}
+ {preview !== null && } +
+ + + + + + +
+ ) +} + +function plural(count: number, noun: string): string { + return `${count} ${count === 1 ? noun : `${noun}s`}` +} + +function checkAgainNote(problems: number): string { + return `Fix ${plural(problems, 'problem')}, then check again.` +} + +/** What a finished Check found, for screen readers; the summary itself stays out of the announcement. */ +function checkAnnouncement(preview: FindingPublishPreview | null): string { + if (preview === null) return '' + const found = `Check found ${plural(preview.planned.length, 'finding')} to publish, ${preview.skipped.length} skipped.` + return preview.problems.length > 0 ? `${found} ${checkAgainNote(preview.problems.length)}` : found +} + +function sameRequest(first: FindingPublishPreviewRequest, second: FindingPublishPreviewRequest): boolean { + return first.publisher_name === second.publisher_name && first.destination === second.destination + && first.finding_ids.length === second.finding_ids.length + && first.finding_ids.every((findingId, index) => findingId === second.finding_ids[index]) +} + +/** Where a Check says each selected finding will go. */ +function FindingPublishCheckSummary({ preview }: { preview: FindingPublishPreview }) { + const styles = useFindingPublishDialogStyles() + const titles = new Map(preview.planned.map(item => [item.finding_id, item.title])) + return ( +
+
+
Destination
+
+
Planned
+
+ { + const parent = item.parent_finding_id === null ? undefined : titles.get(item.parent_finding_id) + const partOf = item.part_of === null ? '' : ` · Part of: ${item.part_of}` + return `${item.title} → under ${parent ?? preview.destination.title}${partOf}` + }} /> +
+
Skipped
+
+ `${skip.title} · ${skip.reason}`} /> +
+
Problems
+
+ `${problem.title}: ${problem.message}`} /> +
+
+ {preview.problems.length > 0 ? ( + + {checkAgainNote(preview.problems.length)} + + ) : ( + + Publishing again creates new work items. + + )} +
+ ) +} + +/** Every finding's outcome in one publish run. */ +function FindingPublishOutcome({ result }: { result: FindingPublishResult }) { + const styles = useFindingPublishDialogStyles() + const complete = result.failure === null && result.stopped_reason === null + return ( + <> + + + {complete ? 'Published.' : 'The run stopped before every finding was published.'} Created{' '} + {result.created.length} {result.created.length === 1 ? 'item' : 'items'}. + + +
+
Run ID
+
{result.run_id}
+
Destination
+
+
Created
+
+ {result.created.length === 0 ? 'None' : ( +
    + {result.created.map(item => ( +
  • + +
  • + ))} +
+ )} +
+
Skipped
+
+ `${skip.title} · ${skip.reason}`} /> +
+ {result.failure !== null && <> +
Failure
+
+ {/* The publisher's message says what to do; when the item might exist, it says so, so it isn't repeated. */} + {result.failure.outcome_unknown && + Outcome unknown + } + + {result.failure.title}: {result.failure.message} + +
+ } + {result.stopped_reason !== null && <> +
Stopped
+
{result.stopped_reason}
+ } +
Not attempted
+
+ item.title} /> +
+
+ + ) +} + +interface ReferenceListProps { + items: readonly T[] + describe: (item: T) => string +} + +function ReferenceList({ items, describe }: ReferenceListProps) { + const styles = useFindingPublishDialogStyles() + if (items.length === 0) return <>None + return ( +
    + {items.map(item =>
  • {describe(item)}
  • )} +
+ ) +} + +function DestinationLink({ destination }: { destination: FindingPublishDestination }) { + const styles = useFindingPublishDialogStyles() + return ( + <> + + {destination.location && {destination.location}} + + ) +} + +/** A link that opens in a new tab, or plain text when the publisher gave no web address. */ +function WebLink({ url, text }: { url: string; text: string }) { + if (!WEB_URL.test(url)) return <>{text} + return {text} +} diff --git a/frontend/src/components/Operations/FindingSelectionTree.styles.ts b/frontend/src/components/Operations/FindingSelectionTree.styles.ts new file mode 100644 index 0000000000..13dfbcb53a --- /dev/null +++ b/frontend/src/components/Operations/FindingSelectionTree.styles.ts @@ -0,0 +1,42 @@ +import type { CSSProperties } from 'react' + +import { makeStyles, tokens } from '@fluentui/react-components' + +import { NARROW_VIEWPORT_QUERY } from '@/styles/touchTargets' + +// Fluent's medium Checkbox indicator. With its inline margins and the label's padding, a row's title starts after it. +const CHECKBOX_INDICATOR_SIZE = '16px' +const TITLE_INDENT = `calc(${tokens.spacingHorizontalS} * 2 + ${CHECKBOX_INDICATOR_SIZE} + ${tokens.spacingHorizontalXS})` +// Deeper sub-findings share the deepest indent so a long decomposition still fits a narrow dialog; each row names +// its parent for screen readers. +const MAX_INDENT_LEVELS = 4 + +/** A sub-finding row's indent, lining it up with its parent's title. */ +export function findingIndent(depth: number): CSSProperties | undefined { + if (depth <= 0) return undefined + return { paddingInlineStart: `calc(${TITLE_INDENT} * ${Math.min(depth, MAX_INDENT_LEVELS)})` } +} + +export const useFindingSelectionTreeStyles = makeStyles({ + list: { margin: 0, padding: 0, listStyleType: 'none' }, + // Read to screen readers; the indent and the locked check already show it on screen. + visuallyHidden: { + position: 'absolute', + width: '1px', + height: '1px', + padding: 0, + margin: '-1px', + overflow: 'hidden', + clip: 'rect(0, 0, 0, 0)', + whiteSpace: 'nowrap', + border: 0, + }, + row: { display: 'flex', flexWrap: 'wrap', alignItems: 'center', columnGap: tokens.spacingHorizontalS, minWidth: 0 }, + checkbox: { flex: '1 1 12rem', minWidth: 0 }, + label: { minWidth: 0, overflowWrap: 'anywhere' }, + created: { + color: tokens.colorNeutralForeground3, + // On narrow screens the time gets its own line, lined up under the title. + [NARROW_VIEWPORT_QUERY]: { flexBasis: '100%', paddingInlineStart: TITLE_INDENT }, + }, +}) diff --git a/frontend/src/components/Operations/FindingSelectionTree.test.tsx b/frontend/src/components/Operations/FindingSelectionTree.test.tsx new file mode 100644 index 0000000000..bf0202b322 --- /dev/null +++ b/frontend/src/components/Operations/FindingSelectionTree.test.tsx @@ -0,0 +1,79 @@ +import { useState } from 'react' + +import { render, screen } from '@testing-library/react' +import userEvent from '@testing-library/user-event' +import { FluentProvider, webLightTheme } from '@fluentui/react-components' + +import { DEFAULT_FINDING_FIELDS_FIXTURE } from '@/test-utils/findingFieldsFixtures' +import type { FindingListItem } from '@/types' +import FindingSelectionTree from './FindingSelectionTree' + +function finding(index: number, overrides: Partial = {}): FindingListItem { + return { + id: `finding-${index}`, operation_id: 'operation-1', title: `Finding ${index}`, severity: 'moderate', + field_values: {}, created_at: `2026-12-01T12:0${index}:00Z`, evidence_count: 0, rows: [], retired: [], + parent_finding_id: null, demonstrated: true, paths: [], child_count: 0, ...overrides, + } +} + +const PARENT = finding(1, { title: 'Parent' }) +const CHILD = finding(2, { title: 'Child', parent_finding_id: PARENT.id }) +const GRANDCHILD = finding(3, { title: 'Grandchild', parent_finding_id: CHILD.id }) +const OTHER = finding(4, { title: 'Other' }) +const FINDINGS = [PARENT, OTHER, GRANDCHILD, CHILD] + +function Harness({ initial, disabled = false }: { initial: ReadonlySet; disabled?: boolean }) { + const [selected, setSelected] = useState(initial) + return ( + + + {[...selected].sort().join(',')} + + ) +} + +describe('FindingSelectionTree', () => { + it('lists sub-findings under their parents, naming each parent for screen readers', () => { + render() + + const rows = screen.getAllByRole('listitem').map(item => item.textContent ?? '') + expect(rows.map(row => row.split('Moderate')[0])).toEqual(['Parent', 'Child', 'Grandchild', 'Other']) + expect(screen.getByRole('checkbox', { name: 'Child' })).toHaveAccessibleDescription(/Sub-finding of “Parent”/) + }) + + it('includes every sub-finding of a chosen finding, which then can’t be unchecked alone', async () => { + const user = userEvent.setup() + render() + + await user.click(screen.getByRole('checkbox', { name: 'Parent' })) + + expect(screen.getByRole('checkbox', { name: 'Child' })).toBeChecked() + expect(screen.getByRole('checkbox', { name: 'Child' })).toBeDisabled() + expect(screen.getByRole('checkbox', { name: 'Grandchild' })).toBeChecked() + expect(screen.getByRole('checkbox', { name: 'Grandchild' })).toHaveAccessibleDescription(/Included with “Child”/) + // The parent now includes the child, so the child's own choice is dropped. + expect(screen.getByRole('status', { name: 'Selected' })).toHaveTextContent(PARENT.id) + expect(screen.getByRole('checkbox', { name: 'Select all' })).toBePartiallyChecked() + }) + + it('selects every top-level finding, then nothing', async () => { + const user = userEvent.setup() + render() + const selectAll = screen.getByRole('checkbox', { name: 'Select all' }) + + await user.click(selectAll) + expect(selectAll).toBeChecked() + expect(screen.getByRole('status', { name: 'Selected' })).toHaveTextContent(`${PARENT.id},${OTHER.id}`) + + await user.click(selectAll) + expect(selectAll).not.toBeChecked() + expect(screen.getByRole('status', { name: 'Selected' })).toBeEmptyDOMElement() + }) + + it('disables every box while disabled', () => { + render() + + for (const checkbox of screen.getAllByRole('checkbox')) expect(checkbox).toBeDisabled() + }) +}) diff --git a/frontend/src/components/Operations/FindingSelectionTree.tsx b/frontend/src/components/Operations/FindingSelectionTree.tsx new file mode 100644 index 0000000000..7241251b71 --- /dev/null +++ b/frontend/src/components/Operations/FindingSelectionTree.tsx @@ -0,0 +1,83 @@ +import { useId, type Dispatch, type SetStateAction } from 'react' + +import { Checkbox, Text } from '@fluentui/react-components' + +import type { FindingFields, FindingListItem } from '@/types' +import { findingDescendantIds, findingTreeSelection, flattenFindingTree } from '@/utils/findingTree' + +import { findingIndent, useFindingSelectionTreeStyles } from './FindingSelectionTree.styles' +import FindingSeverityBadge from './FindingSeverityBadge' + +const NO_SELECTION: ReadonlySet = new Set() + +interface FindingSelectionTreeProps { + /** Every finding of the operation, in listing order. */ + findings: readonly FindingListItem[] + /** The active finding fields, which decide the severity badges. */ + fields: FindingFields + /** The findings the user chose. A chosen finding includes all of its sub-findings. */ + selected: ReadonlySet + onSelectedChange: Dispatch>> + disabled: boolean +} + +/** + * A "Select all" box and every finding as a checkbox, sub-findings indented under their parents. Choosing a finding + * includes its sub-findings, which then show as checked and can't be unchecked alone. + */ +export default function FindingSelectionTree({ + findings, fields, selected, onSelectedChange, disabled, +}: FindingSelectionTreeProps) { + const styles = useFindingSelectionTreeStyles() + const rowId = useId() + const { children, roots, implied, included, allSelected } = findingTreeSelection(findings, selected) + const selectAllChecked = allSelected ? true : included.length === 0 ? false : 'mixed' + const titles = new Map(findings.map(finding => [finding.id, finding.title])) + + const toggle = (findingId: string, checked: boolean): void => { + onSelectedChange(current => { + const next = new Set(current) + if (checked) { + next.add(findingId) + // Its sub-findings are now included with it, so they no longer need their own selection. + for (const descendant of findingDescendantIds(children, findingId)) next.delete(descendant) + } else { + next.delete(findingId) + } + return next + }) + } + + // One flat list in tree order: nesting elements per level would recurse once per level of a deep decomposition. + return ( + <> + { onSelectedChange(allSelected ? NO_SELECTION : new Set(roots.map(finding => finding.id))) }} /> +
    + {flattenFindingTree(findings).map(({ finding, depth }) => { + const createdId = `${rowId}-${finding.id}-created` + const relationId = `${rowId}-${finding.id}-relation` + const isImplied = implied.has(finding.id) + const parentTitle = depth > 0 && finding.parent_finding_id ? titles.get(finding.parent_finding_id) : undefined + return ( +
  • + { toggle(finding.id, data.checked === true) }} /> + + {parentTitle !== undefined && + {isImplied ? 'Included with' : 'Sub-finding of'} “{parentTitle}” + } + + + +
  • + ) + })} +
+ + ) +} diff --git a/frontend/src/components/Operations/OperationDetailPage.test.tsx b/frontend/src/components/Operations/OperationDetailPage.test.tsx index c4829707ed..3becc0d78f 100644 --- a/frontend/src/components/Operations/OperationDetailPage.test.tsx +++ b/frontend/src/components/Operations/OperationDetailPage.test.tsx @@ -4,7 +4,7 @@ import { FluentProvider, webLightTheme } from '@fluentui/react-components' import type { ReactElement } from 'react' import { createMemoryRouter, MemoryRouter, Route, RouterProvider, Routes } from 'react-router' -import { attacksApi, operationsApi, scenariosApi } from '@/services/api' +import { attacksApi, findingPublishersApi, operationsApi, scenariosApi } from '@/services/api' import { useRuntime } from '@/hooks/useRuntime' import { ThemeProvider } from '@/hooks/useTheme' import { UserPreferencesProvider } from '@/hooks/useUserPreferences' @@ -24,6 +24,7 @@ jest.mock('@/services/api', () => ({ }, attacksApi: { listAttacks: jest.fn() }, scenariosApi: { listRuns: jest.fn() }, + findingPublishersApi: { list: jest.fn() }, })) jest.mock('@/hooks/useRuntime', () => ({ ...jest.requireActual('@/hooks/useRuntime'), useRuntime: jest.fn() })) @@ -85,6 +86,47 @@ beforeEach(() => { jest.mocked(operationsApi.detachFindingEvidence).mockResolvedValue(undefined) jest.mocked(attacksApi.listAttacks).mockResolvedValue({ items: [], pagination: { limit: 5, has_more: false } }) jest.mocked(scenariosApi.listRuns).mockResolvedValue({ items: [], pagination: { limit: 5, has_more: false } }) + jest.mocked(findingPublishersApi.list).mockResolvedValue({ items: [] }) +}) + +it('offers Publish findings only when the deployment registers a publisher', async () => { + renderPage() + expect(await screen.findByRole('button', { name: 'Export findings' })).toBeInTheDocument() + expect(findingPublishersApi.list).toHaveBeenCalled() + expect(screen.queryByRole('button', { name: 'Publish findings' })).not.toBeInTheDocument() +}) + +it('says when the publishers can’t be read and offers to read them again', async () => { + const user = userEvent.setup() + jest.mocked(findingPublishersApi.list).mockRejectedValueOnce(new Error('Service unavailable')) + jest.mocked(findingPublishersApi.list).mockResolvedValueOnce({ + items: [{ name: 'azure_devops', info: { destination_label: 'Work item', destination_hint: 'Paste its ID.' } }], + }) + renderPage() + + expect(await screen.findByText(/Could not load finding publishers: Service unavailable/)).toBeInTheDocument() + expect(screen.queryByRole('button', { name: 'Publish findings' })).not.toBeInTheDocument() + await user.click(screen.getByRole('button', { name: 'Retry finding publishers' })) + + expect(await screen.findByRole('button', { name: 'Publish findings' })).toBeInTheDocument() + expect(screen.queryByText(/Could not load finding publishers/)).not.toBeInTheDocument() +}) + +it('shows Publish findings with the first publisher when one is registered', async () => { + const user = userEvent.setup() + jest.mocked(findingPublishersApi.list).mockResolvedValue({ + items: [ + { name: 'azure_devops', info: { destination_label: 'Operation work item', destination_hint: 'Paste its ID.' } }, + { name: 'zeta', info: { destination_label: 'Folder', destination_hint: 'Name a folder.' } }, + ], + }) + renderPage() + + await user.click(await screen.findByRole('button', { name: 'Publish findings' })) + + const dialog = screen.getByRole('dialog', { name: 'Publish findings' }) + expect(within(dialog).getByRole('textbox', { name: 'Operation work item' })).toBeInTheDocument() + expect(within(dialog).getByText('Paste its ID.')).toBeInTheDocument() }) it('renames the operation and edits its description, keeping the draft after a failed or conflicting save', async () => { diff --git a/frontend/src/components/Operations/OperationDetailPage.tsx b/frontend/src/components/Operations/OperationDetailPage.tsx index 89d36b673a..fe8d396211 100644 --- a/frontend/src/components/Operations/OperationDetailPage.tsx +++ b/frontend/src/components/Operations/OperationDetailPage.tsx @@ -8,11 +8,13 @@ import { AddRegular, ArrowLeftRegular } from '@fluentui/react-icons' import { DEFAULT_HISTORY_FILTERS, filtersToSearchParams } from '@/components/History/historyFilters' import { useFindingFields } from '@/hooks/useFindingFields' +import { useFindingPublishers } from '@/hooks/useFindingPublishers' import { operationsApi } from '@/services/api' import { toApiError } from '@/services/errors' import type { FindingListItem, FindingListResponse, OperationDetail } from '@/types' import FindingDialog, { type FindingDraft, type FindingSaveAttempt } from './FindingDialog' import FindingExportDialog from './FindingExportDialog' +import FindingPublishDialog from './FindingPublishDialog' import FindingPathsDialog from './FindingPathsDialog' import FindingTreeItem, { type FindingTreeActions } from './FindingTreeItem' import OperationDeleteDialog from './OperationDeleteDialog' @@ -54,6 +56,9 @@ function OperationDetailContent({ operationId, onOperationChanged }: { operation const styles = useOperationsStyles() const navigate = useNavigate() const { fields, error: fieldsError, retry: retryFields, fieldsRevision } = useFindingFields(operationId) + // Publishing is offered only when the deployment registers a publisher; the dialog uses the first by name. + const { publishers, error: publishersError, retry: retryPublishers } = useFindingPublishers() + const publisher = publishers?.[0] const [params, setParams] = useSearchParams() const rawOffset = Number(params.get('offset') ?? 0) const offset = Number.isSafeInteger(rawOffset) && rawOffset >= 0 ? rawOffset : 0 @@ -246,6 +251,9 @@ function OperationDetailContent({ operationId, onOperationChanged }: { operation }} /> {fields !== null && } + {fields !== null && publisher !== undefined && } + } {fieldsError ? ( Could not load finding fields: {fieldsError}{' '} diff --git a/frontend/src/components/Operations/findingPublish.contract.json b/frontend/src/components/Operations/findingPublish.contract.json new file mode 100644 index 0000000000..158e369f55 --- /dev/null +++ b/frontend/src/components/Operations/findingPublish.contract.json @@ -0,0 +1,93 @@ +{ + "preview": { + "destination": { + "id": "12345", + "title": "Operation Contoso", + "url": "https://tracker.example.test/12345", + "location": "Example / Red Team" + }, + "planned": [ + { + "finding_id": "00000000-0000-0000-0000-000000000001", + "title": "Leaks the system prompt", + "parent_finding_id": null, + "part_of": null + }, + { + "finding_id": "00000000-0000-0000-0000-000000000002", + "title": "Decodes Base64", + "parent_finding_id": "00000000-0000-0000-0000-000000000001", + "part_of": null + }, + { + "finding_id": "00000000-0000-0000-0000-000000000003", + "title": "Writes the payload", + "parent_finding_id": null, + "part_of": "Earlier finding" + } + ], + "skipped": [ + { + "finding_id": "00000000-0000-0000-0000-000000000004", + "title": "Role-play", + "reason": "Not demonstrated" + } + ], + "problems": [], + "plan_digest": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" + }, + "result": { + "run_id": "0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f", + "destination": { + "id": "12345", + "title": "Operation Contoso", + "url": "https://tracker.example.test/12345", + "location": "Example / Red Team" + }, + "created": [ + { + "finding_id": "00000000-0000-0000-0000-000000000001", + "title": "Leaks the system prompt", + "external_id": "101", + "url": "https://tracker.example.test/101", + "parent_external_id": "12345" + } + ], + "skipped": [ + { + "finding_id": "00000000-0000-0000-0000-000000000004", + "title": "Role-play", + "reason": "Not demonstrated" + } + ], + "failure": { + "finding_id": "00000000-0000-0000-0000-000000000002", + "title": "Decodes Base64", + "message": "The service didn't answer.", + "outcome_unknown": true + }, + "stopped_reason": null, + "not_attempted": [ + { + "finding_id": "00000000-0000-0000-0000-000000000003", + "title": "Writes the payload" + } + ] + }, + "problem_types": { + "check_again": [ + "/errors/publish-plan-changed", + "/errors/publish-problems", + "/errors/publish-too-many", + "/errors/validation-error" + ], + "nothing_created": [ + "/errors/not-found", + "/errors/public-origin", + "/errors/publish-deadline", + "/errors/publish-destination", + "/errors/publisher-misconfigured", + "/errors/publisher-unavailable" + ] + } +} diff --git a/frontend/src/hooks/useAllOperationFindings.ts b/frontend/src/hooks/useAllOperationFindings.ts new file mode 100644 index 0000000000..827bb71e63 --- /dev/null +++ b/frontend/src/hooks/useAllOperationFindings.ts @@ -0,0 +1,73 @@ +import { useCallback, useEffect, useState } from 'react' + +import { operationsApi } from '@/services/api' +import { toApiError } from '@/services/errors' +import type { FindingListItem } from '@/types' + +const PAGE_SIZE = 100 + +/** + * Reads every finding of an operation, page by page. A finding created while pages load shifts later pages, so a + * row a later page repeats keeps its first place. + * @param isCancelled - Checked after each page; once true, loading stops. + * @returns The findings in listing order, or null when loading was cancelled. + */ +export async function loadAllOperationFindingsAsync( + operationId: string, isCancelled: () => boolean, +): Promise { + const loaded = new Map() + const seenOffsets = new Set() + let offset: number | null = 0 + while (offset !== null) { + // A repeated offset means the server is not advancing the page, and + // fetching it again would loop forever, so stop with an error the + // same way the shared pagination helper treats a cyclic cursor. + if (seenOffsets.has(offset)) { + throw new Error('The findings page offset did not advance.') + } + seenOffsets.add(offset) + const page = await operationsApi.listFindings(operationId, { limit: PAGE_SIZE, offset }) + if (isCancelled()) return null + for (const finding of page.items) { + if (!loaded.has(finding.id)) loaded.set(finding.id, finding) + } + offset = page.has_more ? page.next_offset : null + } + return [...loaded.values()] +} + +type OperationFindingsLoad = + | { status: 'loading' } + | { status: 'error'; error: string } + | { status: 'loaded'; findings: FindingListItem[] } + +interface AllOperationFindings { + readonly load: OperationFindingsLoad + readonly retry: () => void +} + +/** + * Loads every finding of an operation when the caller mounts, and again when `fieldsRevision` changes, because + * changed finding fields relabel them. + */ +export function useAllOperationFindings(operationId: string, fieldsRevision: number): AllOperationFindings { + const [attempt, setAttempt] = useState(0) + // Each result carries the request it answers, so an earlier one shows as still loading. + const key = JSON.stringify([operationId, fieldsRevision, attempt]) + const [result, setResult] = useState<{ key: string; load: OperationFindingsLoad } | null>(null) + + useEffect(() => { + let ignore = false + loadAllOperationFindingsAsync(operationId, () => ignore) + .then(findings => { + if (findings !== null) setResult({ key, load: { status: 'loaded', findings } }) + }) + .catch((cause: unknown) => { + if (!ignore) setResult({ key, load: { status: 'error', error: toApiError(cause).detail } }) + }) + return () => { ignore = true } + }, [key, operationId]) + + const retry = useCallback(() => { setAttempt(value => value + 1) }, []) + return { load: result?.key === key ? result.load : { status: 'loading' }, retry } +} diff --git a/frontend/src/hooks/useFindingPublish.ts b/frontend/src/hooks/useFindingPublish.ts new file mode 100644 index 0000000000..b058b31bdc --- /dev/null +++ b/frontend/src/hooks/useFindingPublish.ts @@ -0,0 +1,109 @@ +import { useCallback, useEffect, useRef, useState } from 'react' + +import contract from '@/components/Operations/findingPublish.contract.json' +import { operationsApi } from '@/services/api' +import { apiErrorMessage, toApiError } from '@/services/errors' +import type { FindingPublishPreview, FindingPublishPreviewRequest, FindingPublishResult } from '@/types' + +// The backend returns these problems only before a Publish creates anything; once it creates, every outcome is in +// its 200 result. Its tests check the shared list against the problems its routes return. +/** Problems after which the same Check can be published again once the cause is fixed. */ +const NOTHING_CREATED_TYPES: ReadonlySet = new Set(contract.problem_types.nothing_created) +/** Problems after which a Publish needs a different selection or a new Check. */ +const CHECK_AGAIN_TYPES: ReadonlySet = new Set(contract.problem_types.check_again) +// Any other failure, such as no response or a gateway's error, may follow a create, so it clears the Check and warns. +const OUTCOME_UNKNOWN = 'Items might have been created anyway. Look in the destination before publishing again.' + +/** A Check and the request it answered. */ +export interface FindingPublishCheck { + readonly request: FindingPublishPreviewRequest + readonly preview: FindingPublishPreview +} + +interface FindingPublishFailureMessage { + readonly action: 'check' | 'publish' + readonly message: string +} + +interface FindingPublishSession { + /** The last Check that succeeded, until a Publish needs a new one. */ + readonly check: FindingPublishCheck | null + readonly result: FindingPublishResult | null + readonly error: FindingPublishFailureMessage | null + readonly busy: 'checking' | 'publishing' | null + readonly runCheck: (request: FindingPublishPreviewRequest) => Promise + /** Publishes exactly what `check` showed, sending its plan digest. */ + readonly publish: (check: FindingPublishCheck) => Promise + /** Drops the Check, and any Check still running, after the selection or the destination changed. */ + readonly clearCheck: () => void +} + +/** Runs one dialog's Checks and its Publish against an operation, keeping what the server returned. */ +export function useFindingPublish(operationId: string): FindingPublishSession { + const [check, setCheck] = useState(null) + const [result, setResult] = useState(null) + const [error, setError] = useState(null) + const [busy, setBusy] = useState<'checking' | 'publishing' | null>(null) + // Only the latest Check may show; an earlier one that answers late is dropped. + const latestCheck = useRef(0) + const publishing = useRef(false) + const session = useRef(null) + + useEffect(() => { + const controller = new AbortController() + session.current = controller + return () => { controller.abort() } + }, []) + + const runCheck = useCallback(async (request: FindingPublishPreviewRequest): Promise => { + const signal = session.current?.signal + if (publishing.current || signal === undefined || signal.aborted) return + const attempt = latestCheck.current + 1 + latestCheck.current = attempt + setBusy('checking') + setError(null) + try { + const preview = await operationsApi.previewFindingPublish(operationId, request, signal) + if (latestCheck.current === attempt) setCheck({ request, preview }) + } catch (cause: unknown) { + if (signal.aborted || latestCheck.current !== attempt) return + setCheck(null) + setError({ action: 'check', message: apiErrorMessage(toApiError(cause)) }) + } finally { + if (!signal.aborted && latestCheck.current === attempt) setBusy(null) + } + }, [operationId]) + + const publish = useCallback(async (checked: FindingPublishCheck): Promise => { + if (publishing.current) return + publishing.current = true + // A Check still running would answer for a request that is no longer the one being published. + latestCheck.current += 1 + setBusy('publishing') + setError(null) + try { + setResult(await operationsApi.publishFindings(operationId, { + ...checked.request, plan_digest: checked.preview.plan_digest, + })) + } catch (cause: unknown) { + const apiError = toApiError(cause) + const nothingCreated = apiError.type !== undefined && NOTHING_CREATED_TYPES.has(apiError.type) + if (!nothingCreated) setCheck(null) + const known = nothingCreated || (apiError.type !== undefined && CHECK_AGAIN_TYPES.has(apiError.type)) + const message = apiErrorMessage(apiError) + setError({ action: 'publish', message: known ? message : `${message} ${OUTCOME_UNKNOWN}` }) + } finally { + publishing.current = false + setBusy(null) + } + }, [operationId]) + + const clearCheck = useCallback((): void => { + // A Check still running answers for the request before the change, so it is dropped too. + latestCheck.current += 1 + setCheck(null) + if (!publishing.current) setBusy(null) + }, []) + + return { check, result, error, busy, runCheck, publish, clearCheck } +} diff --git a/frontend/src/hooks/useFindingPublishers.ts b/frontend/src/hooks/useFindingPublishers.ts new file mode 100644 index 0000000000..c952f04d8b --- /dev/null +++ b/frontend/src/hooks/useFindingPublishers.ts @@ -0,0 +1,45 @@ +import { useCallback, useEffect, useState } from 'react' + +import { findingPublishersApi } from '@/services/api' +import { toApiError } from '@/services/errors' +import type { FindingPublisherListItem } from '@/types' + +import { useRuntime } from './useRuntime' + +interface FindingPublishersState { + /** Null until the list first loads. A reload keeps the last list until the new one arrives. */ + readonly publishers: readonly FindingPublisherListItem[] | null + /** The last load failure, or an empty string. */ + readonly error: string + readonly retry: () => void +} + +/** + * Loads the finding publishers the deployment registers, and again when the runtime generation changes, because + * reinitializing can add or remove them. Publishing is offered only once the list has loaded with a publisher in it. + */ +export function useFindingPublishers(): FindingPublishersState { + const { generation } = useRuntime() + const [publishers, setPublishers] = useState(null) + const [error, setError] = useState('') + const [attempt, setAttempt] = useState(0) + + useEffect(() => { + let ignore = false + findingPublishersApi.list() + .then(response => { + if (ignore) return + setPublishers(response.items) + setError('') + }) + .catch((cause: unknown) => { if (!ignore) setError(toApiError(cause).detail) }) + return () => { ignore = true } + }, [attempt, generation]) + + const retry = useCallback(() => { + setError('') + setAttempt(value => value + 1) + }, []) + + return { publishers, error, retry } +} diff --git a/frontend/src/services/api.ts b/frontend/src/services/api.ts index 7420355d0d..5c082df5cd 100644 --- a/frontend/src/services/api.ts +++ b/frontend/src/services/api.ts @@ -107,6 +107,11 @@ import type { FindingEvidenceAttachResponse, FindingEvidenceListResponse, FindingExportRequest, + FindingPublisherListResponse, + FindingPublishPreview, + FindingPublishPreviewRequest, + FindingPublishRequest, + FindingPublishResult, Operation, OperationCreate, OperationDetail, @@ -222,6 +227,24 @@ export const operationsApi = { `${operationPath(operationId)}/findings/export`, request, withConfig({ responseType: 'blob', signal }), )).data }, + /** Checks where selected findings would go with a publisher. Writes nothing. */ + previewFindingPublish: async ( + operationId: string, request: FindingPublishPreviewRequest, signal?: AbortSignal, + ): Promise => { + return (await apiClient.post( + `${operationPath(operationId)}/findings/publish/preview`, request, withConfig({ signal }), + )).data + }, + /** Creates the items a Check showed. Once creating starts, every outcome comes back in the result. */ + publishFindings: async (operationId: string, request: FindingPublishRequest): Promise => { + return (await apiClient.post(`${operationPath(operationId)}/findings/publish`, request)).data + }, +} + +export const findingPublishersApi = { + list: async (): Promise => { + return (await apiClient.get('/finding-publishers')).data + }, } const apiClient = axios.create({ diff --git a/frontend/src/types/index.ts b/frontend/src/types/index.ts index 958ab42171..8afabc18cf 100644 --- a/frontend/src/types/index.ts +++ b/frontend/src/types/index.ts @@ -2891,6 +2891,101 @@ export interface FindingExportRequest { dashboard_origin: string } +/** How a finding publisher asks for its destination: the input's label and the hint under it. */ +export interface FindingPublisherInfo { + destination_label: string + destination_hint: string +} + +/** A finding publisher the deployment registers. */ +export interface FindingPublisherListItem { + name: string + info: FindingPublisherInfo +} + +/** The registered finding publishers, sorted by name. An empty list means publishing isn't offered. */ +export interface FindingPublisherListResponse { + items: FindingPublisherListItem[] +} + +/** Selected findings of one Operation to check with a publisher. Each includes all of its sub-findings. */ +export interface FindingPublishPreviewRequest { + finding_ids: string[] + publisher_name: string + /** The existing item that new items go under, as the user wrote it. */ + destination: string +} + +/** A publish of exactly what the Check with `plan_digest` showed. */ +export interface FindingPublishRequest extends FindingPublishPreviewRequest { + plan_digest: string +} + +/** The existing item that new items go under; `location` names where they're created. */ +export interface FindingPublishDestination { + id: string + title: string + url: string + location: string +} + +export interface FindingPublishReference { + finding_id: string + title: string +} + +/** + * A finding a publish would create an item for. It goes under its planned parent's new item, or under the + * destination when `parent_finding_id` is null; `part_of` names a parent it doesn't go under. + */ +export interface FindingPublishPreviewItem extends FindingPublishReference { + parent_finding_id: string | null + part_of: string | null +} + +/** A selected finding that a publish leaves out, and why. */ +export interface FindingPublishSkip extends FindingPublishReference { + reason: string +} + +/** A planned finding that can't be published until it is fixed. */ +export interface FindingPublishProblem extends FindingPublishReference { + message: string +} + +/** Where every selected finding would go; `planned` lists parents before their children. */ +export interface FindingPublishPreview { + destination: FindingPublishDestination + planned: FindingPublishPreviewItem[] + skipped: FindingPublishSkip[] + problems: FindingPublishProblem[] + plan_digest: string +} + +/** An item a publish created, and the item it went under. */ +export interface FindingPublishedItem extends FindingPublishReference { + external_id: string + url: string + parent_external_id: string +} + +/** The finding whose item failed, which stopped the run. `outcome_unknown` means the item might exist anyway. */ +export interface FindingPublishFailure extends FindingPublishReference { + message: string + outcome_unknown: boolean +} + +/** Every outcome of one publish run; `run_id` is recorded in each created item. */ +export interface FindingPublishResult { + run_id: string + destination: FindingPublishDestination + created: FindingPublishedItem[] + skipped: FindingPublishSkip[] + failure: FindingPublishFailure | null + stopped_reason: string | null + not_attempted: FindingPublishReference[] +} + /** A flagged share of applicable conversations with a 90% Wilson interval; `rate` is null when none apply. */ export interface AssertBinaryRate { rate: number | null diff --git a/frontend/src/utils/findingTree.ts b/frontend/src/utils/findingTree.ts index a405995be0..8ffd476128 100644 --- a/frontend/src/utils/findingTree.ts +++ b/frontend/src/utils/findingTree.ts @@ -75,6 +75,37 @@ export function findingDescendantIds( return descendants } +/** What a selection of findings includes, given that a selected finding includes all of its sub-findings. */ +export interface FindingTreeSelection { + readonly children: ReadonlyMap + readonly roots: readonly T[] + /** Findings included with a selected ancestor, which show as checked and can't be unchecked alone. */ + readonly implied: ReadonlySet + /** Every finding the selection includes, in listing order. */ + readonly included: readonly T[] + /** The selected findings to send, in tree order, leaving out those an ancestor already includes. */ + readonly selectedIds: string[] + /** Whether the selection includes every finding. */ + readonly allSelected: boolean +} + +/** Works out what the selected findings include, for a selection tree and the request it sends. */ +export function findingTreeSelection( + findings: readonly T[], selected: ReadonlySet, +): FindingTreeSelection { + const children = findingChildren(findings) + const implied = new Set(findings.filter(finding => selected.has(finding.id)) + .flatMap(finding => findingDescendantIds(children, finding.id))) + const included = findings.filter(finding => selected.has(finding.id) || implied.has(finding.id)) + const selectedIds = flattenFindingTree(findings) + .map(({ finding }) => finding.id) + .filter(findingId => selected.has(findingId) && !implied.has(findingId)) + return { + children, roots: children.get(null) ?? [], implied, included, selectedIds, + allSelected: included.length === findings.length, + } +} + /** * The numbers the report gives a finding's direct sub-findings: the parent's number, then each one's position in the * order listed, so "1.2" is the second sub-finding of finding 1. diff --git a/infra/README.md b/infra/README.md index ea0c9a2a7a..a58f1935c6 100644 --- a/infra/README.md +++ b/infra/README.md @@ -527,7 +527,7 @@ Each internal app stage (test, and prod after approval) does these steps in sequ 2. Preview, then create or update the manual ACA job `-migrate` from `infra/migration.bicep`. This does not start the job. The job uses the built image, the app managed identity, and the app configuration sources. If job preparation fails, the running app is not stopped. Before updating the job, and again before starting each of its executions in steps 3, 4 and 6, the stage lists the job's executions. If any execution has not finished (its status is not `Succeeded`, `Failed`, `Stopped` or `Degraded`), for example a migration started by a canceled deployment, or if the list cannot be read, the stage aborts without deploying the app or stopping that execution; wait for it to finish, then run the stage again. Before step 5 the stage has not stopped the app, but a canceled deployment may already have stopped it; at step 6 the app stays offline. This check does not lock the job, so do not run two deployments of the same slot at once. 3. Start a check-only execution using the full deployed job template, changing only the migration container's arguments to `--check-only`, and wait up to about 10 minutes. This preserves its environment and resources. Every execution requires that the template's migration container still uses this deployment's image, so an update by another deployment cannot change the image that runs. It validates the database target and checks the schema without applying migrations. If it succeeds, skip steps 4–6: deploy without stopping the app, except as step 7 describes for a seeded deployment. If the execution fails, log the failure and continue to step 4. A template/start/status API error, interrupted execution, or polling timeout aborts deployment without stopping the app; a timed-out execution is stopped, and if the stop request fails, deployment reports an unknown execution state that must be confirmed before retrying. 4. Start a revision-check execution the same way with `--check-upgradable`, and wait up to about 10 minutes. It fails if the database is stamped with a revision that this image's migrations do not contain, which means a newer release already migrated it, or if the database is already at this image's head, so migrating cannot fix the schema mismatch (for example, a migration edited after it was deployed, a model change without a migration, or a manual database change). If it fails, abort deployment **without stopping the app**; deploy the newer release (or a later one), or investigate the schema mismatch. -5. Deactivate all active revisions and wait for their replicas, including replicas from inactive revisions, to stop. Each poll reads all revision states in one Azure API call. Missing or invalid replica counts do not count as zero. If shutdown is not confirmed, do not start the migration. The app is offline until step 7. This also supports a rerun when the app is already stopped. +5. Deactivate all active revisions and wait for their replicas, including replicas from inactive revisions, to stop. The wait outlasts the app's 300-second termination grace period, which lets requests in flight finish. Each poll reads all revision states in one Azure API call. Missing or invalid replica counts do not count as zero. If shutdown is not confirmed, do not start the migration. The app is offline until step 7. This also supports a rerun when the app is already stopped. 6. Start the job the same way, with the migration container's check arguments removed, and wait up to the job's 2-hour `replicaTimeout`. Before opening a database connection, it verifies that the connection string identifies the deployment server and database. It then upgrades the schema and checks it. The job logs list each applied revision with timestamps and data-backfill progress. If the migration fails or times out, stop. The app stays offline and is not deployed. Fix the cause and run the stage again. 7. Deploy the app with `PYRIT_REQUIRE_CURRENT_SCHEMA=true`. The app checks the schema and does not migrate. If the app template did not change (for example, a rerun with the same image), the stage activates the previous revision again, including when a successful check skipped migration on an already-stopped app. With `pyritConfigSeedUri`, a revision that kept running is first stopped as in step 5, so it starts with the seeded configuration; the app is briefly offline. @@ -742,6 +742,8 @@ Supported Azure integrations, including OpenAI, Content Safety, and Speech, can - **Network topology**: Public ACA-managed HTTPS ingress with optional `allowedCidr` plus VNet-integrated fixed NAT egress is the base topology. Front Door Premium is an optional inbound layer. Private Link plus disabled ACA public access makes Front Door the only public application path. The team ADO infrastructure stage enables this isolated-origin mode; default app-only runs preserve shared networking and the environment access mode. `allowedCidr` must be empty when Front Door is enabled; Bicep rejects the combination. - **Ingress vs. egress**: Front Door affects inbound requests only. The reserved NAT public IP remains the source for ACA-originated outbound connections. +- **Public origin**: Bicep sets `PYRIT_PUBLIC_ORIGIN` to `https://` plus the Front Door host name when Front Door is enabled, and the ACA host name otherwise. Links the backend writes into other systems, such as evidence links in published findings, open this origin; request headers never set it. +- **Shutdown**: The app's `terminationGracePeriodSeconds` is 300, above Front Door's 240-second timeout and within ACA's 600-second maximum, so a request still running when a revision stops, such as a finding publish, can finish before ACA kills the container. `stop_app` in `deploy_app.sh` checks for stopped replicas up to 90 times, 5 seconds apart (`PYRIT_STOP_POLL_ATTEMPTS`, `PYRIT_STOP_POLL_SECONDS`), which outlasts the grace period. - **NAT routing**: NAT Gateway supplies the outbound source IP only while the subnet's effective default route remains `Internet`. A UDR or propagated BGP `0.0.0.0/0` route to a firewall or gateway takes precedence; in that topology, allow-list the egress device's public IP instead. - **Network outputs**: `egressPublicIpAddress`, `natGatewayId`, `acaInfrastructureSubnetId`, and `vnetName` describe the created network. - **PIP lock**: `protectEgressPublicIp=true` creates a resource-scoped `CanNotDelete` lock. The internal ADO workflow enables it; community examples leave it disabled unless the operator explicitly opts in. diff --git a/infra/application.bicep b/infra/application.bicep index 9103b22ec2..2306b37864 100644 --- a/infra/application.bicep +++ b/infra/application.bicep @@ -280,9 +280,16 @@ resource containerApp 'Microsoft.App/containerApps@2024-03-01' = { : 'https://${acaOriginHostName},https://${frontDoorHostName}') : 'https://${acaOriginHostName}' } + // Evidence links written into other systems, such as published findings, open the public origin. + { + name: 'PYRIT_PUBLIC_ORIGIN' + value: enableFrontDoor ? 'https://${frontDoorHostName}' : 'https://${acaOriginHostName}' + } ] } ] + // Above Front Door's 240-second timeout, so a request in flight during a deployment can finish. ACA allows 600. + terminationGracePeriodSeconds: 300 scale: { minReplicas: minReplicas maxReplicas: maxReplicas diff --git a/infra/pipelines/deploy_app.sh b/infra/pipelines/deploy_app.sh index 50e6d9631e..8c71fcdb7f 100644 --- a/infra/pipelines/deploy_app.sh +++ b/infra/pipelines/deploy_app.sh @@ -125,7 +125,8 @@ stop_app() { --resource-group "$PYRIT_DEPLOYMENT_RESOURCE_GROUP" --name "$PYRIT_APP_NAME" --revision "$revision" -o none fi done <<< "$revision_names" - for ((attempt = 1; attempt <= ${PYRIT_STOP_POLL_ATTEMPTS:-60}; attempt++)); do + # The checks outlast the app's 300-second termination grace period, which lets requests in flight finish. + for ((attempt = 1; attempt <= ${PYRIT_STOP_POLL_ATTEMPTS:-90}; attempt++)); do if ! revisions=$(az containerapp revision list \ --resource-group "$PYRIT_DEPLOYMENT_RESOURCE_GROUP" --name "$PYRIT_APP_NAME" --all -o json); then deployment_error "Could not read app revisions to confirm shutdown" diff --git a/pyrit/backend/README.md b/pyrit/backend/README.md index a9b5da2bf2..13b72ab9c0 100644 --- a/pyrit/backend/README.md +++ b/pyrit/backend/README.md @@ -689,6 +689,38 @@ offer a bounded restart. Copy/branch, manual continuation, export and assessment stay disabled until the selected transcript is complete; legacy active/manual read behavior is unchanged. +### Publishing findings + +A deployment offers publishing by registering a `FindingPublisher` in +`FindingPublisherRegistry`, usually from an initializer. +`GET /api/finding-publishers` lists each one's `name` and `info`, sorted by name; +an empty list means publishing isn't offered. + +`POST /api/operations/{operation_id}/findings/publish/preview` (**Check**) takes +`finding_ids`, `publisher_name` and `destination`, and returns where each finding +would go, the skipped findings, any problems and a `plan_digest`, without writing +anything. `POST /api/operations/{operation_id}/findings/publish` takes the same +fields plus that `plan_digest`, and creates only what the Check showed. Once it +starts creating items, it returns 200 with every finding's outcome, even after a +failure. Publishing again creates new items. + +A request takes at most 100 findings, counting sub-findings, and has 210 seconds. +The publish is for the signed-in user. Evidence links open `PYRIT_PUBLIC_ORIGIN`. + +| Status | Meaning | +|---|---| +| 400 | The destination can't be used. | +| 404 | The Operation, a finding or the publisher doesn't exist. | +| 409 | The plan changed since the Check; check again. | +| 422 | Too many findings, or a Publish with problems (one `errors` entry each). | +| 502 | The destination's service is unavailable or rejected the server's credentials. | +| 503 | Out of time before creating anything, or `PYRIT_PUBLIC_ORIGIN` isn't set. | +| 500 | The publisher can't represent the finding fields; the log says why. | + +The publisher writes with the server's own credentials, such as its managed +identity, so that identity needs permission to create items under the +destinations users name. + ### Scenario result hierarchy These read-only APIs provide the backend foundation for compound-attack browsing. @@ -1141,3 +1173,6 @@ Environment variables: - `PYRIT_API_HOST` - Host to bind to (default: localhost) - `PYRIT_API_PORT` - Port to listen on (default: 8000) - `PYRIT_API_RELOAD` - Enable auto-reload (default: false) +- `PYRIT_PUBLIC_ORIGIN` - The deployment's public origin, such as `https://pyrit.example.com`, which links written + into other systems open. Read when the runtime starts or reinitializes; a value that isn't an origin is logged, and + publishing findings returns 503 until a valid one is set diff --git a/pyrit/backend/main.py b/pyrit/backend/main.py index a532d6fdab..ea672b3ab9 100644 --- a/pyrit/backend/main.py +++ b/pyrit/backend/main.py @@ -37,6 +37,7 @@ configuration, converters, datasets, + finding_publishers, health, initializers, labels, @@ -158,6 +159,7 @@ async def lifespan(app: FastAPI) -> AsyncGenerator[None, None]: app.include_router(techniques.router, prefix="/api", tags=["techniques"]) app.include_router(datasets.router, prefix="/api", tags=["datasets"]) app.include_router(operations.router, prefix="/api", tags=["operations"]) +app.include_router(finding_publishers.router, prefix="/api", tags=["finding-publishers"]) app.include_router(prompt_generations.router, prefix="/api", tags=["prompt-generations"]) app.include_router(scenarios.router, prefix="/api", tags=["scenarios"]) app.include_router(scenario_presets.router, prefix="/api", tags=["scenario-presets"]) diff --git a/pyrit/backend/models/finding_publishers.py b/pyrit/backend/models/finding_publishers.py new file mode 100644 index 0000000000..2b555ab42f --- /dev/null +++ b/pyrit/backend/models/finding_publishers.py @@ -0,0 +1,50 @@ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT license. + +"""Requests and listings for publishing an operation's findings to another system.""" + +from pydantic import BaseModel, ConfigDict, Field + +from pyrit.backend.models.operations import FindingSelectionRequest +from pyrit.models import FindingPublisherInfo + +# Long enough for any work item URL a user pastes. +MAX_PUBLISH_TEXT_LENGTH = 2_048 + + +class FindingPublisherListItem(BaseModel): + """A registered finding publisher, and how to ask for its destination.""" + + model_config = ConfigDict(extra="forbid") + + name: str + info: FindingPublisherInfo + + +class FindingPublisherListResponse(BaseModel): + """The registered finding publishers, sorted by name. An empty list means publishing isn't offered.""" + + model_config = ConfigDict(extra="forbid") + + items: list[FindingPublisherListItem] + + +class FindingPublishPreviewRequest(FindingSelectionRequest): + """The findings to check, the publisher to check them with, and the destination to put them under.""" + + publisher_name: str = Field( + min_length=1, max_length=MAX_PUBLISH_TEXT_LENGTH, description="A registered finding publisher's name" + ) + destination: str = Field( + min_length=1, + max_length=MAX_PUBLISH_TEXT_LENGTH, + description="The existing item that new items go under, as the user wrote it", + ) + + +class FindingPublishRequest(FindingPublishPreviewRequest): + """The findings to publish, with the plan digest of the Check that showed where they go.""" + + plan_digest: str = Field( + pattern=r"^[0-9a-f]{64}$", description="The plan digest from the preview of the same request" + ) diff --git a/pyrit/backend/models/operations.py b/pyrit/backend/models/operations.py index c5b1875320..08d4310cc5 100644 --- a/pyrit/backend/models/operations.py +++ b/pyrit/backend/models/operations.py @@ -282,8 +282,26 @@ class FindingExportFormat(StrEnum): MARKDOWN = "markdown" -class FindingExportRequest(BaseModel): - """The findings to download, the file format, and the dashboard origin their evidence links open.""" +def require_origin(url: AnyHttpUrl) -> AnyHttpUrl: + """ + Accept only a scheme, host, and optional port. + + Args: + url (AnyHttpUrl): The address to check. + + Returns: + AnyHttpUrl: The origin. + + Raises: + ValueError: If the address has credentials, a path, a query, or a fragment. + """ + if url.username or url.password or url.path not in (None, "/") or url.query is not None or url.fragment is not None: + raise ValueError("Must be an origin, without credentials, a path, a query, or a fragment.") + return url + + +class FindingSelectionRequest(BaseModel): + """Selected findings of an operation. Each includes all of its sub-findings.""" model_config = ConfigDict(extra="forbid") @@ -292,8 +310,6 @@ class FindingExportRequest(BaseModel): max_length=MAX_EXPORT_FINDINGS, description="Distinct findings of the operation to include, each with all of its sub-findings", ) - format: FindingExportFormat = FindingExportFormat.DOCX - dashboard_origin: AnyHttpUrl = Field(description="The dashboard's origin, which evidence links open") @field_validator("finding_ids") @classmethod @@ -311,6 +327,13 @@ def _reject_duplicates(cls, finding_ids: list[UUID]) -> list[UUID]: raise ValueError("Each finding can be selected only once.") return finding_ids + +class FindingExportRequest(FindingSelectionRequest): + """The findings to download, the file format, and the dashboard origin their evidence links open.""" + + format: FindingExportFormat = FindingExportFormat.DOCX + dashboard_origin: AnyHttpUrl = Field(description="The dashboard's origin, which evidence links open") + @field_validator("dashboard_origin") @classmethod def _require_origin(cls, url: AnyHttpUrl) -> AnyHttpUrl: @@ -319,16 +342,5 @@ def _require_origin(cls, url: AnyHttpUrl) -> AnyHttpUrl: Returns: AnyHttpUrl: The dashboard origin. - - Raises: - ValueError: If the address has credentials, a path, a query, or a fragment. """ - if ( - url.username - or url.password - or url.path not in (None, "/") - or url.query is not None - or url.fragment is not None - ): - raise ValueError("Must be an origin, without credentials, a path, a query, or a fragment.") - return url + return require_origin(url) diff --git a/pyrit/backend/routes/common.py b/pyrit/backend/routes/common.py index d1e6b0fef7..1a55dea0b0 100644 --- a/pyrit/backend/routes/common.py +++ b/pyrit/backend/routes/common.py @@ -8,6 +8,7 @@ from pyrit.backend.middleware.auth import AuthenticatedUser from pyrit.backend.models.common import NotSaveableProblemDetail, validate_label_filter +from pyrit.models import FindingPublishRequester from pyrit.models.catalog import SavedEntryOwner from pyrit.registry import NotSaveableError @@ -48,6 +49,23 @@ def saved_entry_owner_from_request(request: Request) -> SavedEntryOwner | None: return SavedEntryOwner(oid=user.oid, name=user.name or user.email) +def finding_publish_requester_from_request(request: Request) -> FindingPublishRequester | None: + """ + Return the signed-in user that a finding publish is for. + + Args: + request: The incoming FastAPI request. + + Returns: + FindingPublishRequester | None: The user's name and email, each None when Microsoft Graph gave none, or None + when sign-in is off. + """ + user = getattr(request.state, "user", None) + if not isinstance(user, AuthenticatedUser): + return None + return FindingPublishRequester(name=user.name or None, email=user.email or None) + + def not_saveable_response(*, error: NotSaveableError, request: Request) -> JSONResponse: """ Build the problem response for an entry that can't be saved as asked. diff --git a/pyrit/backend/routes/finding_publishers.py b/pyrit/backend/routes/finding_publishers.py new file mode 100644 index 0000000000..c9413cd756 --- /dev/null +++ b/pyrit/backend/routes/finding_publishers.py @@ -0,0 +1,20 @@ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT license. + +from fastapi import APIRouter + +from pyrit.backend.models.finding_publishers import FindingPublisherListResponse +from pyrit.backend.services.finding_publish import list_finding_publishers + +router = APIRouter(prefix="/finding-publishers", tags=["finding-publishers"]) + + +@router.get("", response_model=FindingPublisherListResponse) +async def list_finding_publishers_async() -> FindingPublisherListResponse: + """ + List the finding publishers this deployment registers, with how each asks for its destination. + + Returns: + FindingPublisherListResponse: The publishers, sorted by name. An empty list means publishing isn't offered. + """ + return list_finding_publishers() diff --git a/pyrit/backend/routes/operations.py b/pyrit/backend/routes/operations.py index 3b900799f3..8d48fe899f 100644 --- a/pyrit/backend/routes/operations.py +++ b/pyrit/backend/routes/operations.py @@ -1,12 +1,18 @@ # Copyright (c) Microsoft Corporation. # Licensed under the MIT license. +import logging from collections.abc import Awaitable -from typing import Annotated, TypeVar +from http import HTTPStatus +from typing import Annotated, Any, TypeVar from uuid import UUID -from fastapi import APIRouter, HTTPException, Query, Response, status +from fastapi import APIRouter, HTTPException, Query, Request, Response, status +from fastapi.responses import JSONResponse +from pydantic import AnyHttpUrl +from pyrit.backend.models import FieldError, ProblemDetail +from pyrit.backend.models.finding_publishers import FindingPublishPreviewRequest, FindingPublishRequest from pyrit.backend.models.operations import ( FindingCreateRequest, FindingEvidenceAttachResponse, @@ -24,7 +30,15 @@ OperationListResponse, OperationUpdateRequest, ) -from pyrit.backend.services.finding_export import FindingExportTooLargeError, export_findings_async +from pyrit.backend.routes.common import finding_publish_requester_from_request +from pyrit.backend.services.finding_export import export_findings_async +from pyrit.backend.services.finding_publish import ( + MAX_PUBLISH_FINDINGS, + FindingPublisherNotFoundError, + PublicOriginUnavailableError, + preview_finding_publish_async, + publish_findings_async, +) from pyrit.backend.services.operation_service import ( DuplicateOperationError, FindingConflictError, @@ -35,14 +49,88 @@ ) from pyrit.common import print_deprecation_message from pyrit.memory.memory_interface import OperationInUseError -from pyrit.models import Finding, FindingFields, FindingValuesError, Operation +from pyrit.models import ( + Finding, + FindingFields, + FindingPublishPreview, + FindingPublishResult, + FindingValuesError, + Operation, +) from pyrit.models.harm_category import HarmCategory +from pyrit.output import ( + FindingPublishDeadlineError, + FindingPublishDestinationError, + FindingPublisherConfigurationError, + FindingPublishError, + FindingPublisherUnavailableError, + FindingPublishPlanChangedError, + FindingPublishValidationError, + FindingSelectionNotFoundError, + FindingSelectionTooLargeError, +) from pyrit.setup.finding_fields import get_active_finding_fields T = TypeVar("T") +logger = logging.getLogger(__name__) + router = APIRouter(prefix="/operations", tags=["operations"]) +_MISCONFIGURED = "The finding publisher is misconfigured. Ask an administrator to check the server log." +_FAILED = "The finding publisher failed unexpectedly. Ask an administrator to check the server log." +# Each Check or Publish error with its status, problem type, and message; None shows the error's own message. The +# publisher's own 401 is a 502, never a 401, because the dashboard retries a 401 with a new token and would publish +# again. +_PUBLISH_PROBLEMS: tuple[tuple[type[Exception], int, str, str | None], ...] = ( + (FindingSelectionNotFoundError, status.HTTP_404_NOT_FOUND, "/errors/not-found", None), + (FindingPublisherNotFoundError, status.HTTP_404_NOT_FOUND, "/errors/not-found", None), + ( + FindingSelectionTooLargeError, + status.HTTP_422_UNPROCESSABLE_CONTENT, + "/errors/publish-too-many", + f"Publish at most {MAX_PUBLISH_FINDINGS:,} findings at a time, counting sub-findings.", + ), + ( + FindingPublishValidationError, + status.HTTP_422_UNPROCESSABLE_CONTENT, + "/errors/publish-problems", + "Fix these problems, then check again", + ), + (FindingPublishPlanChangedError, status.HTTP_409_CONFLICT, "/errors/publish-plan-changed", None), + (FindingPublishDestinationError, status.HTTP_400_BAD_REQUEST, "/errors/publish-destination", None), + (FindingPublisherUnavailableError, status.HTTP_502_BAD_GATEWAY, "/errors/publisher-unavailable", None), + (PublicOriginUnavailableError, status.HTTP_503_SERVICE_UNAVAILABLE, "/errors/public-origin", None), + ( + FindingPublishDeadlineError, + status.HTTP_503_SERVICE_UNAVAILABLE, + "/errors/publish-deadline", + "Ran out of time before creating anything. Try again.", + ), + # Its own type, unlike the catch-all 500, because a publisher checks the fields before it creates anything. + ( + FindingPublisherConfigurationError, + status.HTTP_500_INTERNAL_SERVER_ERROR, + "/errors/publisher-misconfigured", + _MISCONFIGURED, + ), +) +_PUBLISH_ERRORS: tuple[type[Exception], ...] = (*(entry[0] for entry in _PUBLISH_PROBLEMS), FindingPublishError) +_PUBLISH_ERROR_RESPONSES: dict[int | str, dict[str, Any]] = { + status.HTTP_400_BAD_REQUEST: {"model": ProblemDetail, "description": "The destination isn't one to publish to"}, + status.HTTP_404_NOT_FOUND: {"model": ProblemDetail, "description": "The operation, a finding, or the publisher"}, + status.HTTP_409_CONFLICT: {"model": ProblemDetail, "description": "The plan changed since Check"}, + status.HTTP_422_UNPROCESSABLE_CONTENT: { + "model": ProblemDetail, + "description": "Too many findings, or, for a Publish, problems to fix", + }, + status.HTTP_502_BAD_GATEWAY: {"model": ProblemDetail, "description": "The destination's service is unavailable"}, + status.HTTP_503_SERVICE_UNAVAILABLE: { + "model": ProblemDetail, + "description": "Out of time before creating anything, or no public origin is configured", + }, +} + @router.post("", response_model=Operation, status_code=status.HTTP_201_CREATED) async def create_operation_async(request: OperationCreateRequest) -> Operation: @@ -244,12 +332,18 @@ async def export_operation_findings_async(*, operation_id: UUID, request: Findin Response: The complete document as an attachment. Raises: - HTTPException: 422 when the selection has more findings, with their sub-findings, than one export allows. + HTTPException: 404 when the operation or a selected finding is missing, and 422 when the selection has more + findings, with their sub-findings, than one export allows. """ try: - exported = await _require_operation_async(export_findings_async(operation_id=operation_id, request=request)) - except FindingExportTooLargeError as exc: - raise HTTPException(status_code=status.HTTP_422_UNPROCESSABLE_CONTENT, detail=str(exc)) from exc + exported = await export_findings_async(operation_id=operation_id, request=request) + except FindingSelectionNotFoundError as exc: + raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=str(exc)) from exc + except FindingSelectionTooLargeError as exc: + raise HTTPException( + status_code=status.HTTP_422_UNPROCESSABLE_CONTENT, + detail=f"Select at most {exc.max_findings:,} findings to download at once, counting sub-findings.", + ) from exc return Response( content=exported.content, media_type=exported.media_type, @@ -257,6 +351,61 @@ async def export_operation_findings_async(*, operation_id: UUID, request: Findin ) +@router.post( + "/{operation_id}/findings/publish/preview", + response_model=FindingPublishPreview, + responses=_PUBLISH_ERROR_RESPONSES, +) +async def preview_operation_findings_publish_async( + *, operation_id: UUID, body: FindingPublishPreviewRequest, request: Request +) -> FindingPublishPreview | JSONResponse: + """ + Check where each selected finding would go in another system, without writing anything. + + Each selected finding includes all of its sub-findings. Problems that would stop a publish are returned with the + preview, not as an error. + + Returns: + FindingPublishPreview | JSONResponse: The destination, the planned and skipped findings, the problems and + the plan digest to publish with, or the problem response for an error. + """ + try: + return await preview_finding_publish_async( + operation_id=operation_id, request=body, public_origin=_public_origin(request) + ) + except _PUBLISH_ERRORS as exc: + return _publish_problem(error=exc, request=request) + + +@router.post( + "/{operation_id}/findings/publish", + response_model=FindingPublishResult, + responses=_PUBLISH_ERROR_RESPONSES, +) +async def publish_operation_findings_async( + *, operation_id: UUID, body: FindingPublishRequest, request: Request +) -> FindingPublishResult | JSONResponse: + """ + Create an item in another system for each finding that the Check with ``plan_digest`` planned. + + Once the first item is being created, every finding's outcome is in the result: created, skipped, failed (saying + whether the item might exist anyway) or not attempted. Publishing again creates new items. + + Returns: + FindingPublishResult | JSONResponse: Every finding's outcome, or the problem response for an error before + anything was created. + """ + try: + return await publish_findings_async( + operation_id=operation_id, + request=body, + requested_by=finding_publish_requester_from_request(request), + public_origin=_public_origin(request), + ) + except _PUBLISH_ERRORS as exc: + return _publish_problem(error=exc, request=request) + + @router.put("/{operation_id}/findings/{finding_id}", response_model=FindingResponse) async def update_operation_finding_async( *, operation_id: UUID, finding_id: UUID, request: FindingUpdateRequest @@ -397,3 +546,47 @@ def _name_conflict(exc: DuplicateOperationError) -> HTTPException: status_code=status.HTTP_409_CONFLICT, detail={"message": str(exc), "operation": exc.existing.model_dump(mode="json")}, ) + + +def _public_origin(request: Request) -> AnyHttpUrl | None: + # The runtime reads PYRIT_PUBLIC_ORIGIN when it applies its configuration; it is unset before then. + origin = getattr(request.app.state, "public_origin", None) + return origin if isinstance(origin, AnyHttpUrl) else None + + +def _publish_problem(*, error: Exception, request: Request) -> JSONResponse: + """ + Map a Check or Publish error to its problem response. + + Returns: + JSONResponse: The problem, with one ``errors`` entry per problem for a Publish with problems. + """ + mapped = next((entry for entry in _PUBLISH_PROBLEMS if isinstance(error, entry[0])), None) + if isinstance(error, (FindingPublishDestinationError, FindingPublisherUnavailableError)): + # Diagnostics hold only what helps an administrator, such as the service's status and error code. + diagnostics = ", ".join(f"{key} {value}" for key, value in error.diagnostics.items()) or "none" + logger.warning( + "Finding publish on %s stopped before creating anything: %s (diagnostics: %s).", + request.url.path, + type(error).__name__, + diagnostics, + ) + if mapped is None or mapped[1] == status.HTTP_500_INTERNAL_SERVER_ERROR: + # A configuration error, or any other publisher error: the details are for administrators. + logger.error("Finding publish failed on %s: %s", request.url.path, error, exc_info=error) + if mapped is None: + # Any other publisher error might follow a create, so it keeps the catch-all type, which isn't classified. + mapped = (Exception, status.HTTP_500_INTERNAL_SERVER_ERROR, "/errors/internal-error", _FAILED) + _, problem_status, problem_type, message = mapped + errors = None + if isinstance(error, FindingPublishValidationError): + errors = [FieldError(field=problem.title, message=problem.message) for problem in error.problems] + problem = ProblemDetail( + type=problem_type, + title=HTTPStatus(problem_status).phrase, + status=problem_status, + detail=message or str(error), + instance=str(request.url.path), + errors=errors, + ) + return JSONResponse(status_code=problem_status, content=problem.model_dump(exclude_none=True)) diff --git a/pyrit/backend/services/finding_export.py b/pyrit/backend/services/finding_export.py index 6b3ad754ef..c2809c1a98 100644 --- a/pyrit/backend/services/finding_export.py +++ b/pyrit/backend/services/finding_export.py @@ -22,20 +22,15 @@ from docx.text.paragraph import Paragraph from pydantic import AnyHttpUrl -from pyrit.backend.models import ScoreView from pyrit.backend.models.operations import ( MAX_EXPORT_FINDINGS, - EvidenceAvailability, - FindingEvidenceItem, FindingExportFormat, FindingExportRequest, ) -from pyrit.backend.services.operation_service import OperationService -from pyrit.models import ScoreStatus +from pyrit.output import FindingEvidenceLinkTarget, build_finding_report, build_finding_selection_async from pyrit.output.finding_report.markdown import MarkdownFindingReportPrinter from pyrit.output.finding_report.report import ( DETAIL_SEPARATOR, - EVIDENCE_NOTE, NO_EVIDENCE, UNAVAILABLE_EVIDENCE, FindingReport, @@ -43,7 +38,6 @@ FindingReportEntry, FindingReportEvidence, FindingReportField, - build_finding_report, plain_text, ) from pyrit.output.finding_report.word import add_word_paths @@ -52,8 +46,6 @@ _MARKDOWN_MEDIA_TYPE = "text/markdown; charset=utf-8" _DOCX_MEDIA_TYPE = "application/vnd.openxmlformats-officedocument.wordprocessingml.document" _LINK_COLOR = RGBColor(0x05, 0x63, 0xC1) -_HUMAN_SCORER = "ManualScorer" -_BOOLEAN_SCORES = {"true": "True", "false": "False"} # Word 2013 and later; the template's older mode opens documents in Compatibility Mode. _WORD_COMPATIBILITY_MODE = "15" _WORD_TABLE_STYLE = "Table Grid" @@ -74,10 +66,6 @@ class FindingExportFile: filename: str -class FindingExportTooLargeError(ValueError): - """Raised when the selected findings, with all of their sub-findings, are more than one export allows.""" - - async def export_findings_async(*, operation_id: UUID, request: FindingExportRequest) -> FindingExportFile: """ Build one document of an Operation's selected findings, in the dashboard's listing order, with evidence references. @@ -90,9 +78,8 @@ async def export_findings_async(*, operation_id: UUID, request: FindingExportReq FindingExportFile: The complete document. Raises: - OperationNotFoundError: If the Operation does not exist. - FindingNotFoundError: If a selected finding is not in the Operation. - FindingExportTooLargeError: If the findings to include, with sub-findings, exceed ``MAX_EXPORT_FINDINGS``. + FindingSelectionNotFoundError: If the Operation does not exist, or a selected finding is not in it. + FindingSelectionTooLargeError: If the findings to include, with sub-findings, exceed ``MAX_EXPORT_FINDINGS``. """ report = await _build_report_async(operation_id=operation_id, request=request) now = datetime.now(UTC) @@ -119,90 +106,35 @@ def _export_filename(*, operation_id: UUID, extension: str, now: datetime) -> st async def _build_report_async(*, operation_id: UUID, request: FindingExportRequest) -> FindingReport: - service = OperationService() - operation = await service.get_async(operation_id) - # One snapshot of the selected trees: every path step is among these findings, so they are not read again. - included = await service.get_finding_subtrees_async(operation_id=operation_id, finding_ids=request.finding_ids) - if len(included) > MAX_EXPORT_FINDINGS: - raise FindingExportTooLargeError( - f"Select at most {MAX_EXPORT_FINDINGS:,} findings to download at once, counting sub-findings." - ) - selected = await service.get_evidence_for_findings_async(findings=included) - finding_ids = {finding.id for finding in included} - evidence = { - finding.id: tuple( - _project_evidence(item=item, operation_id=operation_id, dashboard_origin=request.dashboard_origin) - for item in items - ) - for finding, items in selected - } - part_of = await service.get_finding_titles_async( - operation_id=operation_id, - finding_ids=list( - {finding.parent_finding_id for finding in included if finding.parent_finding_id} - finding_ids - ), + fields = get_active_finding_fields() + selection = await build_finding_selection_async( + operation_id=operation_id, finding_ids=request.finding_ids, fields=fields, max_findings=MAX_EXPORT_FINDINGS ) return build_finding_report( - operation_name=operation.name, - findings=included, - fields=get_active_finding_fields(), - evidence=evidence, - part_of=part_of, + selection=selection, + fields=fields, + link_for=partial(conversation_link, dashboard_origin=request.dashboard_origin), ) -def _project_evidence( - *, item: FindingEvidenceItem, operation_id: UUID, dashboard_origin: AnyHttpUrl -) -> FindingReportEvidence: - if item.outcome is None: - # The attack result is gone, so its saved ID stands in for its objective. - return FindingReportEvidence(title=str(item.item.attack_result_id), summary=(), details=(), link_url=None) - objective = item.objective if item.objective and item.objective.strip() else "No objective" - summary = ( - FindingReportField(label="Outcome", value=item.outcome.value.capitalize()), - FindingReportField(label="Score", value=_score_text(item.score)), - ) - details = [] - if item.score is not None and item.score.score_rationale: - details.append(FindingReportField(label="Rationale", value=item.score.score_rationale)) - # As on the dashboard, an attack's Operation is named only when it isn't the document's own. - if item.source_operation_id != operation_id: - details.append( - FindingReportField(label="From operation", value=item.source_operation_name or "Not in an operation") - ) - link_url = None - if item.availability == EvidenceAvailability.AVAILABLE and item.conversation_id is not None: - link_url = _conversation_link( - dashboard_origin=dashboard_origin, item=item, conversation_id=item.conversation_id - ) - return FindingReportEvidence(title=objective, summary=summary, details=tuple(details), link_url=link_url) - - -def _score_text(score: ScoreView | None) -> str: - if score is None: - return "Not scored" - if score.status == ScoreStatus.UNDETERMINED: - value = "Undetermined" - else: - value = _BOOLEAN_SCORES.get(str(score.score_value).lower(), str(score.score_value)) - scorer = "human review" if score.scorer_type == _HUMAN_SCORER else score.scorer_type - return f"{value} ({scorer})" - - -def _conversation_link(*, dashboard_origin: AnyHttpUrl, item: FindingEvidenceItem, conversation_id: str) -> str: +def conversation_link(target: FindingEvidenceLinkTarget, *, dashboard_origin: AnyHttpUrl) -> str: """ Build the dashboard route that opens evidence's conversation and returns to the evidence. + Args: + target (FindingEvidenceLinkTarget): The evidence and the conversation it opens. + dashboard_origin (AnyHttpUrl): The dashboard's origin, such as ``https://pyrit.example.com``. + Returns: str: The absolute link, matching the dashboard's ``attackConversationRoutePath``; both are tested against ``frontend/src/utils/attackConversationRoute.cases.json``. """ path = ( - f"/attack/chat/{_encode_segment(str(item.item.attack_result_id))}" - f"/conversations/{_encode_segment(conversation_id)}" + f"/attack/chat/{_encode_segment(str(target.attack_result_id))}" + f"/conversations/{_encode_segment(target.conversation_id)}" ) - query = {"scenarioResultId": str(item.scenario_result_id)} if item.scenario_result_id else {} - query["findingEvidenceId"] = str(item.item.id) + query = {"scenarioResultId": str(target.scenario_result_id)} if target.scenario_result_id else {} + query["findingEvidenceId"] = str(target.evidence_id) return f"{str(dashboard_origin).rstrip('/')}{path}?{urlencode(query)}" @@ -216,7 +148,7 @@ def _render_docx(*, report: FindingReport, now: datetime) -> bytes: title = plain_text(f"Findings - {report.operation_name}") _replace_template_metadata(document=document, title=title, now=now) document.add_heading(title, level=1) - document.add_paragraph(EVIDENCE_NOTE) + document.add_paragraph(report.evidence_note) table = document.add_table(rows=1, cols=len(_WORD_COLUMNS)) table.style = document.styles[_WORD_TABLE_STYLE] header = table.rows[0] diff --git a/pyrit/backend/services/finding_publish.py b/pyrit/backend/services/finding_publish.py new file mode 100644 index 0000000000..26904f8d02 --- /dev/null +++ b/pyrit/backend/services/finding_publish.py @@ -0,0 +1,179 @@ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT license. + +"""Check and publish an operation's selected findings with a registered finding publisher.""" + +import logging +import os +from functools import partial +from time import monotonic +from uuid import UUID + +from pydantic import AnyHttpUrl, TypeAdapter + +from pyrit.backend.models.finding_publishers import ( + FindingPublisherListItem, + FindingPublisherListResponse, + FindingPublishPreviewRequest, + FindingPublishRequest, +) +from pyrit.backend.models.operations import require_origin +from pyrit.backend.services.finding_export import conversation_link +from pyrit.models import FindingFields, FindingPublishPreview, FindingPublishRequester, FindingPublishResult +from pyrit.output import FindingPublisher, FindingSelection, build_finding_selection_async +from pyrit.registry import FindingPublisherRegistry +from pyrit.setup.finding_fields import get_active_finding_fields + +logger = logging.getLogger(__name__) + +# The most findings one Check or Publish takes, counting sub-findings, so a publish fits in its time budget. +MAX_PUBLISH_FINDINGS = 100 +# Each request's time budget from admission, within the 240 seconds that Front Door and ACA allow a request. +PUBLISH_BUDGET_SECONDS = 210 +# The deployment's public origin, which evidence links written into other systems open. +PUBLIC_ORIGIN_VARIABLE = "PYRIT_PUBLIC_ORIGIN" + +_ORIGIN_ADAPTER = TypeAdapter(AnyHttpUrl) + + +class FindingPublisherNotFoundError(LookupError): + """Raised when no finding publisher is registered under the requested name.""" + + +class PublicOriginUnavailableError(RuntimeError): + """Raised when ``PYRIT_PUBLIC_ORIGIN`` is unset or not an origin, so evidence links can't be built.""" + + def __init__(self) -> None: + """Initialize the error with what an administrator must do.""" + super().__init__( + f"Publishing needs the deployment's public address. Ask an administrator to set {PUBLIC_ORIGIN_VARIABLE}." + ) + + +def read_public_origin() -> AnyHttpUrl | None: + """ + Read the deployment's public origin from ``PYRIT_PUBLIC_ORIGIN``, once the runtime has loaded its settings. + + The origin comes from the deployment's settings, never from a request, because other people open the links + built from it. A value that isn't an origin is logged and ignored, so only publishing fails. + + Returns: + AnyHttpUrl | None: The origin, or None when it is unset or invalid. + """ + value = os.getenv(PUBLIC_ORIGIN_VARIABLE, "").strip() + if not value: + return None + try: + return require_origin(_ORIGIN_ADAPTER.validate_python(value)) + except ValueError: # Includes pydantic's ValidationError. + logger.warning( + "%s is not an origin, such as https://pyrit.example.com, so publishing findings is unavailable.", + PUBLIC_ORIGIN_VARIABLE, + ) + return None + + +def list_finding_publishers() -> FindingPublisherListResponse: + """ + List the registered finding publishers by name, with how each asks for its destination. + + Returns: + FindingPublisherListResponse: The publishers, sorted by name; empty when publishing isn't offered. + """ + entries = FindingPublisherRegistry.get_registry_singleton().instances.get_all_instances() + return FindingPublisherListResponse( + items=[FindingPublisherListItem(name=entry.name, info=entry.instance.info) for entry in entries] + ) + + +async def preview_finding_publish_async( + *, operation_id: UUID, request: FindingPublishPreviewRequest, public_origin: AnyHttpUrl | None +) -> FindingPublishPreview: + """ + Show where each selected finding would go, without writing anything. + + Args: + operation_id (UUID): The operation the findings belong to. + request (FindingPublishPreviewRequest): The findings, the publisher and the destination. + public_origin (AnyHttpUrl | None): The deployment's public origin, or None when it isn't configured. + + Returns: + FindingPublishPreview: The destination, the planned and skipped findings, the problems and the plan digest. + + Raises: + FindingPublisherNotFoundError: If no publisher has the requested name. + PublicOriginUnavailableError: If the deployment has no public origin. + FindingSelectionNotFoundError: If the operation or a selected finding is missing. + FindingSelectionTooLargeError: If the selection has more than ``MAX_PUBLISH_FINDINGS`` findings. + """ + deadline = monotonic() + PUBLISH_BUDGET_SECONDS + publisher = _require_publisher(request.publisher_name) + # A preview links nothing, but checking now saves the user from a Publish that can't run. + _require_public_origin(public_origin) + fields = get_active_finding_fields() + selection = await _gather_async(operation_id=operation_id, request=request, fields=fields) + return await publisher.preview_async( + selection=selection, fields=fields, destination=request.destination, deadline=deadline + ) + + +async def publish_findings_async( + *, + operation_id: UUID, + request: FindingPublishRequest, + requested_by: FindingPublishRequester | None, + public_origin: AnyHttpUrl | None, +) -> FindingPublishResult: + """ + Create an item for each finding that the Check with ``request.plan_digest`` planned, and report every outcome. + + Args: + operation_id (UUID): The operation the findings belong to. + request (FindingPublishRequest): The findings, the publisher, the destination and the Check's plan digest. + requested_by (FindingPublishRequester | None): The signed-in user, or None when sign-in is off. + public_origin (AnyHttpUrl | None): The deployment's public origin, or None when it isn't configured. + + Returns: + FindingPublishResult: The run ID and every finding's outcome. + + Raises: + FindingPublisherNotFoundError: If no publisher has the requested name. + PublicOriginUnavailableError: If the deployment has no public origin. + FindingSelectionNotFoundError: If the operation or a selected finding is missing. + FindingSelectionTooLargeError: If the selection has more than ``MAX_PUBLISH_FINDINGS`` findings. + """ + deadline = monotonic() + PUBLISH_BUDGET_SECONDS + publisher = _require_publisher(request.publisher_name) + link_for = partial(conversation_link, dashboard_origin=_require_public_origin(public_origin)) + fields = get_active_finding_fields() + selection = await _gather_async(operation_id=operation_id, request=request, fields=fields) + return await publisher.publish_async( + selection=selection, + fields=fields, + destination=request.destination, + link_for=link_for, + requested_by=requested_by, + expected_plan_digest=request.plan_digest, + deadline=deadline, + ) + + +def _require_publisher(name: str) -> FindingPublisher: + publisher = FindingPublisherRegistry.get_registry_singleton().instances.get(name) + if publisher is None: + raise FindingPublisherNotFoundError(f"Finding publisher '{name}' not found.") + return publisher + + +def _require_public_origin(public_origin: AnyHttpUrl | None) -> AnyHttpUrl: + if public_origin is None: + raise PublicOriginUnavailableError + return public_origin + + +async def _gather_async( + *, operation_id: UUID, request: FindingPublishPreviewRequest, fields: FindingFields +) -> FindingSelection: + return await build_finding_selection_async( + operation_id=operation_id, finding_ids=request.finding_ids, fields=fields, max_findings=MAX_PUBLISH_FINDINGS + ) diff --git a/pyrit/backend/services/operation_service.py b/pyrit/backend/services/operation_service.py index 54fcf0c598..e002dadaed 100644 --- a/pyrit/backend/services/operation_service.py +++ b/pyrit/backend/services/operation_service.py @@ -26,21 +26,17 @@ from pyrit.memory import CentralMemory from pyrit.memory.memory_interface import FindingHierarchyError from pyrit.models import ( - AttackResult, - AttackResultSelection, Finding, FindingCreate, FindingEvidence, FindingFields, Operation, OperationCreate, + ResolvedFindingEvidence, is_finding_path_complete, ) from pyrit.setup.finding_fields import get_active_finding_fields -# Keeps every ID list a batch reads within SQL Server's 2100-parameter limit. -_EVIDENCE_BATCH_SIZE = 500 - class OperationNotFoundError(LookupError): """Raised when a request names an operation that does not exist.""" @@ -355,183 +351,15 @@ async def list_finding_evidence_async( finding_id=finding_id, limit=limit + 1, offset=offset ) has_more = len(evidence) > limit + resolved = await CentralMemory.get_memory_instance().get_resolved_finding_evidence_async( + evidence=evidence[:limit] + ) return FindingEvidenceListResponse( - items=await self._resolve_evidence_async(evidence=evidence[:limit]), + items=[_evidence_item(item) for item in resolved], has_more=has_more, next_offset=offset + limit if has_more else None, ) - async def get_finding_subtrees_async(self, *, operation_id: UUID, finding_ids: Sequence[UUID]) -> list[Finding]: - """ - Read selected findings of an operation with all of their sub-findings, at any depth. - - Returns: - list[Finding]: Each finding once, ordered as ``list_findings_async`` orders findings. - - Raises: - OperationNotFoundError: If no operation has this ID. - FindingNotFoundError: If a selected finding is not in the operation. - """ - await self.get_async(operation_id) - findings = await CentralMemory.get_memory_instance().get_finding_subtrees_async( - operation_id=operation_id, - finding_ids=finding_ids, - severity_order=get_active_finding_fields().severity_order, - ) - found = {finding.id for finding in findings} - missing = next((finding_id for finding_id in finding_ids if finding_id not in found), None) - if missing is not None: - raise FindingNotFoundError(f"Finding '{missing}' not found in operation '{operation_id}'.") - return findings - - async def get_finding_titles_async(self, *, operation_id: UUID, finding_ids: Sequence[UUID]) -> dict[UUID, str]: - """ - Read the titles of an operation's findings. IDs that are not in the operation are omitted. - - Returns: - dict[UUID, str]: Each found finding's title. - """ - findings = await CentralMemory.get_memory_instance().get_findings_by_ids_async( - operation_id=operation_id, finding_ids=finding_ids - ) - return {finding.id: finding.title for finding in findings} - - async def get_findings_with_evidence_async( - self, *, operation_id: UUID, finding_ids: Sequence[UUID] - ) -> list[tuple[Finding, list[FindingEvidenceItem]]]: - """ - Read selected findings of an operation, each with all its evidence as the evidence page shows it. - - Returns: - list[tuple[Finding, list[FindingEvidenceItem]]]: Each finding with its evidence, newest evidence first, - ordered as ``list_findings_async`` orders findings. - - Raises: - OperationNotFoundError: If no operation has this ID. - FindingNotFoundError: If a requested finding is not in the operation. - """ - await self.get_async(operation_id) - memory = CentralMemory.get_memory_instance() - findings = await memory.get_findings_by_ids_async( - operation_id=operation_id, - finding_ids=finding_ids, - severity_order=get_active_finding_fields().severity_order, - ) - found = {finding.id for finding in findings} - missing = next((finding_id for finding_id in finding_ids if finding_id not in found), None) - if missing is not None: - raise FindingNotFoundError(f"Finding '{missing}' not found in operation '{operation_id}'.") - return await self.get_evidence_for_findings_async(findings=findings) - - async def get_evidence_for_findings_async( - self, *, findings: Sequence[Finding] - ) -> list[tuple[Finding, list[FindingEvidenceItem]]]: - """ - Pair findings that were already read with all their evidence, as the evidence page shows it. - - The findings are kept as given, not read again, so a tree read in one snapshot stays consistent. - - Returns: - list[tuple[Finding, list[FindingEvidenceItem]]]: Each finding in input order with its evidence, newest - evidence first. - """ - evidence = await CentralMemory.get_memory_instance().get_finding_evidence_for_findings_async( - finding_ids=[finding.id for finding in findings] - ) - resolved = await self._resolve_evidence_async( - evidence=[item for finding in findings for item in evidence.get(finding.id, [])] - ) - by_id = {item.item.id: item for item in resolved} - return [(finding, [by_id[item.id] for item in evidence.get(finding.id, [])]) for finding in findings] - - async def _resolve_evidence_async(self, *, evidence: Sequence[FindingEvidence]) -> list[FindingEvidenceItem]: - """ - Show each evidence link with its attack's current outcome, score, and conversation. - - Returns: - list[FindingEvidenceItem]: The evidence in input order. - """ - items: list[FindingEvidenceItem] = [] - for start in range(0, len(evidence), _EVIDENCE_BATCH_SIZE): - batch = evidence[start : start + _EVIDENCE_BATCH_SIZE] - items.extend(await self._resolve_evidence_batch_async(evidence=batch)) - return items - - async def _resolve_evidence_batch_async(self, *, evidence: Sequence[FindingEvidence]) -> list[FindingEvidenceItem]: - memory = CentralMemory.get_memory_instance() - attacks = await memory.get_attack_results_async( - attack_result_ids=list({str(item.attack_result_id) for item in evidence}), - result_selection=AttackResultSelection.ALL_RESULTS, - ) - owners = {attack.attack_result_id: attack for attack in attacks} - linked_ids = {attack.operation_id for attack in attacks if attack.operation_id is not None} - operation_names = ( - {saved.id: saved.name for saved in await memory.get_operations_async(operation_ids=list(linked_ids))} - if linked_ids - else {} - ) - conversations = await self._score_conversations_async(attacks=attacks) - stats = await memory.get_conversation_stats_async(conversation_ids=list(set(conversations.values()))) - items = [] - for item in evidence: - owner = owners.get(str(item.attack_result_id)) - if owner is None: - items.append( - FindingEvidenceItem( - item=item, availability=EvidenceAvailability.UNAVAILABLE, scenario_result_id=None - ) - ) - continue - conversation_id = conversations[owner.attack_result_id] - available = conversation_id in stats and stats[conversation_id].message_count > 0 - items.append( - FindingEvidenceItem( - item=item, - availability=EvidenceAvailability.AVAILABLE if available else EvidenceAvailability.UNAVAILABLE, - scenario_result_id=UUID(owner.attribution_parent_id) if owner.attribution_parent_id else None, - source_operation_id=owner.operation_id, - source_operation_name=( - operation_names.get(owner.operation_id) if owner.operation_id else owner.operation - ), - objective=owner.objective, - outcome=owner.outcome, - score=ScoreView.from_domain(owner.last_score, is_objective_score=True) - if owner.last_score - else None, - conversation_id=conversation_id, - ) - ) - return items - - @staticmethod - async def _score_conversations_async(*, attacks: Sequence[AttackResult]) -> dict[str, str]: - """ - Find the conversation holding each attack's score, so the score shown and the transcript opened agree. - - Returns: - dict[str, str]: By attack result ID, the active conversation holding its score, otherwise its main one. - """ - piece_ids = [ - str(attack.last_score.message_piece_id) - for attack in attacks - if attack.last_score is not None and attack.last_score.message_piece_id is not None - ] - pieces = ( - await CentralMemory.get_memory_instance().get_message_pieces_async(prompt_ids=piece_ids) - if piece_ids - else [] - ) - scored_in: dict[str, str] = {str(piece.id): str(piece.conversation_id) for piece in pieces} - conversations: dict[str, str] = {} - for attack in attacks: - score = attack.last_score - scored = scored_in.get(str(score.message_piece_id)) if score is not None else None - active = attack.get_active_conversation_ids() - conversations[attack.attack_result_id] = ( - scored if scored is not None and scored in active else attack.conversation_id - ) - return conversations - async def detach_finding_evidence_async(self, *, operation_id: UUID, finding_id: UUID, evidence_id: UUID) -> None: """Unlink evidence, but only if it belongs to the requested finding.""" await self.get_async(operation_id) @@ -671,3 +499,23 @@ async def delete_finding_async(self, *, operation_id: UUID, finding_id: UUID) -> raise FindingNotFoundError(str(exc)) from exc except FindingHierarchyError as exc: raise FindingConflictError(str(exc)) from exc + + +def _evidence_item(resolved: ResolvedFindingEvidence) -> FindingEvidenceItem: + """ + Show resolved evidence as the evidence page lists it, with its score as the attack's objective score. + + Returns: + FindingEvidenceItem: The evidence with its availability and attack context. + """ + return FindingEvidenceItem( + item=resolved.evidence, + availability=EvidenceAvailability.AVAILABLE if resolved.available else EvidenceAvailability.UNAVAILABLE, + scenario_result_id=resolved.scenario_result_id, + source_operation_id=resolved.source_operation_id, + source_operation_name=resolved.source_operation_name, + objective=resolved.objective, + outcome=resolved.outcome, + score=ScoreView.from_domain(resolved.score, is_objective_score=True) if resolved.score else None, + conversation_id=resolved.conversation_id, + ) diff --git a/pyrit/backend/services/runtime_lifecycle.py b/pyrit/backend/services/runtime_lifecycle.py index 1c5a73a7ae..439f7dfb1d 100644 --- a/pyrit/backend/services/runtime_lifecycle.py +++ b/pyrit/backend/services/runtime_lifecycle.py @@ -17,6 +17,7 @@ from pyrit.backend.services.analytics_service import get_analytics_service from pyrit.backend.services.configuration_file_service import ConfigurationFileService from pyrit.backend.services.environment_file_service import EnvironmentFileService +from pyrit.backend.services.finding_publish import read_public_origin from pyrit.backend.services.prompt_generation_service import peek_prompt_generation_service from pyrit.backend.services.saved_entry_restore import build_saved_entry_async from pyrit.backend.services.scenario_run_service import get_scenario_run_service, peek_scenario_run_service @@ -131,6 +132,8 @@ def _publish(self, config: ConfigurationLoader) -> None: # A proposal shown to users, never created or resolved to a saved Operation. self.app.state.default_operation = (config.operation or "").strip() or None self.app.state.max_concurrent_scenario_runs = config.max_concurrent_scenario_runs + # Read after initialization loads the environment files, so a value in ~/.pyrit/.env counts too. + self.app.state.public_origin = read_public_origin() self.generation = str(uuid.uuid4()) self.state, self.outcome, self.message = "ready", "success", "PyRIT is ready." diff --git a/pyrit/memory/memory_interface.py b/pyrit/memory/memory_interface.py index c441d9b221..c5b3bed5c3 100644 --- a/pyrit/memory/memory_interface.py +++ b/pyrit/memory/memory_interface.py @@ -174,6 +174,7 @@ PromptGenerationRecord, PromptGenerationStatus, RequestTraceContext, + ResolvedFindingEvidence, RetryEvent, ScenarioAttackResultDelta, ScenarioIdentifier, @@ -783,6 +784,9 @@ class MemoryInterface(abc.ABC): # for backends with higher limits (e.g., Azure SQL supports 2100). _MAX_BIND_VARS: int = 500 + # Evidence resolved per batch: each batch's ID lists stay within SQL Server's 2100-parameter limit. + _RESOLVED_EVIDENCE_BATCH_SIZE: int = 500 + # Label keys are interpolated into backend-specific JSON path expressions # (e.g. ``$.key``) in the per-backend label-filter helpers. We restrict keys # to a conservative allowlist so a crafted key cannot break out of the JSON @@ -1796,6 +1800,90 @@ async def get_finding_evidence_for_findings_async( evidence.setdefault(entry.finding_id, []).append(entry.get_evidence()) return evidence + async def get_resolved_finding_evidence_async( + self, *, evidence: Sequence[FindingEvidence] + ) -> list[ResolvedFindingEvidence]: + """ + Read each evidence link's attack, with its current outcome, score, and the conversation holding that score. + + Links whose attack result is gone are kept and marked unavailable. + + Args: + evidence (Sequence[FindingEvidence]): The evidence to resolve. + + Returns: + list[ResolvedFindingEvidence]: The evidence in input order. + """ + resolved: list[ResolvedFindingEvidence] = [] + for start in range(0, len(evidence), self._RESOLVED_EVIDENCE_BATCH_SIZE): + batch = evidence[start : start + self._RESOLVED_EVIDENCE_BATCH_SIZE] + resolved.extend(await self._resolve_finding_evidence_batch_async(evidence=batch)) + return resolved + + async def _resolve_finding_evidence_batch_async( + self, *, evidence: Sequence[FindingEvidence] + ) -> list[ResolvedFindingEvidence]: + attacks = await self.get_attack_results_async( + attack_result_ids=list({str(item.attack_result_id) for item in evidence}), + result_selection=AttackResultSelection.ALL_RESULTS, + ) + owners = {attack.attack_result_id: attack for attack in attacks} + linked_ids = {attack.operation_id for attack in attacks if attack.operation_id is not None} + operation_names = ( + {saved.id: saved.name for saved in await self.get_operations_async(operation_ids=list(linked_ids))} + if linked_ids + else {} + ) + conversations = await self._get_score_conversations_async(attacks=attacks) + stats = await self.get_conversation_stats_async(conversation_ids=list(set(conversations.values()))) + resolved = [] + for item in evidence: + owner = owners.get(str(item.attack_result_id)) + if owner is None: + resolved.append(ResolvedFindingEvidence(evidence=item, available=False)) + continue + conversation_id = conversations[owner.attack_result_id] + resolved.append( + ResolvedFindingEvidence( + evidence=item, + available=conversation_id in stats and stats[conversation_id].message_count > 0, + scenario_result_id=uuid.UUID(owner.attribution_parent_id) if owner.attribution_parent_id else None, + source_operation_id=owner.operation_id, + source_operation_name=( + operation_names.get(owner.operation_id) if owner.operation_id else owner.operation + ), + objective=owner.objective, + outcome=owner.outcome, + score=owner.last_score, + conversation_id=conversation_id, + ) + ) + return resolved + + async def _get_score_conversations_async(self, *, attacks: Sequence[AttackResult]) -> dict[str, str]: + """ + Find the conversation holding each attack's score, so the score shown and the transcript opened agree. + + Returns: + dict[str, str]: By attack result ID, the active conversation holding its score, otherwise its main one. + """ + piece_ids = [ + str(attack.last_score.message_piece_id) + for attack in attacks + if attack.last_score is not None and attack.last_score.message_piece_id is not None + ] + pieces = await self.get_message_pieces_async(prompt_ids=piece_ids) if piece_ids else [] + scored_in: dict[str, str] = {str(piece.id): str(piece.conversation_id) for piece in pieces} + conversations: dict[str, str] = {} + for attack in attacks: + score = attack.last_score + scored = scored_in.get(str(score.message_piece_id)) if score is not None else None + active = attack.get_active_conversation_ids() + conversations[attack.attack_result_id] = ( + scored if scored is not None and scored in active else attack.conversation_id + ) + return conversations + async def get_finding_evidence_by_source_async( self, *, finding_id: uuid.UUID, attack_result_id: uuid.UUID ) -> FindingEvidence | None: diff --git a/pyrit/models/__init__.py b/pyrit/models/__init__.py index e81d7711a8..66cafe23b5 100644 --- a/pyrit/models/__init__.py +++ b/pyrit/models/__init__.py @@ -90,6 +90,19 @@ FindingSeverityColor, FindingValuesError, ) + from pyrit.models.finding_publication import ( + FindingPublishDestination, + FindingPublishedItem, + FindingPublisherInfo, + FindingPublishFailure, + FindingPublishPreview, + FindingPublishPreviewItem, + FindingPublishProblem, + FindingPublishReference, + FindingPublishRequester, + FindingPublishResult, + FindingPublishSkip, + ) from pyrit.models.harm_definition import HarmDefinition, ScaleDescription, get_all_harm_definitions from pyrit.models.identifiers import ( REGISTRY_NAME_PATTERN, @@ -170,6 +183,7 @@ ) from pyrit.models.prompt_generation_estimate import PromptGenerationEstimate, PromptGenerationStageEstimate from pyrit.models.question_answering import QuestionAnsweringDataset, QuestionAnsweringEntry, QuestionChoice + from pyrit.models.resolved_finding_evidence import ResolvedFindingEvidence from pyrit.models.results.assert_policy_metrics import AssertBinaryRate, AssertPolicyMetrics from pyrit.models.results.attack_result import AttackOutcome, AttackResult, AttackResultRole, AttackResultT from pyrit.models.results.attack_result_metadata import AttackResultMetadata @@ -580,12 +594,24 @@ "FindingCreate": "pyrit.models.finding", "FindingEvidence": "pyrit.models.finding", "is_finding_path_complete": "pyrit.models.finding", + "ResolvedFindingEvidence": "pyrit.models.resolved_finding_evidence", "DEFAULT_FINDING_FIELDS": "pyrit.models.finding_fields", "FindingField": "pyrit.models.finding_fields", "FindingFields": "pyrit.models.finding_fields", "FindingFieldType": "pyrit.models.finding_fields", "FindingSeverityColor": "pyrit.models.finding_fields", "FindingValuesError": "pyrit.models.finding_fields", + "FindingPublishDestination": "pyrit.models.finding_publication", + "FindingPublishedItem": "pyrit.models.finding_publication", + "FindingPublisherInfo": "pyrit.models.finding_publication", + "FindingPublishFailure": "pyrit.models.finding_publication", + "FindingPublishPreview": "pyrit.models.finding_publication", + "FindingPublishPreviewItem": "pyrit.models.finding_publication", + "FindingPublishProblem": "pyrit.models.finding_publication", + "FindingPublishReference": "pyrit.models.finding_publication", + "FindingPublishRequester": "pyrit.models.finding_publication", + "FindingPublishResult": "pyrit.models.finding_publication", + "FindingPublishSkip": "pyrit.models.finding_publication", "ConversationType": "pyrit.models.messages.conversation_reference", "ContentEntryScorable": "pyrit.models.score", "ContentScorable": "pyrit.models.score", diff --git a/pyrit/models/finding_publication.py b/pyrit/models/finding_publication.py new file mode 100644 index 0000000000..4e6a6b78af --- /dev/null +++ b/pyrit/models/finding_publication.py @@ -0,0 +1,118 @@ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT license. + +"""What a finding publisher shows before it publishes, and what it reports after.""" + +from uuid import UUID + +from pydantic import BaseModel, ConfigDict + + +class _FindingPublicationModel(BaseModel): + model_config = ConfigDict(extra="forbid", frozen=True) + + +class FindingPublisherInfo(_FindingPublicationModel): + """How a surface asks for a publisher's destination: the input's label and the hint under it.""" + + destination_label: str + destination_hint: str + + +class FindingPublishDestination(_FindingPublicationModel): + """ + The existing item that new items go under. + + ``location`` names where new items are created, such as an organization and project. + """ + + id: str + title: str + url: str + location: str + + +class FindingPublishRequester(_FindingPublicationModel): + """The person a publish is for. Either part may be unknown.""" + + name: str | None = None + email: str | None = None + + +class FindingPublishReference(_FindingPublicationModel): + """A finding, by its ID and title.""" + + finding_id: UUID + title: str + + +class FindingPublishPreviewItem(FindingPublishReference): + """ + A finding that a publish would create an item for. + + ``parent_finding_id`` is the planned finding whose new item this one goes under; None means the destination. + ``part_of`` is the parent's title when the finding has a parent but doesn't go under its new item. + """ + + parent_finding_id: UUID | None = None + part_of: str | None = None + + +class FindingPublishedItem(FindingPublishReference): + """An item a publish created, and the existing or new item it went under.""" + + external_id: str + url: str + parent_external_id: str + + +class FindingPublishSkip(FindingPublishReference): + """A selected finding that a publish leaves out, and why.""" + + reason: str + + +class FindingPublishProblem(FindingPublishReference): + """A planned finding that can't be published until it is fixed.""" + + message: str + + +class FindingPublishFailure(FindingPublishReference): + """The finding whose item failed, which stopped the run. ``outcome_unknown`` means the item might exist anyway.""" + + message: str + outcome_unknown: bool + + +class FindingPublishPreview(_FindingPublicationModel): + """ + Where every selected finding would go, without writing anything. + + ``planned`` lists parents before their children. Publishing sends ``plan_digest`` back, so a publish creates + only what this preview showed. + """ + + destination: FindingPublishDestination + planned: tuple[FindingPublishPreviewItem, ...] + skipped: tuple[FindingPublishSkip, ...] + problems: tuple[FindingPublishProblem, ...] + plan_digest: str + + +class FindingPublishResult(_FindingPublicationModel): + """ + Every outcome of one publish run. + + Read in order, ``created``, ``failure`` and ``not_attempted`` list each planned finding exactly once, in plan + order. At most one of ``failure`` and ``stopped_reason`` is set; every planned finding after that point is in + ``not_attempted``. ``run_id`` is recorded in each created item. + """ + + run_id: str + destination: FindingPublishDestination + created: tuple[FindingPublishedItem, ...] + skipped: tuple[FindingPublishSkip, ...] + failure: FindingPublishFailure | None = None + stopped_reason: str | None = None + not_attempted: tuple[FindingPublishReference, ...] = () diff --git a/pyrit/models/resolved_finding_evidence.py b/pyrit/models/resolved_finding_evidence.py new file mode 100644 index 0000000000..dacc6cec24 --- /dev/null +++ b/pyrit/models/resolved_finding_evidence.py @@ -0,0 +1,31 @@ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT license. + +from uuid import UUID + +from pydantic import BaseModel, ConfigDict + +from pyrit.models.finding import FindingEvidence +from pyrit.models.results.attack_result import AttackOutcome +from pyrit.models.score import Score + + +class ResolvedFindingEvidence(BaseModel): + """ + A finding's evidence with its attack's current outcome, score, and the conversation to open. + + ``available`` is whether the attack result exists and its conversation has messages. The other fields are + ``None`` when the attack result is gone. + """ + + model_config = ConfigDict(extra="forbid", frozen=True) + + evidence: FindingEvidence + available: bool + scenario_result_id: UUID | None = None + source_operation_id: UUID | None = None + source_operation_name: str | None = None + objective: str | None = None + outcome: AttackOutcome | None = None + score: Score | None = None + conversation_id: str | None = None diff --git a/pyrit/output/__init__.py b/pyrit/output/__init__.py index dc7847952b..245533e2ad 100644 --- a/pyrit/output/__init__.py +++ b/pyrit/output/__init__.py @@ -10,6 +10,10 @@ - **PrinterBase** that all printers inherit from - Domain printers for attack results, scenario results, and scorer information - **Convenience functions** (e.g., ``output_attack_async``) +- **Finding reports**: ``build_finding_selection_async`` gathers an Operation's findings, and ``build_finding_report`` + lays them out for a printer +- **Finding publishers** (``FindingPublisher``, ``AzureDevOpsFindingPublisher``), which create items for findings in + other systems File names indicate output format (pretty.py = ANSI-colored, markdown.py = Markdown). Abstract methods inside each printer determine the data source (memory, REST, fixtures). @@ -21,6 +25,29 @@ if TYPE_CHECKING: from pyrit.output.base import PrinterBase + from pyrit.output.finding_publisher.azure_devops import ( + AzureDevOpsField, + AzureDevOpsFieldKind, + AzureDevOpsFindingPublisher, + ) + from pyrit.output.finding_publisher.base import FindingPublisher + from pyrit.output.finding_publisher.errors import ( + FindingPublishCreateError, + FindingPublishDeadlineError, + FindingPublishDestinationError, + FindingPublisherConfigurationError, + FindingPublishError, + FindingPublisherUnavailableError, + FindingPublishPlanChangedError, + FindingPublishValidationError, + ) + from pyrit.output.finding_publisher.plan import FindingPublishPlan, FindingPublishPlanItem, plan_finding_publish + from pyrit.output.finding_report.report import FindingEvidenceLinkTarget, FindingSelection, build_finding_report + from pyrit.output.finding_report.selection import ( + FindingSelectionNotFoundError, + FindingSelectionTooLargeError, + build_finding_selection_async, + ) from pyrit.output.helpers import ( output_attack_async, output_conversation_async, @@ -37,7 +64,27 @@ from pyrit.output.sink import FileSink, IPythonMarkdownSink, OutputFormat, Sink, StdoutSink, get_default_sink _LAZY_EXPORTS: dict[str, str | tuple[str, str | None]] = { + "AzureDevOpsField": "pyrit.output.finding_publisher.azure_devops", + "AzureDevOpsFieldKind": "pyrit.output.finding_publisher.azure_devops", + "AzureDevOpsFindingPublisher": "pyrit.output.finding_publisher.azure_devops", + "build_finding_report": "pyrit.output.finding_report.report", + "build_finding_selection_async": "pyrit.output.finding_report.selection", "FileSink": "pyrit.output.sink", + "FindingEvidenceLinkTarget": "pyrit.output.finding_report.report", + "FindingPublishCreateError": "pyrit.output.finding_publisher.errors", + "FindingPublishDeadlineError": "pyrit.output.finding_publisher.errors", + "FindingPublishDestinationError": "pyrit.output.finding_publisher.errors", + "FindingPublishError": "pyrit.output.finding_publisher.errors", + "FindingPublisher": "pyrit.output.finding_publisher.base", + "FindingPublisherConfigurationError": "pyrit.output.finding_publisher.errors", + "FindingPublisherUnavailableError": "pyrit.output.finding_publisher.errors", + "FindingPublishPlan": "pyrit.output.finding_publisher.plan", + "FindingPublishPlanChangedError": "pyrit.output.finding_publisher.errors", + "FindingPublishPlanItem": "pyrit.output.finding_publisher.plan", + "FindingPublishValidationError": "pyrit.output.finding_publisher.errors", + "FindingSelection": "pyrit.output.finding_report.report", + "FindingSelectionNotFoundError": "pyrit.output.finding_report.selection", + "FindingSelectionTooLargeError": "pyrit.output.finding_report.selection", "get_default_sink": "pyrit.output.sink", "IPythonMarkdownSink": "pyrit.output.sink", "OutputFormat": "pyrit.output.sink", @@ -52,6 +99,7 @@ "output_score_async": "pyrit.output.helpers", "output_scorer_async": "pyrit.output.helpers", "output_scorer_selection_report_async": "pyrit.output.helpers", + "plan_finding_publish": "pyrit.output.finding_publisher.plan", "PrinterBase": "pyrit.output.base", "Sink": "pyrit.output.sink", "StdoutSink": "pyrit.output.sink", diff --git a/pyrit/output/finding_publisher/__init__.py b/pyrit/output/finding_publisher/__init__.py new file mode 100644 index 0000000000..e55474c484 --- /dev/null +++ b/pyrit/output/finding_publisher/__init__.py @@ -0,0 +1,4 @@ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT license. + +"""Finding publishers, which create items for selected findings in other systems.""" diff --git a/pyrit/output/finding_publisher/azure_devops.py b/pyrit/output/finding_publisher/azure_devops.py new file mode 100644 index 0000000000..bc3060e294 --- /dev/null +++ b/pyrit/output/finding_publisher/azure_devops.py @@ -0,0 +1,927 @@ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT license. + +"""Publish findings as Azure DevOps work items under an existing work item.""" + +import asyncio +import html +import json +import logging +import re +import unicodedata +from collections import Counter +from collections.abc import Awaitable, Callable, Collection, Iterator, Mapping +from dataclasses import dataclass +from enum import StrEnum +from time import monotonic +from typing import Any +from urllib.parse import quote, urlsplit + +import httpx + +from pyrit.common.net_utility import get_httpx_client +from pyrit.models import ( + ComponentIdentifier, + FindingField, + FindingFields, + FindingFieldType, + FindingPublishDestination, + FindingPublishedItem, + FindingPublisherInfo, + FindingPublishProblem, + FindingPublishRequester, +) +from pyrit.models.finding_fields import FindingFieldOption +from pyrit.output.finding_publisher.base import FindingPublisher +from pyrit.output.finding_publisher.errors import ( + FindingPublishCreateError, + FindingPublishDeadlineError, + FindingPublishDestinationError, + FindingPublisherConfigurationError, + FindingPublisherUnavailableError, +) +from pyrit.output.finding_publisher.plan import FindingPublishPlan, FindingPublishPlanItem +from pyrit.output.finding_report.report import ( + DETAIL_SEPARATOR, + PATH_STEP_SEPARATOR, + STEP_NOT_DEMONSTRATED, + UNAVAILABLE_EVIDENCE, + FindingReportEvidence, + FindingReportField, + FindingReportPath, + plain_text, +) + +logger = logging.getLogger(__name__) + +_TITLE = "System.Title" +_DESCRIPTION = "System.Description" +_AREA_PATH = "System.AreaPath" +_ITERATION_PATH = "System.IterationPath" +_ASSIGNED_TO = "System.AssignedTo" +_HISTORY = "System.History" +_SET_BY_PUBLISHER = (_TITLE, _AREA_PATH, _ITERATION_PATH, _ASSIGNED_TO, _HISTORY) +_PARENT_LINK = "System.LinkTypes.Hierarchy-Reverse" +_MAX_WORK_ITEM_ID = 2_147_483_647 +_ORGANIZATION = r"[A-Za-z0-9](?:[A-Za-z0-9-]*[A-Za-z0-9])?" +_DEV_AZURE_URL = re.compile(rf"https://dev\.azure\.com/(?P{_ORGANIZATION})/?", re.IGNORECASE) +_VISUAL_STUDIO_URL = re.compile(rf"https://(?P{_ORGANIZATION})\.visualstudio\.com/?", re.IGNORECASE) +_WORK_ITEM_PATH = re.compile(r"/_workitems/edit/([0-9]{1,10})(?:/|$)", re.IGNORECASE) +_SERVICE_CODE = re.compile(r"^(?:TF|VS)[0-9]+") +_RATE_LIMIT_HEADERS = ( + "Retry-After", + "X-RateLimit-Resource", + "X-RateLimit-Delay", + "X-RateLimit-Limit", + "X-RateLimit-Remaining", + "X-RateLimit-Reset", +) + +_TOKEN_MESSAGE = ( + "The server couldn't get an Azure DevOps token for its publishing identity. Ask an administrator to check the " + "deployment's identity." +) +_UNREACHABLE_MESSAGE = "Couldn't reach Azure DevOps. Try again in a few minutes." +_STATUS_MESSAGES = { + 401: ( + "Azure DevOps didn't accept the publishing identity (HTTP 401). Ask an administrator to check that it " + "belongs to the organization." + ), + 403: ( + "The publishing identity isn't allowed to do this in Azure DevOps (HTTP 403). Ask an administrator to check " + "its permissions on the project's area." + ), + 429: "Azure DevOps is throttling the publishing identity (HTTP 429). Try again in a few minutes.", +} + + +class AzureDevOpsFieldKind(StrEnum): + """How a finding value is written to an Azure DevOps field.""" + + HTML = "html" + """Escaped HTML, keeping line breaks.""" + TEXT = "text" + """One line, sent as written.""" + CHOICE = "choice" + """An option key, sent as written, so each key must equal an Azure DevOps value.""" + + +@dataclass(frozen=True) +class AzureDevOpsField: + """An Azure DevOps field that a finding value is written to, such as ``Custom.FindingSeverity``.""" + + reference_name: str + kind: AzureDevOpsFieldKind + + +@dataclass(frozen=True) +class _DestinationContext: + area_path: str + iteration_path: str + + +class _FailureKind(StrEnum): + TOKEN = "token" + UNREACHABLE = "unreachable" + NO_ANSWER = "no_answer" + REJECTED = "rejected" + + +class _RequestFailedError(Exception): + """A request that failed, classified by whether Azure DevOps could have acted on it.""" + + def __init__( + self, + *, + kind: _FailureKind, + detail: str = "", + status: int | None = None, + service_message: str = "", + diagnostics: Mapping[str, str] | None = None, + ) -> None: + super().__init__(kind.value) + self.kind = kind + self.detail = detail + self.status = status + self.service_message = service_message + self.diagnostics: Mapping[str, str] = dict(diagnostics or {}) + + +class AzureDevOpsFindingPublisher(FindingPublisher): + """ + Publishes findings as Azure DevOps work items under an existing work item, through REST API 7.1. + + Each finding becomes a work item of ``work_item_type``, linked as a child of the destination or of its parent + finding's new work item. Its Area and Iteration are copied from the destination, it is assigned to the requester, + and its History notes the requester, the run ID and the finding ID. ``bypassRules`` is never set, so the project's + rules apply. Titles and single-line values are never shortened; a value Azure DevOps can't hold is a problem. + + The constructor does no I/O. Requests use the publishing identity's Azure DevOps token, by default from + ``DefaultAzureCredential``, and each request has at most ``REQUEST_TIMEOUT_SECONDS``. + """ + + API_VERSION: str = "7.1" + AZURE_DEVOPS_SCOPE: str = "499b84ac-1321-427f-aa17-267ca6975798/.default" + REQUEST_TIMEOUT_SECONDS: float = 30.0 + MAX_SINGLE_LINE_LENGTH: int = 255 + + def __init__( + self, + *, + organization_url: str, + project: str, + work_item_type: str, + destination_work_item_types: Collection[str], + field_map: Mapping[str, AzureDevOpsField], + evidence_field: str, + unmapped_keys: Collection[str] = (), + fixed_fields: Mapping[str, str | bool] | None = None, + nest_sub_findings: bool = True, + destination_label: str = "Parent work item", + destination_hint: str = "Paste the parent work item's ID or URL.", + token_provider: Callable[[], Awaitable[str]] | None = None, + ) -> None: + """ + Configure the publisher without contacting Azure DevOps. + + Args: + organization_url (str): ``https://dev.azure.com/{organization}`` or + ``https://{organization}.visualstudio.com``. + project (str): The project that new work items, and the destination, belong to. + work_item_type (str): The type of the new work items. + destination_work_item_types (Collection[str]): The types a destination work item may have. + field_map (Mapping[str, AzureDevOpsField]): The Azure DevOps field for each finding field or level key, + including ``severity``. + evidence_field (str): The field that holds the evidence references, after any mapped evidence text. + unmapped_keys (Collection[str]): Finding field and level keys that are deliberately not published. + Defaults to none. + fixed_fields (Mapping[str, str | bool] | None): Values written to every new work item, by field + reference name. Defaults to None. + nest_sub_findings (bool): Whether a sub-finding goes under its parent finding's new work item when both + are published in one run. Otherwise every finding goes under the destination. Defaults to True. + destination_label (str): The label of the destination input. Defaults to "Parent work item". + destination_hint (str): The hint under the destination input. Defaults to + "Paste the parent work item's ID or URL.". + token_provider (Callable[[], Awaitable[str]] | None): Returns an Azure DevOps access token. Defaults to + None, which uses ``get_azure_async_token_provider`` with ``AZURE_DEVOPS_SCOPE`` on the first request. + + Raises: + ValueError: If ``organization_url`` has another form, or a required value is empty. + TypeError: If ``destination_work_item_types`` or ``unmapped_keys`` is a single string. + """ + self._organization_url, self._organization = _parse_organization_url(organization_url) + self._project = _require_text(name="project", value=project) + self._work_item_type = _require_text(name="work_item_type", value=work_item_type) + self._evidence_field = _require_text(name="evidence_field", value=evidence_field) + self._destination_types = tuple( + _require_text(name="destination_work_item_types", value=value) + for value in _require_collection(name="destination_work_item_types", value=destination_work_item_types) + ) + if not self._destination_types: + raise ValueError("destination_work_item_types needs at least one work item type.") + self._unmapped_keys = frozenset(_require_collection(name="unmapped_keys", value=unmapped_keys)) + self._field_map: dict[str, AzureDevOpsField] = dict(field_map) + self._fixed_fields: dict[str, str | bool] = dict(fixed_fields or {}) + self._nest_sub_findings = nest_sub_findings + self._info = FindingPublisherInfo(destination_label=destination_label, destination_hint=destination_hint) + self._token_provider = token_provider + + @property + def info(self) -> FindingPublisherInfo: + """The destination input's label and hint.""" + return self._info + + @property + def nest_sub_findings(self) -> bool: + """Whether a sub-finding goes under its parent finding's new work item when both are published.""" + return self._nest_sub_findings + + def check_fields(self, *, fields: FindingFields) -> None: + """ + Check that every finding field has one deliberate mapping that Azure DevOps can hold. + + Args: + fields (FindingFields): The active finding fields. + + Raises: + FindingPublisherConfigurationError: Listing every key or field that breaks a rule. + """ + errors = [*self._coverage_errors(fields), *self._target_errors(), *self._kind_errors(fields)] + if errors: + raise FindingPublisherConfigurationError( + "The Azure DevOps publisher can't publish these finding fields. " + " ".join(errors) + ) + + def _check_plan(self, *, plan: FindingPublishPlan, fields: FindingFields) -> list[FindingPublishProblem]: + """ + Report titles and single-line values that Azure DevOps can't hold as written. + + Args: + plan (FindingPublishPlan): The planned findings. + fields (FindingFields): The active finding fields. + + Returns: + list[FindingPublishProblem]: A problem for each value that has a line break or is too long. + """ + labels = _field_labels(fields) + problems = [] + for item in plan.items: + finding = item.finding + for label, noun, value in self._single_line_values(item=item, labels=labels): + message = self._single_line_problem(label=label, noun=noun, value=value) + if message is not None: + problems.append(FindingPublishProblem(finding_id=finding.id, title=finding.title, message=message)) + return problems + + async def _open_destination_async( + self, *, destination: str, deadline: float | None + ) -> tuple[FindingPublishDestination, object]: + """ + Parse the destination's ID or URL, then read the work item and check its project and type. + + Args: + destination (str): A work item ID, or a work item URL in the configured organization. + deadline (float | None): The ``time.monotonic()`` value by which the call must finish, or None. + + Returns: + tuple[FindingPublishDestination, object]: The destination, and its Area and Iteration to copy. + + Raises: + FindingPublishDestinationError: If the destination is invalid, missing, not visible, in another project + or of another type. + FindingPublisherUnavailableError: If Azure DevOps can't be used. + FindingPublishDeadlineError: If too little time is left to send the request. + """ + work_item_id = self._parse_destination(destination) + try: + body = await self._request_async( + method="GET", url=f"{self._organization_url}/_apis/wit/workitems/{work_item_id}", deadline=deadline + ) + except _RequestFailedError as failure: + raise self._destination_failure(failure=failure, work_item_id=work_item_id) from failure + return self._read_destination(work_item_id=work_item_id, body=body) + + async def _create_item_async( + self, + *, + item: FindingPublishPlanItem, + parent_external_id: str, + context: object, + run_id: str, + requested_by: FindingPublishRequester | None, + deadline: float | None, + ) -> FindingPublishedItem: + """ + Create one work item under its parent with a JSON Patch document. + + Args: + item (FindingPublishPlanItem): The planned finding. + parent_external_id (str): The parent work item's ID. + context (object): The destination's Area and Iteration. + run_id (str): The run's ID, written to the History. + requested_by (FindingPublishRequester | None): The person the work item is assigned to, or None. + deadline (float | None): The ``time.monotonic()`` value by which the call must finish, or None. + + Returns: + FindingPublishedItem: The new work item. + + Raises: + FindingPublishDeadlineError: Before sending, if too little time is left. + FindingPublishCreateError: If the work item wasn't created, or might have been. + TypeError: If ``context`` didn't come from ``_open_destination_async``. + """ + if not isinstance(context, _DestinationContext): + raise TypeError("The context must come from _open_destination_async.") + document = self._work_item_document( + item=item, parent_external_id=parent_external_id, context=context, run_id=run_id, requested_by=requested_by + ) + url = ( + f"{self._organization_url}/{quote(self._project, safe='')}/_apis/wit/workitems/" + f"${quote(self._work_item_type, safe='')}" + ) + try: + body = await self._request_async( + method="POST", url=url, deadline=deadline, document=document, run_id=run_id + ) + except _RequestFailedError as failure: + raise self._create_failure(failure=failure, requested_by=requested_by) from failure + external_id, html_url = _created_work_item(body) + return FindingPublishedItem( + finding_id=item.finding.id, + title=item.finding.title, + external_id=external_id, + url=html_url, + parent_external_id=parent_external_id, + ) + + def _build_identifier(self) -> ComponentIdentifier: + """ + Record every setting that shapes the work items, without labels or credentials. + + Returns: + ComponentIdentifier: The publisher's identity. + """ + return ComponentIdentifier.of( + self, + params={ + "organization_url": self._organization_url, + "project": self._project, + "work_item_type": self._work_item_type, + "destination_work_item_types": sorted(self._destination_types), + "field_map": { + key: {"reference_name": target.reference_name, "kind": target.kind.value} + for key, target in sorted(self._field_map.items()) + }, + "unmapped_keys": sorted(self._unmapped_keys), + "fixed_fields": dict(sorted(self._fixed_fields.items())), + "evidence_field": self._evidence_field, + "nest_sub_findings": self._nest_sub_findings, + }, + ) + + # Configuration checks + + def _coverage_errors(self, fields: FindingFields) -> Iterator[str]: + keys = fields.field_keys | {"severity"} + mapped = set(self._field_map) + for key in sorted(keys - mapped - self._unmapped_keys): + yield f"Map '{key}' in field_map, or list it in unmapped_keys." + for key in sorted(mapped & self._unmapped_keys): + yield f"'{key}' is in both field_map and unmapped_keys." + for key in sorted((mapped | self._unmapped_keys) - keys): + yield f"'{key}' in field_map or unmapped_keys isn't a finding field or level." + + def _target_errors(self) -> Iterator[str]: + targets = Counter(target.reference_name.casefold() for target in self._field_map.values()) + for name, count in sorted(targets.items()): + if count > 1: + yield f"Only one key can map to '{name}'." + written = [*(target.reference_name for target in self._field_map.values()), *self._fixed_fields] + for name in written: + if _is_one_of(name, names=_SET_BY_PUBLISHER): + yield f"'{name}' is set by the publisher, so no key or fixed field can target it." + for name in self._fixed_fields: + if _is_one_of(name, names=(_DESCRIPTION, self._evidence_field, *targets)): + yield f"Fixed field '{name}' is also written from the findings." + if _is_one_of(self._evidence_field, names=(_DESCRIPTION, *_SET_BY_PUBLISHER)): + yield f"evidence_field can't be '{self._evidence_field}'." + + def _kind_errors(self, fields: FindingFields) -> Iterator[str]: + sources = dict(_field_sources(fields)) + for key, target in sorted(self._field_map.items()): + if key not in sources: + continue + field, depth = sources[key] + takes_html = _is_one_of(target.reference_name, names=(_DESCRIPTION, self._evidence_field)) + if takes_html and target.kind != AzureDevOpsFieldKind.HTML: + yield f"'{key}' maps to '{target.reference_name}', which takes kind html." + continue + yield from self._kind_error(key=key, kind=target.kind, field=field, depth=depth) + + def _kind_error(self, *, key: str, kind: AzureDevOpsFieldKind, field: FindingField, depth: int) -> Iterator[str]: + if kind == AzureDevOpsFieldKind.CHOICE and field.type == FindingFieldType.CHOICE and not field.allow_other: + for option in _options_at(options=field.options, depth=depth): + if self._single_line_problem(label="", noun="", value=option.key) is not None: + yield f"Option key {option.key!r} of '{key}' must be one line of at most 255 characters." + return + accepted = { + AzureDevOpsFieldKind.TEXT: (FindingFieldType.TEXT, FindingFieldType.NUMBER), + AzureDevOpsFieldKind.HTML: (FindingFieldType.MULTILINE, FindingFieldType.TEXT), + } + if depth == 0 and field.type in accepted.get(kind, ()): + return + source = f"a level of {field.type} field '{field.key}'" if depth else f"a {field.type} field" + if field.allow_other: + source += " that takes Other text" + yield f"'{key}' is {source}, which kind {kind} can't publish; list it in unmapped_keys instead." + + # Plan checks + + def _single_line_values( + self, *, item: FindingPublishPlanItem, labels: Mapping[str, str] + ) -> Iterator[tuple[str, str, str]]: + yield "Title", "titles", item.finding.title + for key, target in self._field_map.items(): + value = _stored_value(item=item, key=key) + if target.kind == AzureDevOpsFieldKind.TEXT and value: + yield labels.get(key, key), "single-line fields", value + + def _single_line_problem(self, *, label: str, noun: str, value: str) -> str | None: + if any(unicodedata.category(character) in ("Cc", "Cs") or character in "\u2028\u2029" for character in value): + return f"{label} contains a line break or tab. Azure DevOps {noun} hold one line." + length = len(value.encode("utf-16-le", "surrogatepass")) // 2 + if length > self.MAX_SINGLE_LINE_LENGTH: + return ( + f"{label} is {length} characters long, as Azure DevOps counts them; emoji and some symbols count as " + f"two. Azure DevOps accepts at most {self.MAX_SINGLE_LINE_LENGTH}." + ) + return None + + # Destination + + def _parse_destination(self, destination: str) -> int: + text = destination.strip() + # At most ten digits, the length of the largest ID, so a huge number can't reach int(). + work_item_id = text if re.fullmatch(r"[0-9]{1,10}", text) else self._work_item_id_from_url(text) + if work_item_id is None or not 1 <= int(work_item_id) <= _MAX_WORK_ITEM_ID: + raise FindingPublishDestinationError( + f"Paste a work item ID, or a link from {self._organization_url}, such as " + f"{self._organization_url}/{quote(self._project)}/_workitems/edit/12345." + ) + return int(work_item_id) + + def _work_item_id_from_url(self, text: str) -> str | None: + try: + parts = urlsplit(text) + port = parts.port + except ValueError: + return None + host = (parts.hostname or "").casefold() + if parts.scheme.casefold() != "https" or parts.username is not None or port is not None: + return None + path = parts.path + organization = self._organization.casefold() + if host == "dev.azure.com": + first, _, path = path.lstrip("/").partition("/") + if first.casefold() != organization: + return None + path = "/" + path + elif host != f"{organization}.visualstudio.com": + return None + match = _WORK_ITEM_PATH.search(path) + return str(match.group(1)) if match else None + + def _read_destination( + self, *, work_item_id: int, body: Mapping[str, Any] + ) -> tuple[FindingPublishDestination, _DestinationContext]: + fields = body.get("fields") + html_url = _nested_text(body, "_links", "html", "href") + if not isinstance(fields, Mapping) or not html_url: + raise FindingPublisherUnavailableError(_no_answer_message("unreadable response")) + project = _text(fields.get("System.TeamProject")) + if project.casefold() != self._project.casefold(): + raise FindingPublishDestinationError(f"Work item {work_item_id} isn't in the {self._project} project.") + work_item_type = _text(fields.get("System.WorkItemType")) + if not _is_one_of(work_item_type, names=self._destination_types): + raise FindingPublishDestinationError( + f"Work item {work_item_id} is of type {work_item_type or 'unknown'}. Paste a work item of type " + f"{' or '.join(self._destination_types)}." + ) + destination = FindingPublishDestination( + id=str(work_item_id), + title=_text(fields.get(_TITLE)), + url=html_url, + location=f"{self._organization} / {project}", + ) + context = _DestinationContext( + area_path=_text(fields.get(_AREA_PATH)), iteration_path=_text(fields.get(_ITERATION_PATH)) + ) + return destination, context + + def _destination_failure(self, *, failure: _RequestFailedError, work_item_id: int) -> Exception: + if failure.status == 404: + return FindingPublishDestinationError( + f"Work item {work_item_id} doesn't exist, or the publishing identity can't see it.", + diagnostics=failure.diagnostics, + ) + return FindingPublisherUnavailableError(_failure_message(failure), diagnostics=failure.diagnostics) + + # Work items + + def _work_item_document( + self, + *, + item: FindingPublishPlanItem, + parent_external_id: str, + context: _DestinationContext, + run_id: str, + requested_by: FindingPublishRequester | None, + ) -> list[dict[str, Any]]: + email = _non_blank(requested_by.email) if requested_by else None + values: dict[str, str | bool] = { + _TITLE: item.finding.title, + **self._mapped_values(item), + _DESCRIPTION: self._description_html(item), + self._evidence_field: _join_with_rule( + main=self._mapped_html(item=item, reference_name=self._evidence_field), + appendix=_evidence_html(item.entry.evidence), + ), + **self._fixed_fields, + _AREA_PATH: context.area_path, + _ITERATION_PATH: context.iteration_path, + _ASSIGNED_TO: email or "", + _HISTORY: _html(_history_note(run_id=run_id, finding_id=str(item.finding.id), requested_by=requested_by)), + } + document: list[dict[str, Any]] = [ + {"op": "add", "path": f"/fields/{name}", "value": value} for name, value in values.items() if value != "" + ] + parent_url = f"{self._organization_url}/_apis/wit/workItems/{parent_external_id}" + document.append({"op": "add", "path": "/relations/-", "value": {"rel": _PARENT_LINK, "url": parent_url}}) + return document + + def _mapped_values(self, item: FindingPublishPlanItem) -> dict[str, str]: + values = {} + for key, target in self._field_map.items(): + value = _stored_value(item=item, key=key) + if not value or _is_one_of(target.reference_name, names=(_DESCRIPTION, self._evidence_field)): + continue + values[target.reference_name] = _html(value) if target.kind == AzureDevOpsFieldKind.HTML else value + return values + + def _mapped_html(self, *, item: FindingPublishPlanItem, reference_name: str) -> str: + for key, target in self._field_map.items(): + if _is_one_of(target.reference_name, names=(reference_name,)): + return _html(_stored_value(item=item, key=key)) + return "" + + def _description_html(self, item: FindingPublishPlanItem) -> str: + appendix = "" + if item.part_of: + appendix += f"

Part of: {_html(item.part_of)}

" + if item.entry.paths: + appendix += _paths_html(item.entry.paths) + if item.retired: + retired = "".join(f"
  • {_html(key)}: {_html(value)}
  • " for key, value in item.retired) + appendix += f"

    Retired fields

      {retired}
    " + return _join_with_rule(main=self._mapped_html(item=item, reference_name=_DESCRIPTION), appendix=appendix) + + def _create_failure( + self, *, failure: _RequestFailedError, requested_by: FindingPublishRequester | None + ) -> FindingPublishCreateError: + if failure.kind == _FailureKind.NO_ANSWER: + message = ( + f"Couldn't get an answer from Azure DevOps ({failure.detail}). This work item might exist anyway. " + "Check Azure DevOps before publishing this finding again." + ) + return FindingPublishCreateError(message, outcome_unknown=True, diagnostics=failure.diagnostics) + email = _non_blank(requested_by.email) if requested_by else None + if failure.status == 400 and email and re.search(r"assigned\s?to", failure.service_message, re.IGNORECASE): + message = ( + f"Azure DevOps couldn't assign the work item to {email} (HTTP 400). Ask the organization's " + "administrators to add you, or ask a member to publish." + ) + else: + message = _failure_message(failure) + return FindingPublishCreateError(message, outcome_unknown=False, diagnostics=failure.diagnostics) + + # Requests + + async def _request_async( + self, + *, + method: str, + url: str, + deadline: float | None, + document: list[dict[str, Any]] | None = None, + run_id: str | None = None, + ) -> Mapping[str, Any]: + """ + Send one request with a fresh client, within the request timeout and only if it fits the deadline. + + Returns: + Mapping[str, Any]: The JSON object of a 2xx response. + + Raises: + FindingPublishDeadlineError: Before getting a token, if less than a full request timeout is left. + _RequestFailedError: If the request failed, classified by whether it could have reached Azure DevOps. + """ + if deadline is not None and deadline - monotonic() < self.REQUEST_TIMEOUT_SECONDS: + raise FindingPublishDeadlineError("Too little time is left to send another request to Azure DevOps.") + sent = False + try: + async with asyncio.timeout(self.REQUEST_TIMEOUT_SECONDS): + token = await self._get_token_async() + sent = True + response = await self._send_async(method=method, url=url, token=token, document=document) + except TimeoutError as exc: + if not sent: + logger.warning("Getting an Azure DevOps token for the publishing identity timed out.") + raise _RequestFailedError(kind=_FailureKind.TOKEN) from exc + raise _RequestFailedError(kind=_FailureKind.NO_ANSWER, detail="timed out") from exc + except (httpx.ConnectError, httpx.ConnectTimeout) as exc: + raise _RequestFailedError(kind=_FailureKind.UNREACHABLE) from exc + except httpx.TimeoutException as exc: + raise _RequestFailedError(kind=_FailureKind.NO_ANSWER, detail="timed out") from exc + except httpx.RequestError as exc: + raise _RequestFailedError(kind=_FailureKind.NO_ANSWER, detail="no response") from exc + _warn_if_slowed(method=method, response=response, run_id=run_id) + return _read_response(response) + + async def _get_token_async(self) -> str: + try: + if self._token_provider is None: + from pyrit.auth import get_azure_async_token_provider + + self._token_provider = get_azure_async_token_provider(self.AZURE_DEVOPS_SCOPE) + token = await self._token_provider() + except Exception as exc: + logger.warning("Couldn't get an Azure DevOps token for the publishing identity.", exc_info=True) + raise _RequestFailedError(kind=_FailureKind.TOKEN) from exc + if not isinstance(token, str) or not token: + logger.warning("The Azure DevOps token provider returned no token.") + raise _RequestFailedError(kind=_FailureKind.TOKEN) + return token + + async def _send_async( + self, *, method: str, url: str, token: str, document: list[dict[str, Any]] | None + ) -> httpx.Response: + headers = {"Authorization": f"Bearer {token}", "Accept": "application/json"} + content = None + if document is not None: + headers["Content-Type"] = "application/json-patch+json" + content = json.dumps(document) + async with get_httpx_client(use_async=True, timeout=self.REQUEST_TIMEOUT_SECONDS) as client: + return await client.request( + method, url, params={"api-version": self.API_VERSION}, headers=headers, content=content + ) + + +def _parse_organization_url(organization_url: str) -> tuple[str, str]: + url = organization_url.strip() + for pattern in (_DEV_AZURE_URL, _VISUAL_STUDIO_URL): + match = pattern.fullmatch(url) + if match: + return url.rstrip("/"), str(match.group("org")) + raise ValueError( + "organization_url must be https://dev.azure.com/{organization} or https://{organization}.visualstudio.com, " + f"not {organization_url!r}." + ) + + +def _require_text(*, name: str, value: str) -> str: + if not isinstance(value, str) or not value.strip(): + raise ValueError(f"{name} must not be empty.") + return value + + +def _require_collection(*, name: str, value: Collection[str]) -> Collection[str]: + if isinstance(value, str): + raise TypeError(f"{name} takes a collection of strings, not a single string.") + return value + + +def _is_one_of(name: str, *, names: Collection[str]) -> bool: + folded = name.casefold() + return any(folded == other.casefold() for other in names) + + +def _field_sources(fields: FindingFields) -> Iterator[tuple[str, tuple[FindingField, int]]]: + """ + Pair each finding field and level key with its field and its depth: 0 for the field, then 1 for each level. + + Yields: + tuple[str, tuple[FindingField, int]]: Each key with its field and depth. + """ + for field in [fields.severity, *fields.fields]: + yield field.key, (field, 0) + for depth, (level_key, _) in enumerate(field.levels, start=1): + yield level_key, (field, depth) + + +def _field_labels(fields: FindingFields) -> dict[str, str]: + labels = {} + for field in [fields.severity, *fields.fields]: + labels[field.key] = field.label + labels.update(field.levels) + return labels + + +def _options_at(*, options: list[FindingFieldOption], depth: int) -> Iterator[FindingFieldOption]: + level = options + for _ in range(depth): + level = [child for option in level for child in option.children] + return iter(level) + + +def _stored_value(*, item: FindingPublishPlanItem, key: str) -> str: + finding = item.finding + value = str(finding.severity) if key == "severity" else finding.field_values.get(key, "") + return value if value.strip() else "" + + +def _non_blank(value: str | None) -> str | None: + return value.strip() if value and value.strip() else None + + +def _text(value: object) -> str: + return value if isinstance(value, str) else "" + + +def _nested_text(body: Mapping[str, Any], *keys: str) -> str: + value: object = body + for key in keys: + value = value.get(key) if isinstance(value, Mapping) else None + return _text(value) + + +def _html(value: str) -> str: + """ + Escape authored text for an HTML field, keeping its line breaks. + + Returns: + str: The text with control characters marked, HTML escaped and line breaks as ``
    ``. + """ + return html.escape(plain_text(value)).replace("\n", "
    ") + + +def _join_with_rule(*, main: str, appendix: str) -> str: + return f"{main}
    {appendix}" if main and appendix else main or appendix + + +def _paths_html(paths: tuple[FindingReportPath, ...]) -> str: + items = [] + for path in paths: + steps = PATH_STEP_SEPARATOR.join( + _html(step.title) if step.demonstrated else f"{_html(step.title)} ({STEP_NOT_DEMONSTRATED})" + for step in path.steps + ) + text = f"{_html(path.name)} ({path.status.capitalize()})" + if path.description: + text += f"
    {_html(path.description)}" + if steps: + text += f"
    Steps: {steps}" + items.append(f"
  • {text}
  • ") + return f"

    Attack paths

      {''.join(items)}
    " + + +def _evidence_html(evidence: tuple[FindingReportEvidence, ...]) -> str: + if not evidence: + return "" + items = [] + for reference in evidence: + title = _html(reference.title) + link = _safe_link(reference.link_url) + lines = [f'{title}' if link else f"{title}"] + if reference.summary: + lines.append(DETAIL_SEPARATOR.join(_labelled_html(field) for field in reference.summary)) + lines.extend(_labelled_html(field) for field in reference.details) + if reference.unavailable: + lines.append(UNAVAILABLE_EVIDENCE) + items.append(f"
  • {'
    '.join(lines)}
  • ") + return f"
      {''.join(items)}
    " + + +def _labelled_html(field: FindingReportField) -> str: + return f"{_html(field.label)}: {_html(field.value)}" + + +def _safe_link(url: str | None) -> str | None: + """ + Accept only an absolute ``http`` or ``https`` link without whitespace or control characters. + + Returns: + str | None: The link escaped for an ``href`` attribute, or None to show the title without a link. + """ + if not url or any(character.isspace() or unicodedata.category(character) in ("Cc", "Cs") for character in url): + return None + try: + parts = urlsplit(url) + except ValueError: + return None + if parts.scheme.casefold() not in ("http", "https") or not parts.netloc: + return None + return html.escape(url, quote=True) + + +def _history_note(*, run_id: str, finding_id: str, requested_by: FindingPublishRequester | None) -> str: + name = _non_blank(requested_by.name) if requested_by else None + email = _non_blank(requested_by.email) if requested_by else None + who = f"{name} ({email})" if name and email else name or email or "a CoPyRIT user" + return f"Published from CoPyRIT by {who}. Run {run_id}, finding {finding_id}." + + +def _created_work_item(body: Mapping[str, Any]) -> tuple[str, str]: + work_item_id = body.get("id") + html_url = _nested_text(body, "_links", "html", "href") + valid_id = isinstance(work_item_id, int) and not isinstance(work_item_id, bool) + if not valid_id or not 1 <= work_item_id <= _MAX_WORK_ITEM_ID or not html_url: + raise FindingPublishCreateError( + "Couldn't get an answer from Azure DevOps (unreadable response). This work item might exist anyway. " + "Check Azure DevOps before publishing this finding again.", + outcome_unknown=True, + ) + return str(work_item_id), html_url + + +def _read_response(response: httpx.Response) -> Mapping[str, Any]: + status = response.status_code + body = _json_object(response) + if 200 <= status < 300: + if body is None: + raise _RequestFailedError( + kind=_FailureKind.NO_ANSWER, + detail="unreadable response", + status=status, + diagnostics=_diagnostics(response), + ) + return body + message = _text((body or {}).get("message")).strip() + kind = _FailureKind.REJECTED if 400 <= status < 500 else _FailureKind.NO_ANSWER + raise _RequestFailedError( + kind=kind, detail=f"HTTP {status}", status=status, service_message=message, diagnostics=_diagnostics(response) + ) + + +def _json_object(response: httpx.Response) -> Mapping[str, Any] | None: + try: + body = response.json() + except ValueError: + return None + return body if isinstance(body, dict) else None + + +def _diagnostics(response: httpx.Response) -> dict[str, str]: + """ + Collect what helps an administrator read a failure: never the service's message text, which can quote values. + + Returns: + dict[str, str]: The HTTP status, the service's type key and TF or VS code, and the rate-limit headers. + """ + diagnostics = {"HTTP": str(response.status_code)} + body = _json_object(response) or {} + type_key = _text(body.get("typeKey")) + if type_key: + diagnostics["typeKey"] = type_key + code = _SERVICE_CODE.match(_text(body.get("message"))) + if code: + diagnostics["code"] = code.group(0) + diagnostics.update({name: response.headers[name] for name in _RATE_LIMIT_HEADERS if name in response.headers}) + return diagnostics + + +def _warn_if_slowed(*, method: str, response: httpx.Response, run_id: str | None) -> None: + delay = response.headers.get("X-RateLimit-Delay") + if "Retry-After" not in response.headers and not _is_nonzero(delay): + return + headers = ", ".join(f"{name} {response.headers[name]}" for name in _RATE_LIMIT_HEADERS if name in response.headers) + run = f", run {run_id}" if run_id else "" + logger.warning( + "Azure DevOps is slowing the publishing identity: %s HTTP %s, %s%s.", method, response.status_code, headers, run + ) + + +def _is_nonzero(value: str | None) -> bool: + if value is None: + return False + try: + return float(value) != 0 + except ValueError: + return True + + +def _failure_message(failure: _RequestFailedError) -> str: + if failure.kind == _FailureKind.TOKEN: + return _TOKEN_MESSAGE + if failure.kind == _FailureKind.UNREACHABLE: + return _UNREACHABLE_MESSAGE + if failure.kind == _FailureKind.NO_ANSWER: + return _no_answer_message(failure.detail) + if failure.status in _STATUS_MESSAGES: + return _STATUS_MESSAGES[failure.status] + if failure.service_message: + return f"Azure DevOps rejected the request (HTTP {failure.status}): {failure.service_message}" + return f"Azure DevOps rejected the request (HTTP {failure.status})." + + +def _no_answer_message(detail: str) -> str: + return f"Couldn't get an answer from Azure DevOps ({detail}). Try again in a few minutes." diff --git a/pyrit/output/finding_publisher/base.py b/pyrit/output/finding_publisher/base.py new file mode 100644 index 0000000000..f9a52d7af5 --- /dev/null +++ b/pyrit/output/finding_publisher/base.py @@ -0,0 +1,434 @@ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT license. + +"""The contract every finding publisher follows: preview where findings go, then publish and report every outcome.""" + +import asyncio +import logging +from abc import ABC, abstractmethod +from collections.abc import Callable, Mapping +from dataclasses import dataclass, field +from time import monotonic +from uuid import UUID, uuid4 + +from pyrit.models import ( + FindingFields, + FindingPublishDestination, + FindingPublishedItem, + FindingPublisherInfo, + FindingPublishFailure, + FindingPublishPreview, + FindingPublishProblem, + FindingPublishReference, + FindingPublishRequester, + FindingPublishResult, + FindingValuesError, + Identifiable, +) +from pyrit.output.finding_publisher.errors import ( + FindingPublishCreateError, + FindingPublishDeadlineError, + FindingPublishPlanChangedError, + FindingPublishValidationError, +) +from pyrit.output.finding_publisher.plan import FindingPublishPlan, FindingPublishPlanItem, plan_finding_publish +from pyrit.output.finding_report.report import FindingEvidenceLinkTarget, FindingSelection + +logger = logging.getLogger(__name__) + + +class FindingPublisher(Identifiable, ABC): + """ + Creates items for selected findings under an existing item in another system, such as a work item tracker. + + ``preview_async`` shows where every finding would go and writes nothing. ``publish_async`` creates the items one + at a time, parents first, and stops at the first failure. Until it first asks a subclass to create an item, + errors propagate. From then on, every outcome is in the result and only cancellation escapes. + + Subclasses implement ``info``, ``_open_destination_async``, ``_create_item_async`` and ``_build_identifier``, and + may override ``check_fields``, ``_check_plan`` and ``nest_sub_findings``. A publisher keeps no per-call state, so + one instance can serve concurrent callers. + """ + + STOPPED_FOR_TIME: str = "Stopped to stay within the time limit. Publish the findings that weren't attempted again." + UNEXPECTED_FAILURE: str = ( + "An unexpected error stopped the run while creating this item. It might exist anyway; check the destination " + "before publishing it again." + ) + + @property + @abstractmethod + def info(self) -> FindingPublisherInfo: + """How a surface asks for this publisher's destination.""" + + @property + def nest_sub_findings(self) -> bool: + """Whether a sub-finding goes under its planned parent's new item rather than under the destination.""" + return True + + def check_fields(self, *, fields: FindingFields) -> None: + """ + Check that this publisher can represent every finding field. Accepts any fields unless a subclass overrides it. + + Args: + fields (FindingFields): The active finding fields. + + Raises: + FindingPublisherConfigurationError: In a subclass, if the publisher can't represent the fields. + """ + + async def preview_async( + self, + *, + selection: FindingSelection, + fields: FindingFields, + destination: str, + deadline: float | None = None, + ) -> FindingPublishPreview: + """ + Show where every selected finding would go, without writing anything. + + The destination is opened even when there are problems, so one preview shows everything to fix. Nothing a + preview returns depends on evidence links, so it takes no link builder. + + Args: + selection (FindingSelection): The selected findings with their evidence. + fields (FindingFields): The active finding fields. + destination (str): The existing item that new items go under, as the user wrote it. + deadline (float | None): The ``time.monotonic()`` value by which the call must finish. Defaults to None, + for no overall limit. + + Returns: + FindingPublishPreview: The destination, the planned findings, the skipped findings, the problems and the + plan digest that ``publish_async`` checks. + + Raises: + FindingPublisherConfigurationError: If the publisher can't represent the fields. + FindingPublishDestinationError: If the destination is invalid, missing or not one the publisher takes. + FindingPublisherUnavailableError: If the destination's service can't be used. + FindingPublishDeadlineError: If too little time is left. + """ + self.check_fields(fields=fields) + plan = plan_finding_publish(selection=selection, fields=fields, nest_sub_findings=self.nest_sub_findings) + problems = self._find_problems(plan=plan, fields=fields) + opened, _ = await self._open_async(destination=destination, deadline=deadline) + return FindingPublishPreview( + destination=opened, + planned=tuple(item.preview for item in plan.items), + skipped=plan.skipped, + problems=tuple(problems), + plan_digest=self._digest(plan=plan, destination=destination), + ) + + async def publish_async( + self, + *, + selection: FindingSelection, + fields: FindingFields, + destination: str, + link_for: Callable[[FindingEvidenceLinkTarget], str] | None = None, + requested_by: FindingPublishRequester | None = None, + expected_plan_digest: str | None = None, + deadline: float | None = None, + ) -> FindingPublishResult: + """ + Create an item for each planned finding, parents first, and report every finding's outcome. + + The run stops at the first failure and writes one WARNING summary line, without names, emails, titles or + field values. + + Args: + selection (FindingSelection): The selected findings with their evidence. + fields (FindingFields): The active finding fields. + destination (str): The existing item that new items go under, as the user wrote it. + link_for (Callable[[FindingEvidenceLinkTarget], str] | None): Builds the link for evidence whose + conversation can be opened, such as a public dashboard route. Defaults to None, for evidence + without links. Links don't change the plan digest, so a preview's digest still matches. + requested_by (FindingPublishRequester | None): The person the publish is for. Defaults to None. + expected_plan_digest (str | None): The digest that ``preview_async`` returned. Defaults to None, which + skips the comparison. + deadline (float | None): The ``time.monotonic()`` value by which the call must finish. Defaults to None, + for no overall limit. + + Returns: + FindingPublishResult: The run ID and every finding's outcome. + + Raises: + FindingPublishPlanChangedError: If the plan differs from ``expected_plan_digest``. + FindingPublishValidationError: If any planned finding has a problem. + FindingPublisherConfigurationError: If the publisher can't represent the fields. + FindingPublishDestinationError: If the destination is invalid, missing or not one the publisher takes. + FindingPublisherUnavailableError: If the destination's service can't be used. + FindingPublishDeadlineError: If too little time is left before the first item is created. + """ + self.check_fields(fields=fields) + plan = plan_finding_publish( + selection=selection, fields=fields, link_for=link_for, nest_sub_findings=self.nest_sub_findings + ) + if expected_plan_digest is not None and expected_plan_digest != self._digest( + plan=plan, destination=destination + ): + raise FindingPublishPlanChangedError + problems = self._find_problems(plan=plan, fields=fields) + if problems: + raise FindingPublishValidationError(problems=problems) + run_id = uuid4().hex + opened, context = await self._open_async(destination=destination, deadline=deadline) + run = _PublishRun(run_id=run_id, publisher=type(self).__name__, plan=plan, destination=opened) + await self._create_items_async(run=run, context=context, requested_by=requested_by, deadline=deadline) + return run.result() + + def _check_plan(self, *, plan: FindingPublishPlan, fields: FindingFields) -> list[FindingPublishProblem]: + """ + Report what the destination can't accept, beyond the finding fields' own rules. Finds nothing by default. + + Args: + plan (FindingPublishPlan): The planned findings. + fields (FindingFields): The active finding fields. + + Returns: + list[FindingPublishProblem]: The problems, in plan order. + """ + return [] + + @abstractmethod + async def _open_destination_async( + self, *, destination: str, deadline: float | None + ) -> tuple[FindingPublishDestination, object]: + """ + Parse and read the destination. + + Args: + destination (str): The destination as the user wrote it. + deadline (float | None): The ``time.monotonic()`` value by which the call must finish, or None. + + Returns: + tuple[FindingPublishDestination, object]: The destination, and a context for this call that is passed to + ``_create_item_async``. The context must not hold open resources, because nothing closes it. + + Raises: + FindingPublishDestinationError: If the destination is invalid, missing or not one the publisher takes. + FindingPublisherUnavailableError: If the destination's service can't be used. + FindingPublishDeadlineError: If too little time is left. + """ + + @abstractmethod + async def _create_item_async( + self, + *, + item: FindingPublishPlanItem, + parent_external_id: str, + context: object, + run_id: str, + requested_by: FindingPublishRequester | None, + deadline: float | None, + ) -> FindingPublishedItem: + """ + Create one item under an existing item, recording the run ID and the finding ID in it. + + Args: + item (FindingPublishPlanItem): The planned finding. + parent_external_id (str): The item to create it under: the destination, or its parent's new item. + context (object): The context that ``_open_destination_async`` returned. + run_id (str): The run's ID. + requested_by (FindingPublishRequester | None): The person the publish is for, or None. + deadline (float | None): The ``time.monotonic()`` value by which the call must finish, or None. + + Returns: + FindingPublishedItem: The created item. + + Raises: + FindingPublishDeadlineError: Only before sending anything, if too little time is left. + FindingPublishCreateError: If the item couldn't be created. Set ``outcome_unknown=False`` only when + nothing was sent or the response proves that nothing was created. + """ + + def _find_problems(self, *, plan: FindingPublishPlan, fields: FindingFields) -> list[FindingPublishProblem]: + # Stored values that no current field uses are published as retired values, not checked. + problems = [] + for item in plan.items: + finding = item.finding + values = {key: value for key, value in finding.field_values.items() if key in fields.field_keys} + try: + fields.check_values(severity=finding.severity, field_values=values) + except FindingValuesError as exc: + problems.append(FindingPublishProblem(finding_id=finding.id, title=finding.title, message=str(exc))) + positions = {item.finding.id: index for index, item in enumerate(plan.items)} + # A stable sort keeps each finding's value problem before its destination problems. + return sorted( + [*problems, *self._check_plan(plan=plan, fields=fields)], + key=lambda problem: positions.get(problem.finding_id, len(positions)), + ) + + async def _open_async( + self, *, destination: str, deadline: float | None + ) -> tuple[FindingPublishDestination, object]: + if _deadline_passed(deadline): + raise FindingPublishDeadlineError("The time limit passed before the destination could be opened.") + return await self._open_destination_async(destination=destination, deadline=deadline) + + async def _create_items_async( + self, + *, + run: "_PublishRun", + context: object, + requested_by: FindingPublishRequester | None, + deadline: float | None, + ) -> None: + try: + for item in run.plan.items: + if not await self._create_next_async( + run=run, item=item, context=context, requested_by=requested_by, deadline=deadline + ): + return + except asyncio.CancelledError: + run.cancelled = True + raise + finally: + logger.warning(run.summary()) + + async def _create_next_async( + self, + *, + run: "_PublishRun", + item: FindingPublishPlanItem, + context: object, + requested_by: FindingPublishRequester | None, + deadline: float | None, + ) -> bool: + if _deadline_passed(deadline): + run.stop(reason=self.STOPPED_FOR_TIME) + if not run.created: + raise FindingPublishDeadlineError("The time limit passed before any item could be created.") + return False + parent = run.destination.id if item.parent_finding_id is None else run.external_ids[item.parent_finding_id] + # Stays set only if the call is cancelled, when its request may already have reached the destination. + run.in_flight = item + try: + published = await self._create_item_async( + item=item, + parent_external_id=parent, + context=context, + run_id=run.run_id, + requested_by=requested_by, + deadline=deadline, + ) + # Recording stays guarded: once the create has returned, the item may exist, so nothing may escape. + run.add(item=item, published=_require_published_item(published)) + except FindingPublishDeadlineError: + run.stop(reason=self.STOPPED_FOR_TIME) + return False + except FindingPublishCreateError as exc: + run.fail(item=item, message=str(exc), outcome_unknown=exc.outcome_unknown, diagnostics=exc.diagnostics) + return False + except Exception: + logger.warning("Finding publish run %s stopped on an unexpected error.", run.run_id, exc_info=True) + run.fail(item=item, message=self.UNEXPECTED_FAILURE, outcome_unknown=True) + return False + return True + + def _digest(self, *, plan: FindingPublishPlan, destination: str) -> str: + return plan.digest(identifier_hash=self.get_identifier().hash, destination=destination) + + +@dataclass +class _PublishRun: + """One publish run's progress, kept per call so a shared publisher holds no per-call state.""" + + run_id: str + publisher: str + plan: FindingPublishPlan + destination: FindingPublishDestination + created: list[FindingPublishedItem] = field(default_factory=list) + external_ids: dict[UUID, str] = field(default_factory=dict) + failure: FindingPublishFailure | None = None + diagnostics: Mapping[str, str] = field(default_factory=dict) + stopped_reason: str | None = None + cancelled: bool = False + in_flight: FindingPublishPlanItem | None = None + + def add(self, *, item: FindingPublishPlanItem, published: FindingPublishedItem) -> None: + external_id = published.external_id + self.created.append(published) + self.external_ids[item.finding.id] = external_id + self.in_flight = None + + def stop(self, *, reason: str) -> None: + self.stopped_reason = reason + self.in_flight = None + + def fail( + self, + *, + item: FindingPublishPlanItem, + message: str, + outcome_unknown: bool, + diagnostics: Mapping[str, str] | None = None, + ) -> None: + self.failure = FindingPublishFailure( + finding_id=item.finding.id, title=item.finding.title, message=message, outcome_unknown=outcome_unknown + ) + self.diagnostics = diagnostics or {} + self.in_flight = None + + @property + def not_attempted(self) -> tuple[FindingPublishPlanItem, ...]: + finished = len(self.created) + (1 if self.failure is not None else 0) + return self.plan.items[finished + (1 if self.in_flight is not None else 0) :] + + def result(self) -> FindingPublishResult: + return FindingPublishResult( + run_id=self.run_id, + destination=self.destination, + created=tuple(self.created), + skipped=self.plan.skipped, + failure=self.failure, + stopped_reason=self.stopped_reason, + not_attempted=tuple( + FindingPublishReference(finding_id=item.finding.id, title=item.finding.title) + for item in self.not_attempted + ), + ) + + def summary(self) -> str: + """ + Describe the run in one line for administrators, without names, emails, titles or field values. + + Returns: + str: The run ID, publisher, destination ID, created IDs, outcome counts, failure and stop. + """ + created = f"created {len(self.created)}" + if self.created: + created += f" ({', '.join(item.external_id for item in self.created)})" + if self.in_flight is not None: + created += ", in flight 1 (outcome unknown)" + if self.failure is None: + failure = "no failure" + else: + failure = f"failure with {'unknown' if self.failure.outcome_unknown else 'known'} outcome" + if self.diagnostics: + failure += f" ({', '.join(f'{key} {value}' for key, value in self.diagnostics.items())})" + stopped = "cancelled" if self.cancelled else "yes" if self.stopped_reason else "no" + return ( + f"Finding publish run {self.run_id} to destination {self.destination.id} by {self.publisher}: {created}, " + f"skipped {len(self.plan.skipped)}, not attempted {len(self.not_attempted)}; {failure}; stopped: {stopped}." + ) + + +def _require_published_item(published: object) -> FindingPublishedItem: + """ + Check what ``_create_item_async`` returned before the run records it. + + Returns: + FindingPublishedItem: The created item. + + Raises: + TypeError: If the hook returned anything else, so the run records an unknown outcome for the item. + """ + if not isinstance(published, FindingPublishedItem): + raise TypeError(f"_create_item_async returned {type(published).__name__}, not FindingPublishedItem.") + return published + + +def _deadline_passed(deadline: float | None) -> bool: + return deadline is not None and monotonic() >= deadline diff --git a/pyrit/output/finding_publisher/errors.py b/pyrit/output/finding_publisher/errors.py new file mode 100644 index 0000000000..9444aaf8d2 --- /dev/null +++ b/pyrit/output/finding_publisher/errors.py @@ -0,0 +1,88 @@ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT license. + +"""Errors that finding publishers raise.""" + +from collections.abc import Mapping, Sequence + +from pyrit.models import FindingPublishProblem + + +class FindingPublishError(Exception): + """ + Base class of finding publishing errors. + + ``diagnostics`` hold what helps an administrator read a log, such as an HTTP status, the service's error code and + its rate-limit headers. They never hold names, emails, titles, field values or the service's message text. + """ + + def __init__(self, message: str, *, diagnostics: Mapping[str, str] | None = None) -> None: + """ + Initialize the error. + + Args: + message (str): What happened, for the operator. + diagnostics (Mapping[str, str] | None): Details for logs only. Defaults to None. + """ + super().__init__(message) + self.diagnostics: Mapping[str, str] = dict(diagnostics or {}) + + +class FindingPublishPlanChangedError(FindingPublishError): + """Raised when the plan differs from the one the preview returned, so nothing is published.""" + + def __init__(self) -> None: + """Initialize the error with its message.""" + super().__init__("The findings changed since Check; check again.") + + +class FindingPublishValidationError(FindingPublishError): + """Raised when a publish finds problems, before it writes anything.""" + + def __init__(self, *, problems: Sequence[FindingPublishProblem]) -> None: + """ + Initialize the error with the problems to fix. + + Args: + problems (Sequence[FindingPublishProblem]): Each problem, in plan order. + """ + count = len(problems) + super().__init__(f"Fix {count} {'problem' if count == 1 else 'problems'} before publishing.") + self.problems: tuple[FindingPublishProblem, ...] = tuple(problems) + + +class FindingPublishDestinationError(FindingPublishError, ValueError): + """Raised when the destination can't be parsed, doesn't exist or isn't visible, or isn't one the publisher takes.""" + + +class FindingPublisherUnavailableError(FindingPublishError): + """Raised before any item is created when the service rejects the credentials, has no token or can't be reached.""" + + +class FindingPublishDeadlineError(FindingPublishError): + """Raised when the deadline passed, or too little time is left to send another request.""" + + +class FindingPublishCreateError(FindingPublishError): + """ + Raised by ``FindingPublisher._create_item_async`` when an item couldn't be created. + + ``outcome_unknown`` is True when the item might exist anyway. The base class records the error as the run's + failure, so it never escapes ``publish_async``. + """ + + def __init__(self, message: str, *, outcome_unknown: bool, diagnostics: Mapping[str, str] | None = None) -> None: + """ + Initialize the error. + + Args: + message (str): What happened, for the operator. + outcome_unknown (bool): Whether the item might exist anyway. + diagnostics (Mapping[str, str] | None): Details for logs only. Defaults to None. + """ + super().__init__(message, diagnostics=diagnostics) + self.outcome_unknown = outcome_unknown + + +class FindingPublisherConfigurationError(FindingPublishError): + """Raised when a publisher can't represent the active finding fields.""" diff --git a/pyrit/output/finding_publisher/plan.py b/pyrit/output/finding_publisher/plan.py new file mode 100644 index 0000000000..a87d4e283f --- /dev/null +++ b/pyrit/output/finding_publisher/plan.py @@ -0,0 +1,158 @@ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT license. + +"""Plan which selected findings a publish creates items for, in which order, and under which parent.""" + +import hashlib +import json +from collections.abc import Callable, Mapping +from dataclasses import dataclass +from uuid import UUID + +from pyrit.models import Finding, FindingFields, FindingPublishPreviewItem, FindingPublishSkip +from pyrit.output.finding_report.report import ( + FindingEvidenceLinkTarget, + FindingReportEntry, + FindingSelection, + build_finding_report, +) + +NOT_DEMONSTRATED_REASON = "Not demonstrated" + + +@dataclass(frozen=True) +class FindingPublishPlanItem: + """ + A finding to create an item for. + + ``finding`` holds the raw values, such as option keys, and ``entry`` the evidence and paths as the reports show + them. ``parent_finding_id`` is the planned finding whose new item this one goes under; None means the destination. + ``part_of`` is the parent's title when the finding has a parent but doesn't go under its new item. ``retired`` + holds the ``(key, value)`` of each stored value that no current field uses, in stored order. + """ + + finding: Finding + entry: FindingReportEntry + parent_finding_id: UUID | None + part_of: str | None + retired: tuple[tuple[str, str], ...] + + @property + def preview(self) -> FindingPublishPreviewItem: + """The item as a preview shows it.""" + return FindingPublishPreviewItem( + finding_id=self.finding.id, + title=self.finding.title, + parent_finding_id=self.parent_finding_id, + part_of=self.part_of, + ) + + +@dataclass(frozen=True) +class FindingPublishPlan: + """The findings to create items for, parents before children, and the selected findings left out.""" + + items: tuple[FindingPublishPlanItem, ...] + skipped: tuple[FindingPublishSkip, ...] + + def digest(self, *, identifier_hash: str, destination: str) -> str: + """ + Fingerprint what a publish would create, so it can check that nothing changed since a preview. + + Titles and field values are left out, because a publish checks them again. Evidence links are left out too: + they change what an item says, not which items are created or where. + + Args: + identifier_hash (str): The publisher's identifier hash, which covers its configuration. + destination (str): The destination as the caller wrote it. Surrounding whitespace is ignored. + + Returns: + str: The SHA-256 hex digest of the publisher, the destination, the planned ``(finding, parent)`` pairs + and the skipped findings. + """ + pairs = sorted( + (str(item.finding.id), str(item.parent_finding_id) if item.parent_finding_id else "") for item in self.items + ) + skipped = sorted(str(skip.finding_id) for skip in self.skipped) + content = json.dumps([identifier_hash, destination.strip(), pairs, skipped], separators=(",", ":")) + return hashlib.sha256(content.encode("utf-8")).hexdigest() + + +def plan_finding_publish( + *, + selection: FindingSelection, + fields: FindingFields, + link_for: Callable[[FindingEvidenceLinkTarget], str] | None = None, + nest_sub_findings: bool = True, +) -> FindingPublishPlan: + """ + Plan a publish: order the findings as the reports do, skip those that weren't demonstrated, and decide nesting. + + A sub-finding goes under its parent's new item only when the parent is planned in the same run. Otherwise it goes + under the destination, with its parent's title as ``part_of``. The sub-findings of a skipped finding are still + planned. Each item's evidence and paths come from ``build_finding_report``, as the reports show them. + + Args: + selection (FindingSelection): The selected findings, with their evidence and the titles of parents outside + the selection. + fields (FindingFields): The finding fields that label the values. + link_for (Callable[[FindingEvidenceLinkTarget], str] | None): Builds the link for evidence whose + conversation can be opened. Defaults to None, for evidence without links. + nest_sub_findings (bool): Whether a sub-finding goes under its planned parent's new item. Defaults to True. + + Returns: + FindingPublishPlan: The planned findings, parents before children, and the skipped ones. + """ + report = build_finding_report(selection=selection, fields=fields, link_for=link_for) + findings = {finding.id: finding for finding in selection.findings} + titles = {**selection.part_of, **{finding_id: finding.title for finding_id, finding in findings.items()}} + items: list[FindingPublishPlanItem] = [] + skipped: list[FindingPublishSkip] = [] + planned: set[UUID] = set() + # Pre-order without recursion, so a deep decomposition cannot exhaust the stack. + pending = list(reversed(report.findings)) + while pending: + entry = pending.pop() + pending.extend(reversed(entry.children)) + finding = findings[_finding_id(entry)] + if not finding.demonstrated: + skipped.append( + FindingPublishSkip(finding_id=finding.id, title=finding.title, reason=NOT_DEMONSTRATED_REASON) + ) + continue + items.append( + _plan_item( + finding=finding, + entry=entry, + nests=nest_sub_findings and finding.parent_finding_id in planned, + titles=titles, + fields=fields, + ) + ) + planned.add(finding.id) + return FindingPublishPlan(items=tuple(items), skipped=tuple(skipped)) + + +def _plan_item( + *, + finding: Finding, + entry: FindingReportEntry, + nests: bool, + titles: Mapping[UUID, str], + fields: FindingFields, +) -> FindingPublishPlanItem: + parent_id = finding.parent_finding_id + retired = fields.describe_values(severity=finding.severity, field_values=finding.field_values).retired + return FindingPublishPlanItem( + finding=finding, + entry=entry, + parent_finding_id=parent_id if nests else None, + part_of=titles.get(parent_id) if parent_id is not None and not nests else None, + retired=tuple(retired), + ) + + +def _finding_id(entry: FindingReportEntry) -> UUID: + if entry.finding_id is None: + raise ValueError(f"Report entry {entry.heading!r} has no finding ID.") + return entry.finding_id diff --git a/pyrit/output/finding_report/markdown.py b/pyrit/output/finding_report/markdown.py index 58e293e584..b2ac046b67 100644 --- a/pyrit/output/finding_report/markdown.py +++ b/pyrit/output/finding_report/markdown.py @@ -7,7 +7,6 @@ from pyrit.output.base import PrinterBase from pyrit.output.finding_report.report import ( DETAIL_SEPARATOR, - EVIDENCE_NOTE, NO_EVIDENCE, PATH_STEP_SEPARATOR, PATHS_LABEL, @@ -63,7 +62,7 @@ async def render_async(self, report: FindingReport) -> str: Returns: str: The Markdown document. """ - blocks = [f"# Findings - {_markdown_inline(report.operation_name)}", EVIDENCE_NOTE] + blocks = [f"# Findings - {_markdown_inline(report.operation_name)}", report.evidence_note] # Depth-first without recursion, so a deep decomposition cannot exhaust the stack. pending = [(finding, 0) for finding in reversed(report.findings)] while pending: diff --git a/pyrit/output/finding_report/report.py b/pyrit/output/finding_report/report.py index c091c22ef9..ef48f43d25 100644 --- a/pyrit/output/finding_report/report.py +++ b/pyrit/output/finding_report/report.py @@ -4,7 +4,7 @@ """An Operation's findings laid out for a report, and the text every report format shares.""" import re -from collections.abc import Mapping, Sequence +from collections.abc import Callable, Mapping, Sequence from dataclasses import dataclass, replace from enum import StrEnum from uuid import UUID @@ -16,16 +16,23 @@ Finding, FindingCreate, FindingFields, + ResolvedFindingEvidence, + Score, + ScoreStatus, is_finding_path_complete, ) EVIDENCE_NOTE = "Evidence is listed as references with links to the PyRIT dashboard; transcripts are not included." +UNLINKED_EVIDENCE_NOTE = "Evidence is listed as references; transcripts are not included." UNAVAILABLE_EVIDENCE = "Evidence unavailable" DETAIL_SEPARATOR = " · " PATHS_LABEL = "Paths" PATH_STEP_SEPARATOR = " → " STEP_NOT_DEMONSTRATED = "not demonstrated" +_HUMAN_SCORER = "ManualScorer" +_UNKNOWN_SCORER = "Unknown" +_BOOLEAN_SCORES = {"true": "True", "false": "False"} _LINE_BREAK = re.compile("\r\n|[\r\n\v\f\x1c-\x1e\x85\u2028\u2029]") _UNPRINTABLE = re.compile(r"[\x00-\x08\x0b-\x1f\x7f-\x9f\ud800-\udfff\ufffe\uffff]") @@ -55,18 +62,24 @@ class FindingReportEvidence: """ An attack result attached to a finding, as a reference rather than a transcript. - The ``summary`` fields share one line, and each of the ``details`` has its own. + The ``summary`` fields share one line, and each of the ``details`` has its own. ``available`` is whether the + attack result exists and its conversation has messages, whether or not the report links to it. + ``build_finding_report`` always sets it. ``None`` infers it from ``link_url``, as before: evidence without a link + is unavailable. """ title: str summary: tuple[FindingReportField, ...] details: tuple[FindingReportField, ...] link_url: str | None + available: bool | None = None @property def unavailable(self) -> bool: - """Whether the evidence has no conversation to link to.""" - return self.link_url is None + """Whether the evidence's attack result or its conversation is gone.""" + if self.available is None: + return self.link_url is None + return not self.available @dataclass(frozen=True) @@ -109,7 +122,9 @@ class FindingReportEntry: A finding's title, severity, other populated fields in report order, evidence, paths, and sub-findings. ``number`` places the finding in the report, for example ``1.2`` for the second sub-finding of the first - finding, so path steps can refer to sub-findings. + finding, so path steps can refer to sub-findings. ``finding_id`` is the saved finding's ID, which + ``build_finding_report`` sets so other output, such as a publish plan, can join an entry to its finding. No + report format shows it. """ title: str @@ -120,6 +135,7 @@ class FindingReportEntry: demonstrated: bool = True paths: tuple[FindingReportPath, ...] = () children: tuple["FindingReportEntry", ...] = () + finding_id: UUID | None = None @property def heading(self) -> str: @@ -134,10 +150,41 @@ def status(self) -> FindingReportField | None: @dataclass(frozen=True) class FindingReport: - """An Operation's selected findings, in report order. Sub-findings are nested in their parents.""" + """ + An Operation's selected findings, in report order. Sub-findings are nested in their parents. + + ``evidence_note`` opens the report and says whether evidence links to the PyRIT dashboard. + """ operation_name: str findings: tuple[FindingReportEntry, ...] + evidence_note: str = EVIDENCE_NOTE + + +@dataclass(frozen=True) +class FindingSelection: + """ + An Operation's selected findings, each with its resolved evidence, newest link first. + + ``evidence`` is keyed by finding ID, and ``part_of`` holds the titles of parents outside the selection, keyed by + the parent's ID. + """ + + operation_id: UUID + operation_name: str + findings: tuple[Finding, ...] + evidence: Mapping[UUID, tuple[ResolvedFindingEvidence, ...]] + part_of: Mapping[UUID, str] + + +@dataclass(frozen=True) +class FindingEvidenceLinkTarget: + """What a link to available evidence can point at: the evidence, its attack, and the conversation to open.""" + + evidence_id: UUID + attack_result_id: UUID + conversation_id: str + scenario_result_id: UUID | None def finding_report_entry( @@ -179,25 +226,26 @@ def finding_report_entry( def build_finding_report( *, - operation_name: str, - findings: Sequence[Finding], + selection: FindingSelection, fields: FindingFields, - evidence: Mapping[UUID, tuple[FindingReportEvidence, ...]], - part_of: Mapping[UUID, str], + link_for: Callable[[FindingEvidenceLinkTarget], str] | None = None, ) -> FindingReport: """ Build a numbered report, preserving root order and sorting children oldest first. + Each piece of evidence appears as its attack's objective, outcome, and score, in the selection's order. + Args: - operation_name (str): The report's operation name. - findings (Sequence[Finding]): Complete selected subtrees, without repeated findings. + selection (FindingSelection): Complete selected subtrees, without repeated findings, and their evidence. A + finding without an evidence entry has no evidence. fields (FindingFields): The finding fields that label each finding's values. - evidence (Mapping[UUID, tuple[FindingReportEvidence, ...]]): Projected evidence for each finding. - part_of (Mapping[UUID, str]): Titles of parents outside the selected subtrees. + link_for (Callable[[FindingEvidenceLinkTarget], str] | None): Builds the link for evidence whose + conversation can be opened, such as a PyRIT dashboard route. Defaults to None, for a report without links. Returns: FindingReport: The report, ready for a formatter without further data access. """ + findings = selection.findings by_id = {finding.id: finding for finding in findings} roots = [finding for finding in findings if finding.parent_finding_id not in by_id] children = sorted( @@ -212,12 +260,77 @@ def build_finding_report( ) for finding in (*roots, *children) ) + evidence = { + finding.id: tuple( + _project_evidence(resolved=item, operation_id=selection.operation_id, link_for=link_for) + for item in selection.evidence.get(finding.id, ()) + ) + for finding in findings + } return FindingReport( - operation_name=operation_name, - findings=_project_entries(tree=tree, findings=by_id, fields=fields, evidence=evidence, part_of=part_of), + operation_name=selection.operation_name, + findings=_project_entries( + tree=tree, findings=by_id, fields=fields, evidence=evidence, part_of=selection.part_of + ), + evidence_note=EVIDENCE_NOTE if link_for is not None else UNLINKED_EVIDENCE_NOTE, ) +def _project_evidence( + *, + resolved: ResolvedFindingEvidence, + operation_id: UUID, + link_for: Callable[[FindingEvidenceLinkTarget], str] | None, +) -> FindingReportEvidence: + if resolved.outcome is None: + # The attack result is gone, so its saved ID stands in for its objective. + return FindingReportEvidence( + title=str(resolved.evidence.attack_result_id), summary=(), details=(), link_url=None, available=False + ) + objective = resolved.objective if resolved.objective and resolved.objective.strip() else "No objective" + summary = ( + FindingReportField(label="Outcome", value=resolved.outcome.value.capitalize()), + FindingReportField(label="Score", value=_score_text(resolved.score)), + ) + details = [] + if resolved.score is not None and resolved.score.score_rationale: + details.append(FindingReportField(label="Rationale", value=resolved.score.score_rationale)) + # As on the dashboard, an attack's Operation is named only when it isn't the report's own. + if resolved.source_operation_id != operation_id: + details.append( + FindingReportField(label="From operation", value=resolved.source_operation_name or "Not in an operation") + ) + link_url = None + if link_for is not None and resolved.available and resolved.conversation_id is not None: + link_url = link_for( + FindingEvidenceLinkTarget( + evidence_id=resolved.evidence.id, + attack_result_id=resolved.evidence.attack_result_id, + conversation_id=resolved.conversation_id, + scenario_result_id=resolved.scenario_result_id, + ) + ) + return FindingReportEvidence( + title=objective, + summary=summary, + details=tuple(details), + link_url=link_url, + available=resolved.available, + ) + + +def _score_text(score: Score | None) -> str: + if score is None: + return "Not scored" + if score.status == ScoreStatus.UNDETERMINED: + value = "Undetermined" + else: + value = _BOOLEAN_SCORES.get(str(score.score_value).lower(), str(score.score_value)) + identifier = score.scorer_class_identifier + scorer = identifier.class_name if identifier and identifier.class_name else _UNKNOWN_SCORER + return f"{value} ({'human review' if scorer == _HUMAN_SCORER else scorer})" + + def _project_entries( *, tree: DecompositionTree, @@ -235,7 +348,7 @@ def _project_entries( roots = set(tree.roots) for finding_id in reversed(visit_order): finding = findings[finding_id] - entry = finding_report_entry(finding=finding, fields=fields, evidence=evidence[finding_id]) + entry = finding_report_entry(finding=finding, fields=fields, evidence=evidence.get(finding_id, ())) parent_id = finding.parent_finding_id parent_title = part_of.get(parent_id) if parent_id is not None and finding_id in roots else None entries[finding_id] = replace( @@ -249,6 +362,7 @@ def _project_entries( for index, path in enumerate(finding.paths, start=1) ), children=tuple(entries[child] for child in tree.get_children(finding_id)), + finding_id=finding_id, ) return tuple(entries[root] for root in tree.roots) diff --git a/pyrit/output/finding_report/selection.py b/pyrit/output/finding_report/selection.py new file mode 100644 index 0000000000..a0cc83a30e --- /dev/null +++ b/pyrit/output/finding_report/selection.py @@ -0,0 +1,89 @@ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT license. + +"""Gather an Operation's selected findings and their evidence from memory, ready for a report.""" + +from collections.abc import Sequence +from uuid import UUID + +from pyrit.models import FindingFields +from pyrit.output.finding_report.report import FindingSelection + + +class FindingSelectionNotFoundError(LookupError): + """Raised when the Operation doesn't exist, or a selected finding isn't in it.""" + + +class FindingSelectionTooLargeError(ValueError): + """Raised when the selected findings, counting all of their sub-findings, are more than the caller allows.""" + + def __init__(self, *, max_findings: int) -> None: + """ + Name the limit the selection exceeded. + + Args: + max_findings (int): The most findings the caller allows, counting sub-findings. + """ + super().__init__(f"Select at most {max_findings:,} findings, counting sub-findings.") + self.max_findings = max_findings + + +async def build_finding_selection_async( + *, + operation_id: UUID, + finding_ids: Sequence[UUID], + fields: FindingFields, + max_findings: int | None = None, +) -> FindingSelection: + """ + Read selected findings of an Operation with all of their sub-findings and evidence. + + The findings come from one consistent read, in the dashboard's listing order. Each finding's evidence is resolved + to its attack's current outcome and score, newest link first. Pass the selection to ``build_finding_report``. + + Args: + operation_id (UUID): The Operation the findings belong to. + finding_ids (Sequence[UUID]): The selected findings. Each includes all of its sub-findings. + fields (FindingFields): The finding fields whose severity order sorts the findings. + max_findings (int | None): The most findings to read, counting sub-findings. Defaults to None, for no limit. + + Returns: + FindingSelection: The findings, their evidence, and the titles of parents outside the selection. + + Raises: + FindingSelectionNotFoundError: If the Operation doesn't exist, or a selected finding isn't in it. + FindingSelectionTooLargeError: If there are more than ``max_findings`` findings, counting sub-findings. + """ + from pyrit.memory import CentralMemory + + memory = CentralMemory.get_memory_instance() + try: + operation = await memory.require_operation_async(operation_id=operation_id) + except LookupError as exc: + raise FindingSelectionNotFoundError(f"Operation '{operation_id}' not found.") from exc + # One snapshot of the selected trees: every path step is among these findings, so they are not read again. + findings = await memory.get_finding_subtrees_async( + operation_id=operation_id, finding_ids=finding_ids, severity_order=fields.severity_order + ) + found = {finding.id for finding in findings} + missing = next((finding_id for finding_id in finding_ids if finding_id not in found), None) + if missing is not None: + raise FindingSelectionNotFoundError(f"Finding '{missing}' not found in operation '{operation_id}'.") + if max_findings is not None and len(findings) > max_findings: + raise FindingSelectionTooLargeError(max_findings=max_findings) + linked = await memory.get_finding_evidence_for_findings_async(finding_ids=[finding.id for finding in findings]) + resolved = await memory.get_resolved_finding_evidence_async( + evidence=[item for finding in findings for item in linked.get(finding.id, [])] + ) + by_id = {item.evidence.id: item for item in resolved} + parents = await memory.get_findings_by_ids_async( + operation_id=operation_id, + finding_ids=list({finding.parent_finding_id for finding in findings if finding.parent_finding_id} - found), + ) + return FindingSelection( + operation_id=operation.id, + operation_name=operation.name, + findings=tuple(findings), + evidence={finding.id: tuple(by_id[item.id] for item in linked.get(finding.id, [])) for finding in findings}, + part_of={parent.id: parent.title for parent in parents}, + ) diff --git a/pyrit/registry/__init__.py b/pyrit/registry/__init__.py index a66d50160f..8fc146a715 100644 --- a/pyrit/registry/__init__.py +++ b/pyrit/registry/__init__.py @@ -15,6 +15,8 @@ AttackTechniqueRegistry, ConverterMetadata, ConverterRegistry, + FindingPublisherMetadata, + FindingPublisherRegistry, InitializerMetadata, InitializerRegistry, ScenarioMetadata, @@ -78,6 +80,8 @@ "ConverterRegistry": "pyrit.registry.components", "ConverterMetadata": "pyrit.registry.components", "DefaultInstanceRegistry": "pyrit.registry.instance_registry", + "FindingPublisherMetadata": "pyrit.registry.components", + "FindingPublisherRegistry": "pyrit.registry.components", "InstanceRegistry": "pyrit.registry.instance_registry", "InstanceHoldingRegistry": "pyrit.registry.registry", "ParamBagRegistry": "pyrit.registry.registry", diff --git a/pyrit/registry/components/__init__.py b/pyrit/registry/components/__init__.py index 4b8eb59426..cf9542acc8 100644 --- a/pyrit/registry/components/__init__.py +++ b/pyrit/registry/components/__init__.py @@ -23,6 +23,10 @@ from pyrit.registry.components.attack_registry import AttackRegistry from pyrit.registry.components.attack_technique_registry import AttackTechniqueMetadata, AttackTechniqueRegistry from pyrit.registry.components.converter_registry import ConverterMetadata, ConverterRegistry + from pyrit.registry.components.finding_publisher_registry import ( + FindingPublisherMetadata, + FindingPublisherRegistry, + ) from pyrit.registry.components.initializer_registry import InitializerMetadata, InitializerRegistry from pyrit.registry.components.scenario_preset_registry import ( ScenarioPresetInUseError, @@ -46,6 +50,8 @@ "AttackTechniqueMetadata": "pyrit.registry.components.attack_technique_registry", "ConverterRegistry": "pyrit.registry.components.converter_registry", "ConverterMetadata": "pyrit.registry.components.converter_registry", + "FindingPublisherRegistry": "pyrit.registry.components.finding_publisher_registry", + "FindingPublisherMetadata": "pyrit.registry.components.finding_publisher_registry", "InitializerRegistry": "pyrit.registry.components.initializer_registry", "InitializerMetadata": "pyrit.registry.components.initializer_registry", "ScorerRegistry": "pyrit.registry.components.scorer_registry", diff --git a/pyrit/registry/components/finding_publisher_registry.py b/pyrit/registry/components/finding_publisher_registry.py new file mode 100644 index 0000000000..6b39a16dc4 --- /dev/null +++ b/pyrit/registry/components/finding_publisher_registry.py @@ -0,0 +1,48 @@ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT license. + +""" +Finding publisher registry for PyRIT. + +Holds the ``FindingPublisher`` instances a deployment offers, by name. CoPyRIT shows **Publish findings** only when +one is registered. Publishers are configured in code, such as an initializer, so the registry has no buildable class +catalog. +""" + +from __future__ import annotations + +from dataclasses import dataclass +from typing import TYPE_CHECKING + +from pyrit.registry.registry import InstanceHoldingRegistry +from pyrit.registry.registry_metadata import RegistryMetadata + +if TYPE_CHECKING: + from pyrit.output import FindingPublisher + + +@dataclass(frozen=True) +class FindingPublisherMetadata(RegistryMetadata): + """Metadata describing a ``FindingPublisher`` class. The registry catalogs none.""" + + +class FindingPublisherRegistry(InstanceHoldingRegistry["FindingPublisher", FindingPublisherMetadata]): + """ + Registry that holds configured ``FindingPublisher`` instances under ``instances``. + + Register a publisher from an initializer with ``instances.register(publisher, name=...)``. A publisher needs + configuration that no form can supply, such as a field map, so the class catalog stays empty. + """ + + def _base_type(self) -> type[FindingPublisher]: + """Return ``FindingPublisher``, imported lazily, which ``instances.register`` checks against.""" + from pyrit.output import FindingPublisher + + return FindingPublisher + + def _discover(self) -> None: + """Register no classes, so no publisher constructor is offered for building from user input.""" + + def _metadata_class(self) -> type[FindingPublisherMetadata]: + """Return ``FindingPublisherMetadata``.""" + return FindingPublisherMetadata diff --git a/pyrit/setup/initialization.py b/pyrit/setup/initialization.py index 64d6004b57..24694473aa 100644 --- a/pyrit/setup/initialization.py +++ b/pyrit/setup/initialization.py @@ -69,6 +69,7 @@ def reset_setup_registries() -> None: AttackRegistry, AttackTechniqueRegistry, ConverterRegistry, + FindingPublisherRegistry, InitializerRegistry, ScenarioPresetRegistry, ScenarioRegistry, @@ -85,6 +86,7 @@ def reset_setup_registries() -> None: AttackRegistry, AttackTechniqueRegistry, ConverterRegistry, + FindingPublisherRegistry, InitializerRegistry, ScenarioPresetRegistry, ScenarioRegistry, diff --git a/tests/end_to_end/browser_initializer.py b/tests/end_to_end/browser_initializer.py index cf1beae2af..ee8c28a1d4 100644 --- a/tests/end_to_end/browser_initializer.py +++ b/tests/end_to_end/browser_initializer.py @@ -12,6 +12,11 @@ from pyrit.memory import AttackResultEntry, CentralMemory from pyrit.models import ( AttackResult, + ComponentIdentifier, + FindingPublishDestination, + FindingPublishedItem, + FindingPublisherInfo, + FindingPublishRequester, Message, MessagePiece, ScenarioPreset, @@ -21,8 +26,10 @@ SeedObjective, SeedPrompt, ) +from pyrit.output import FindingPublisher, FindingPublishPlanItem from pyrit.prompt_target import PromptTarget, TargetCapabilities, TargetConfiguration from pyrit.registry import ( + FindingPublisherRegistry, ScenarioPresetRegistry, ScenarioRegistry, ScenarioSuiteRegistry, @@ -43,6 +50,41 @@ from pyrit.setup.pyrit_initializer import PyRITInitializer +class BrowserFindingPublisher(FindingPublisher): + """Publish findings under any destination name without provider access, creating nothing.""" + + @property + def info(self) -> FindingPublisherInfo: + return FindingPublisherInfo(destination_label="Offline folder", destination_hint="Name any folder.") + + def _build_identifier(self) -> ComponentIdentifier: + return ComponentIdentifier.of(self) + + async def _open_destination_async( + self, *, destination: str, deadline: float | None + ) -> tuple[FindingPublishDestination, object]: + name = destination.strip() + return FindingPublishDestination(id=name, title=f"Folder {name}", url="", location="Offline"), None + + async def _create_item_async( + self, + *, + item: FindingPublishPlanItem, + parent_external_id: str, + context: object, + run_id: str, + requested_by: FindingPublishRequester | None, + deadline: float | None, + ) -> FindingPublishedItem: + return FindingPublishedItem( + finding_id=item.finding.id, + title=item.finding.title, + external_id=f"offline-{item.finding.id.hex[:8]}", + url="", + parent_external_id=parent_external_id, + ) + + class BrowserTarget(PromptTarget): """Return a deterministic response without provider access.""" @@ -129,6 +171,9 @@ async def initialize_async(self) -> None: memory = CentralMemory.get_memory_instance() TargetRegistry.get_registry_singleton().register_class(BrowserTarget) TargetRegistry.get_registry_singleton().instances.register(BrowserTarget(), name="browser_offline") + FindingPublisherRegistry.get_registry_singleton().instances.register( + BrowserFindingPublisher(), name="browser_offline" + ) ScorerRegistry.get_registry_singleton().instances.register( SubStringScorer(substring="Offline browser"), name="browser_scorer", diff --git a/tests/unit/backend/test_finding_export.py b/tests/unit/backend/test_finding_export.py index 8a7efd861e..e4ea1ac521 100644 --- a/tests/unit/backend/test_finding_export.py +++ b/tests/unit/backend/test_finding_export.py @@ -22,12 +22,7 @@ import pyrit.memory.memory_interface as memory_interface from pyrit.backend.main import app -from pyrit.backend.models import ScoreView -from pyrit.backend.models.operations import ( - EvidenceAvailability, - FindingEvidenceItem, - FindingExportRequest, -) +from pyrit.backend.models.operations import FindingExportRequest from pyrit.backend.services import finding_export from pyrit.backend.services.finding_export import _render_docx from pyrit.backend.services.operation_service import OperationService @@ -50,6 +45,7 @@ Score, ScoreStatus, ) +from pyrit.output import FindingEvidenceLinkTarget from pyrit.output.finding_report.markdown import MarkdownFindingReportPrinter from pyrit.output.finding_report.report import ( FindingReport, @@ -562,9 +558,11 @@ async def test_report_selects_findings_beyond_the_first_dashboard_page_in_dashbo summary=(FindingReportField(label="Outcome", value="Undetermined"), NOT_SCORED), details=(), link_url=_dashboard_link(evidence=evidence, conversation_id="main"), + available=True, ), ), number="1", + finding_id=named["Critical finding"].id, ), FindingReportEntry( title="Included finding", @@ -572,6 +570,7 @@ async def test_report_selects_findings_beyond_the_first_dashboard_page_in_dashbo fields=(), evidence=(), number="2", + finding_id=named["Included finding"].id, ), FindingReportEntry( title="Low finding", @@ -579,6 +578,7 @@ async def test_report_selects_findings_beyond_the_first_dashboard_page_in_dashbo fields=(), evidence=(), number="3", + finding_id=named["Low finding"].id, ), ), ) @@ -602,50 +602,6 @@ async def test_report_matches_the_dashboard_listing_order(sqlite_instance: SQLit assert [finding.title for finding in report.findings] == [finding.title for finding in dashboard] -async def test_report_reads_findings_once_and_attaches_evidence_to_them( - named_findings_async: tuple[Operation, dict[str, Finding]], -) -> None: - operation, named = named_findings_async - selected = [named["Low finding"].id, named["Critical finding"].id] - subtree_read = OperationService.get_finding_subtrees_async - evidence_read = OperationService.get_evidence_for_findings_async - - with ( - patch.object(OperationService, "get_finding_subtrees_async", autospec=True, side_effect=subtree_read) as tree, - patch.object( - OperationService, "get_evidence_for_findings_async", autospec=True, side_effect=evidence_read - ) as with_evidence, - patch.object( - OperationService, - "get_findings_with_evidence_async", - autospec=True, - side_effect=AssertionError("findings read again"), - ) as reread, - patch.object( - OperationService, "list_findings_async", autospec=True, side_effect=AssertionError("paged findings read") - ) as findings_page, - patch.object( - OperationService, - "list_finding_evidence_async", - autospec=True, - side_effect=AssertionError("paged evidence read"), - ) as evidence_page, - ): - report = await _report_async(operation_id=operation.id, finding_ids=selected) - - tree.assert_awaited_once() - assert tree.await_args is not None and tree.await_args.kwargs["finding_ids"] == selected - with_evidence.assert_awaited_once() - # Evidence is attached to the findings of that one read, in the dashboard's order, without reading them again. - included = await subtree_read(OperationService(), operation_id=operation.id, finding_ids=selected) - assert with_evidence.await_args is not None and with_evidence.await_args.kwargs["findings"] == included - assert [finding.id for finding in included] == selected[::-1] - reread.assert_not_called() - findings_page.assert_not_called() - evidence_page.assert_not_called() - assert [finding.title for finding in report.findings] == ["Critical finding", "Low finding"] - - async def test_report_includes_every_evidence_link_of_a_finding(sqlite_instance: SQLiteMemory) -> None: operation = await sqlite_instance.add_operation_async(Operation(name="Evidence links")) finding = await _add_finding_async(memory=sqlite_instance, operation=operation, title="Many references") @@ -674,6 +630,7 @@ async def test_report_includes_every_evidence_link_of_a_finding(sqlite_instance: summary=(FindingReportField(label="Outcome", value="Undetermined"), NOT_SCORED), details=(NOT_IN_AN_OPERATION,), link_url=_dashboard_link(evidence=item, conversation_id=f"conversation-{index:03d}"), + available=True, ) for index, item in enumerate(evidence) } @@ -737,9 +694,11 @@ def make_score(*, conversation_id: str, scorer: str, value: str) -> Score: FindingReportField(label="From operation", value="Source operation"), ), link_url=_dashboard_link(evidence=evidence, conversation_id=ENCODED_CONVERSATION_ID), + available=True, ), ), number="1", + finding_id=finding.id, ), ) @@ -775,6 +734,7 @@ async def test_report_retains_undetermined_score(sqlite_instance: SQLiteMemory) ), details=(FindingReportField(label="Rationale", value="The scorer could not decide."), NOT_IN_AN_OPERATION), link_url=_dashboard_link(evidence=evidence, conversation_id="main"), + available=True, ), ) @@ -794,12 +754,13 @@ async def test_report_retains_unavailable_evidence(sqlite_instance: SQLiteMemory assert len(exported.evidence) == 2 # Without an objective, the saved attack ID leads the entry, as on the dashboard. assert set(exported.evidence) == { - FindingReportEvidence(title=str(missing_attack_id), summary=(), details=(), link_url=None), + FindingReportEvidence(title=str(missing_attack_id), summary=(), details=(), link_url=None, available=False), FindingReportEvidence( title="Messageless objective", summary=(FindingReportField(label="Outcome", value="Undetermined"), NOT_SCORED), details=(NOT_IN_AN_OPERATION,), link_url=None, + available=False, ), } @@ -833,6 +794,7 @@ async def test_report_projects_optional_and_custom_fields(sqlite_instance: SQLit fields=(FindingReportField(label="Description", value="Only text"),), evidence=(), number="1", + finding_id=plain.id, ), FindingReportEntry( title="Custom finding", @@ -844,9 +806,11 @@ async def test_report_projects_optional_and_custom_fields(sqlite_instance: SQLit summary=(FindingReportField(label="Outcome", value="Undetermined"), NOT_SCORED), details=(NOT_IN_AN_OPERATION,), link_url=_dashboard_link(evidence=evidence, conversation_id="main"), + available=True, ), ), number="2", + finding_id=custom.id, ), ) @@ -865,28 +829,10 @@ async def test_report_labels_findings_with_the_active_fields(sqlite_instance: SQ report = await _report_async(operation_id=operation.id, finding_ids=[finding.id]) - assert report.findings == (replace(finding_report_entry(finding=finding, fields=CONTOSO_FIELDS), number="1"),) - - -@pytest.mark.parametrize( - ("score_value", "scorer", "expected"), - [ - ("true", "SubStringScorer", "True (SubStringScorer)"), - ("false", "ManualScorer", "False (human review)"), - ("0.75", "SelfAskLikertScorer", "0.75 (SelfAskLikertScorer)"), - ], -) -def test_score_text_capitalizes_booleans_and_names_human_review(score_value: str, scorer: str, expected: str) -> None: - score = Score( - score_value=score_value, - score_type="float_scale" if score_value == "0.75" else "true_false", - score_rationale="Synthetic rationale", - scorer_class_identifier=ComponentIdentifier(class_name=scorer, class_module="pyrit.score"), - message_piece_id=uuid4(), + assert report.findings == ( + replace(finding_report_entry(finding=finding, fields=CONTOSO_FIELDS), number="1", finding_id=finding.id), ) - assert finding_export._score_text(ScoreView.from_domain(score)) == expected - LINK = "https://pyrit.example.test/attack/chat/a/conversations/b?findingEvidenceId=c" TABLE_REPORT = FindingReport( @@ -908,14 +854,16 @@ def test_score_text_capitalizes_booleans_and_names_human_review(score_value: str ), details=(FindingReportField(label="Rationale", value="Synthetic rationale"),), link_url=LINK, + available=True, ), FindingReportEvidence( title="Unscored objective", summary=(FindingReportField(label="Outcome", value="Failure"), NOT_SCORED), details=(FindingReportField(label="From operation", value="Synthetic source"),), link_url=LINK, + available=True, ), - FindingReportEvidence(title="attack-404", summary=(), details=(), link_url=None), + FindingReportEvidence(title="attack-404", summary=(), details=(), link_url=None, available=False), ), ), FindingReportEntry( @@ -982,6 +930,7 @@ def test_docx_keeps_arbitrary_projected_fields() -> None: summary=(FindingReportField(label="Synthetic evidence field", value="evidence value"),), details=(FindingReportField(label="Synthetic evidence notes", value="note one\nnote two"),), link_url=None, + available=False, ) report = FindingReport( operation_name="Synthetic evaluation", @@ -1026,21 +975,14 @@ def test_conversation_links_match_the_dashboard_route_contract() -> None: cases = json.loads(ROUTE_CASES.read_text(encoding="utf-8")) links = [ - finding_export._conversation_link( - dashboard_origin=origin, - item=FindingEvidenceItem( - item=FindingEvidence( - id=UUID(case["findingEvidenceId"]), - finding_id=uuid4(), - attack_result_id=UUID(case["attackResultId"]), - ), - availability=EvidenceAvailability.AVAILABLE, - scenario_result_id=UUID(case["scenarioResultId"]) if case["scenarioResultId"] else None, - objective="Linked objective", - outcome=AttackOutcome.SUCCESS, + finding_export.conversation_link( + FindingEvidenceLinkTarget( + evidence_id=UUID(case["findingEvidenceId"]), + attack_result_id=UUID(case["attackResultId"]), conversation_id=case["conversationId"], + scenario_result_id=UUID(case["scenarioResultId"]) if case["scenarioResultId"] else None, ), - conversation_id=case["conversationId"], + dashboard_origin=origin, ) for case in cases ] @@ -1254,7 +1196,7 @@ async def test_export_counts_sub_findings_toward_the_limit( assert within.status_code == 200 assert beyond.status_code == 422 - assert "counting sub-findings" in beyond.json()["detail"] + assert beyond.json()["detail"] == "Select at most 4 findings to download at once, counting sub-findings." assert "content-disposition" not in beyond.headers diff --git a/tests/unit/backend/test_finding_publish.py b/tests/unit/backend/test_finding_publish.py new file mode 100644 index 0000000000..230859170d --- /dev/null +++ b/tests/unit/backend/test_finding_publish.py @@ -0,0 +1,822 @@ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT license. + +import json +import logging +import os +import re +from collections.abc import Generator, Iterator +from contextlib import contextmanager +from dataclasses import dataclass +from pathlib import Path +from unittest.mock import MagicMock, patch +from uuid import UUID, uuid4 + +import httpx +import pytest +from fastapi import FastAPI, Request +from fastapi.testclient import TestClient +from pydantic import AnyHttpUrl + +from pyrit.backend.authentication_policy import resolve_authentication_policy +from pyrit.backend.main import app +from pyrit.backend.middleware.auth import AuthenticatedUser, EntraAuthMiddleware +from pyrit.backend.middleware.compatibility import CompatibilityAPI +from pyrit.backend.models.finding_publishers import FindingPublishPreviewRequest, FindingPublishRequest +from pyrit.backend.routes import operations as operation_routes +from pyrit.backend.routes.common import finding_publish_requester_from_request +from pyrit.backend.services import finding_publish +from pyrit.backend.services.configuration_file_service import ConfigurationFileService +from pyrit.backend.services.runtime_lifecycle import RuntimeLifecycle +from pyrit.memory import SQLiteMemory +from pyrit.models import ( + AttackResult, + ComponentIdentifier, + Finding, + FindingEvidence, + FindingFields, + FindingPublishDestination, + FindingPublishedItem, + FindingPublisherInfo, + FindingPublishFailure, + FindingPublishPreview, + FindingPublishPreviewItem, + FindingPublishProblem, + FindingPublishReference, + FindingPublishRequester, + FindingPublishResult, + FindingPublishSkip, + Message, + MessagePiece, + Operation, +) +from pyrit.output import ( + FindingPublishCreateError, + FindingPublishDeadlineError, + FindingPublishDestinationError, + FindingPublisher, + FindingPublisherConfigurationError, + FindingPublishError, + FindingPublisherUnavailableError, + FindingPublishPlan, + FindingPublishPlanItem, +) +from pyrit.registry import FindingPublisherRegistry +from pyrit.setup import ConfigurationLoader + +pytestmark = pytest.mark.usefixtures("patch_central_database") + +REPO_ROOT = Path(__file__).resolve().parents[3] +# The dialog's tests render these, so the frontend's types follow the API's. +CONTRACT = REPO_ROOT / "frontend" / "src" / "components" / "Operations" / "findingPublish.contract.json" +FRONT_DOOR_BICEP = REPO_ROOT / "infra" / "modules" / "aca_front_door.bicep" +PUBLIC_ORIGIN = "https://copyrit.example.test" +ORIGIN = AnyHttpUrl(PUBLIC_ORIGIN) +CLOCK = "pyrit.backend.services.finding_publish.monotonic" +PUBLISHER_CLOCK = "pyrit.output.finding_publisher.base.monotonic" +DESTINATION = FindingPublishDestination( + id="12345", title="Operation Contoso", url="https://tracker.example.test/12345", location="Example / Red Team" +) +MISSING_ID = UUID(int=404) +_UNSET = object() +SIGN_IN_ENVIRONMENT = { + "PYRIT_AUTH_MODE": "entra", + "ENTRA_CLIENT_ID": "test-client", + "ENTRA_TENANT_ID": "test-tenant", + "ENTRA_ALLOWED_GROUP_IDS": "test-group", + "ENTRA_ADMIN_GROUP_ID": "test-admin-group", +} + + +class _FakePublisher(FindingPublisher): + """Publishes to memory, and fails the ways a configured test asks.""" + + def __init__( + self, + *, + label: str = "Parent item", + open_error: Exception | None = None, + configuration_error: Exception | None = None, + create_errors: dict[str, Exception] | None = None, + plan_problems: dict[str, str] | None = None, + ) -> None: + self._label = label + self._open_error = open_error + self._configuration_error = configuration_error + self._create_errors = create_errors or {} + self._plan_problems = plan_problems or {} + self.created: list[str] = [] + self.links: list[str | None] = [] + self.deadlines: list[float | None] = [] + self.requesters: list[FindingPublishRequester | None] = [] + + @property + def info(self) -> FindingPublisherInfo: + return FindingPublisherInfo(destination_label=self._label, destination_hint="Paste the parent's ID.") + + def check_fields(self, *, fields: FindingFields) -> None: + if self._configuration_error is not None: + raise self._configuration_error + + def _build_identifier(self) -> ComponentIdentifier: + return ComponentIdentifier.of(self, params={"label": self._label}) + + def _check_plan(self, *, plan: FindingPublishPlan, fields: FindingFields) -> list[FindingPublishProblem]: + return [ + FindingPublishProblem(finding_id=item.finding.id, title=item.finding.title, message=message) + for item in plan.items + if (message := self._plan_problems.get(item.finding.title)) + ] + + async def _open_destination_async( + self, *, destination: str, deadline: float | None + ) -> tuple[FindingPublishDestination, object]: + self.deadlines.append(deadline) + if self._open_error is not None: + raise self._open_error + return DESTINATION, None + + async def _create_item_async( + self, + *, + item: FindingPublishPlanItem, + parent_external_id: str, + context: object, + run_id: str, + requested_by: FindingPublishRequester | None, + deadline: float | None, + ) -> FindingPublishedItem: + self.requesters.append(requested_by) + self.links.extend(evidence.link_url for evidence in item.entry.evidence) + error = self._create_errors.get(item.finding.title) + if error is not None: + raise error + self.created.append(item.finding.title) + external_id = str(100 + len(self.created)) + return FindingPublishedItem( + finding_id=item.finding.id, + title=item.finding.title, + external_id=external_id, + url=f"https://tracker.example.test/{external_id}", + parent_external_id=parent_external_id, + ) + + +@dataclass(frozen=True) +class _Seeded: + operation: Operation + parent: Finding + child: Finding + draft: Finding + evidence: FindingEvidence + + +@pytest.fixture +def registry() -> Iterator[FindingPublisherRegistry]: + FindingPublisherRegistry.reset_registry_singleton() + yield FindingPublisherRegistry.get_registry_singleton() + FindingPublisherRegistry.reset_registry_singleton() + + +@pytest.fixture +def public_origin() -> Iterator[None]: + # The runtime reads PYRIT_PUBLIC_ORIGIN into the app's state when it applies its configuration. + with patch.object(app.state, "public_origin", ORIGIN, create=True): + yield + + +@pytest.fixture +async def seeded_async(sqlite_instance: SQLiteMemory) -> _Seeded: + operation = await sqlite_instance.add_operation_async(Operation(name="Contoso")) + parent = await _add_finding_async(memory=sqlite_instance, operation=operation, title="Leaks the system prompt") + child = await _add_finding_async( + memory=sqlite_instance, operation=operation, title="Decodes Base64", parent_finding_id=parent.id + ) + draft = await _add_finding_async(memory=sqlite_instance, operation=operation, title="Role-play", demonstrated=False) + attack = AttackResult(conversation_id="conversation-1", objective="Leak the prompt", operation_id=operation.id) + await sqlite_instance.add_attack_results_to_memory_async(attack_results=[attack]) + await sqlite_instance.add_message_to_memory_async( + request=Message( + message_pieces=[MessagePiece(role="user", original_value="Hello", conversation_id="conversation-1")] + ) + ) + evidence = await sqlite_instance.add_finding_evidence_async( + evidence=FindingEvidence(finding_id=parent.id, attack_result_id=UUID(str(attack.attack_result_id))) + ) + return _Seeded(operation=operation, parent=parent, child=child, draft=draft, evidence=evidence) + + +async def _add_finding_async(*, memory: SQLiteMemory, operation: Operation, title: str, **fields: object) -> Finding: + return await memory.add_finding_async( + finding=Finding(operation_id=operation.id, title=title, severity="moderate", **fields) # type: ignore[arg-type] + ) + + +@contextmanager +def _without_public_origin() -> Generator[None, None, None]: + saved = getattr(app.state, "public_origin", _UNSET) + if saved is not _UNSET: + del app.state.public_origin + try: + yield + finally: + if saved is not _UNSET: + app.state.public_origin = saved + + +def _register(registry: FindingPublisherRegistry, publisher: _FakePublisher, *, name: str = "fake") -> None: + registry.instances.register(publisher, name=name) + + +def _post(path: str, body: dict[str, object], headers: dict[str, str]): + return TestClient(app, raise_server_exceptions=False).post(path, json=body, headers=headers) + + +def _check(*, seeded: _Seeded, headers: dict[str, str], **overrides: object): + body: dict[str, object] = { + "finding_ids": [str(seeded.parent.id), str(seeded.draft.id)], + "publisher_name": "fake", + "destination": "12345", + } + body.update(overrides) + return _post(f"/api/operations/{seeded.operation.id}/findings/publish/preview", body, headers) + + +def _publish(*, seeded: _Seeded, headers: dict[str, str], plan_digest: str | None = None, **overrides: object): + if plan_digest is None: + preview = _check(seeded=seeded, headers=headers, **overrides) + assert preview.status_code == 200, preview.text + plan_digest = preview.json()["plan_digest"] + body: dict[str, object] = { + "finding_ids": [str(seeded.parent.id), str(seeded.draft.id)], + "publisher_name": "fake", + "destination": "12345", + "plan_digest": plan_digest, + } + body.update(overrides) + return _post(f"/api/operations/{seeded.operation.id}/findings/publish", body, headers) + + +def test_list_finding_publishers_is_empty_without_a_publisher( + registry: FindingPublisherRegistry, compatibility_headers: dict[str, str] +) -> None: + response = TestClient(app).get("/api/finding-publishers", headers=compatibility_headers) + + assert response.status_code == 200 + assert response.json() == {"items": []} + + +def test_list_finding_publishers_names_each_with_its_info_sorted_by_name( + registry: FindingPublisherRegistry, compatibility_headers: dict[str, str] +) -> None: + _register(registry, _FakePublisher(label="Work item"), name="zeta") + _register(registry, _FakePublisher(label="Folder"), name="alpha") + + response = TestClient(app).get("/api/finding-publishers", headers=compatibility_headers) + + assert response.json() == { + "items": [ + {"name": "alpha", "info": {"destination_label": "Folder", "destination_hint": "Paste the parent's ID."}}, + {"name": "zeta", "info": {"destination_label": "Work item", "destination_hint": "Paste the parent's ID."}}, + ] + } + + +@pytest.mark.usefixtures("public_origin") +async def test_check_shows_the_plan_without_creating_anything( + registry: FindingPublisherRegistry, compatibility_headers: dict[str, str], seeded_async: _Seeded +) -> None: + publisher = _FakePublisher() + _register(registry, publisher) + + response = _check(seeded=seeded_async, headers=compatibility_headers) + + assert response.status_code == 200, response.text + preview = FindingPublishPreview.model_validate(response.json()) + assert preview.destination == DESTINATION + assert [(item.title, item.parent_finding_id) for item in preview.planned] == [ + ("Leaks the system prompt", None), + ("Decodes Base64", seeded_async.parent.id), + ] + assert [(skip.title, skip.reason) for skip in preview.skipped] == [("Role-play", "Not demonstrated")] + assert preview.problems == () + assert re.fullmatch(r"[0-9a-f]{64}", preview.plan_digest) + assert publisher.created == [] + + +@pytest.mark.usefixtures("public_origin") +async def test_check_returns_problems_with_the_plan( + registry: FindingPublisherRegistry, compatibility_headers: dict[str, str], seeded_async: _Seeded +) -> None: + _register(registry, _FakePublisher(plan_problems={"Decodes Base64": "The title is too long."})) + + response = _check(seeded=seeded_async, headers=compatibility_headers) + + assert response.status_code == 200 + assert response.json()["problems"] == [ + {"finding_id": str(seeded_async.child.id), "title": "Decodes Base64", "message": "The title is too long."} + ] + + +@pytest.mark.usefixtures("public_origin") +async def test_publish_creates_the_checked_plan_with_public_evidence_links( + registry: FindingPublisherRegistry, compatibility_headers: dict[str, str], seeded_async: _Seeded +) -> None: + publisher = _FakePublisher() + _register(registry, publisher) + + response = _publish(seeded=seeded_async, headers=compatibility_headers) + + assert response.status_code == 200, response.text + result = FindingPublishResult.model_validate(response.json()) + assert [(item.title, item.parent_external_id) for item in result.created] == [ + ("Leaks the system prompt", "12345"), + ("Decodes Base64", "101"), + ] + assert [skip.title for skip in result.skipped] == ["Role-play"] + path = f"/attack/chat/{seeded_async.evidence.attack_result_id}/conversations/conversation-1" + assert publisher.links == [f"{PUBLIC_ORIGIN}{path}?findingEvidenceId={seeded_async.evidence.id}"] + # Sign-in is off in these tests, so the publish is for no one in particular. + assert publisher.requesters == [None, None] + + +@pytest.mark.usefixtures("public_origin") +async def test_publish_reports_a_failure_as_a_result( + registry: FindingPublisherRegistry, compatibility_headers: dict[str, str], seeded_async: _Seeded +) -> None: + error = FindingPublishCreateError("The service didn't answer.", outcome_unknown=True) + _register(registry, _FakePublisher(create_errors={"Leaks the system prompt": error})) + + response = _publish(seeded=seeded_async, headers=compatibility_headers) + + assert response.status_code == 200 + result = FindingPublishResult.model_validate(response.json()) + assert result.created == () + assert result.failure == FindingPublishFailure( + finding_id=seeded_async.parent.id, + title="Leaks the system prompt", + message="The service didn't answer.", + outcome_unknown=True, + ) + assert result.not_attempted == (FindingPublishReference(finding_id=seeded_async.child.id, title="Decodes Base64"),) + + +@pytest.fixture +def signed_in_app(compatibility_id: str) -> Iterator[CompatibilityAPI]: + """The backend's routes and middleware with Entra sign-in on; only the Microsoft Graph call is mocked.""" + with patch.dict(os.environ, SIGN_IN_ENVIRONMENT): + signed_in = CompatibilityAPI( + routes=list(app.router.routes), middleware=app.user_middleware, exception_handlers=app.exception_handlers + ) + signed_in.state.compatibility_id = compatibility_id + signed_in.state.authentication_policy = resolve_authentication_policy() + signed_in.state.public_origin = ORIGIN + yield signed_in + + +async def test_publish_is_for_the_signed_in_user( + registry: FindingPublisherRegistry, + seeded_async: _Seeded, + signed_in_app: CompatibilityAPI, + compatibility_headers: dict[str, str], +) -> None: + publisher = _FakePublisher() + _register(registry, publisher) + user = AuthenticatedUser(oid="user-oid", name="Ada Lovelace", email="ada@example.test", groups=["test-group"]) + path = f"/api/operations/{seeded_async.operation.id}/findings/publish" + body = {"finding_ids": [str(seeded_async.child.id)], "publisher_name": "fake", "destination": "12345"} + + with patch.object(EntraAuthMiddleware, "_authenticate_with_graph_async", return_value=user): + async with httpx.AsyncClient( + transport=httpx.ASGITransport(app=signed_in_app, raise_app_exceptions=False), + base_url="http://test", + headers={**compatibility_headers, "Authorization": "Bearer test-only-token"}, + ) as client: + preview = await client.post(f"{path}/preview", json=body) + response = await client.post(path, json={**body, "plan_digest": preview.json()["plan_digest"]}) + + assert response.status_code == 200, response.text + assert publisher.requesters == [FindingPublishRequester(name="Ada Lovelace", email="ada@example.test")] + + +@pytest.mark.parametrize( + ("name", "email", "expected"), + [ + ("Ada Lovelace", "ada@example.test", FindingPublishRequester(name="Ada Lovelace", email="ada@example.test")), + ("", "ada@example.test", FindingPublishRequester(name=None, email="ada@example.test")), + ("Ada Lovelace", "", FindingPublishRequester(name="Ada Lovelace", email=None)), + ], +) +def test_requester_is_the_signed_in_user(name: str, email: str, expected: FindingPublishRequester) -> None: + request = Request({"type": "http"}) + request.state.user = AuthenticatedUser(oid="user-oid", name=name, email=email, groups=[]) + + assert finding_publish_requester_from_request(request) == expected + + +def test_requester_is_none_when_sign_in_is_off() -> None: + assert finding_publish_requester_from_request(Request({"type": "http"})) is None + + +@pytest.mark.usefixtures("public_origin") +@pytest.mark.parametrize("endpoint", ["preview", "publish"]) +@pytest.mark.parametrize( + ("case", "status_code", "problem_type", "detail"), + [ + ("unknown_publisher", 404, "/errors/not-found", "Finding publisher 'missing' not found."), + ("missing_operation", 404, "/errors/not-found", None), + ("missing_finding", 404, "/errors/not-found", None), + ( + "destination", + 400, + "/errors/publish-destination", + "Work item 12345 doesn't exist, or the publishing identity can't see it.", + ), + ( + "unavailable", + 502, + "/errors/publisher-unavailable", + "Azure DevOps rejected the publishing identity's credentials.", + ), + ( + "configuration", + 500, + "/errors/publisher-misconfigured", + "The finding publisher is misconfigured. Ask an administrator to check the server log.", + ), + ("deadline", 503, "/errors/publish-deadline", "Ran out of time before creating anything. Try again."), + ( + "unexpected", + 500, + "/errors/internal-error", + "The finding publisher failed unexpectedly. Ask an administrator to check the server log.", + ), + ], +) +async def test_errors_map_to_their_status( + registry: FindingPublisherRegistry, + compatibility_headers: dict[str, str], + seeded_async: _Seeded, + endpoint: str, + case: str, + status_code: int, + problem_type: str, + detail: str | None, +) -> None: + publisher = _FakePublisher( + open_error={ + "destination": FindingPublishDestinationError( + "Work item 12345 doesn't exist, or the publishing identity can't see it." + ), + "unavailable": FindingPublisherUnavailableError( + "Azure DevOps rejected the publishing identity's credentials." + ), + "deadline": FindingPublishDeadlineError("The time limit passed."), + "unexpected": FindingPublishError("A publisher error the routes don't map."), + }.get(case), + configuration_error=FindingPublisherConfigurationError("Map 'severity'.") if case == "configuration" else None, + ) + # A working publisher with the same identity checks first, so a publish gets past the plan digest. + _register(registry, _FakePublisher()) + preview = await finding_publish.preview_finding_publish_async( + operation_id=seeded_async.operation.id, + request=FindingPublishPreviewRequest( + finding_ids=[seeded_async.parent.id], publisher_name="fake", destination="12345" + ), + public_origin=ORIGIN, + ) + registry.instances.register(publisher, name="fake", replace=True) + body: dict[str, object] = { + "finding_ids": [str(seeded_async.parent.id)], + "publisher_name": "missing" if case == "unknown_publisher" else "fake", + "destination": "12345", + } + if case == "missing_finding": + body["finding_ids"] = [str(seeded_async.parent.id), str(MISSING_ID)] + operation_id = MISSING_ID if case == "missing_operation" else seeded_async.operation.id + path = f"/api/operations/{operation_id}/findings/publish" + if endpoint == "preview": + path += "/preview" + else: + body["plan_digest"] = preview.plan_digest + + response = _post(path, body, compatibility_headers) + + assert response.status_code == status_code, response.text + # The dialog decides from the type whether anything might have been created. + assert response.json()["type"] == problem_type + if detail is not None: + assert response.json()["detail"] == detail + assert publisher.created == [] + + +@pytest.mark.usefixtures("public_origin") +@pytest.mark.parametrize( + "error", + [ + FindingPublisherUnavailableError( + "Azure DevOps rejected Ada Lovelace's request.", diagnostics={"status": "401", "code": "TF400813"} + ), + FindingPublishDestinationError( + "Work item 12345 is of type Task.", diagnostics={"status": "200", "type": "Task"} + ), + ], +) +async def test_errors_opening_the_destination_log_their_diagnostics_only( + registry: FindingPublisherRegistry, + compatibility_headers: dict[str, str], + seeded_async: _Seeded, + caplog: pytest.LogCaptureFixture, + error: FindingPublishError, +) -> None: + _register(registry, _FakePublisher(open_error=error)) + + with caplog.at_level(logging.WARNING, logger=operation_routes.__name__): + _check(seeded=seeded_async, headers=compatibility_headers) + + diagnostics = ", ".join(f"{key} {value}" for key, value in error.diagnostics.items()) + path = f"/api/operations/{seeded_async.operation.id}/findings/publish/preview" + expected = f"Finding publish on {path} stopped before creating anything: {type(error).__name__} " + assert [record.getMessage() for record in caplog.records if record.name == operation_routes.__name__] == [ + f"{expected}(diagnostics: {diagnostics})." + ] + + +@pytest.mark.usefixtures("public_origin") +async def test_publish_with_problems_lists_each_problem( + registry: FindingPublisherRegistry, compatibility_headers: dict[str, str], seeded_async: _Seeded +) -> None: + publisher = _FakePublisher(plan_problems={"Decodes Base64": "The title is too long."}) + _register(registry, publisher) + + response = _publish(seeded=seeded_async, headers=compatibility_headers) + + assert response.status_code == 422 + problem = response.json() + assert problem["type"] == "/errors/publish-problems" + assert problem["detail"] == "Fix these problems, then check again" + assert problem["errors"] == [{"field": "Decodes Base64", "message": "The title is too long."}] + assert publisher.created == [] + + +@pytest.mark.usefixtures("public_origin") +async def test_publish_refuses_a_plan_that_changed_since_check( + registry: FindingPublisherRegistry, + compatibility_headers: dict[str, str], + seeded_async: _Seeded, + sqlite_instance: SQLiteMemory, +) -> None: + publisher = _FakePublisher() + _register(registry, publisher) + preview = _check(seeded=seeded_async, headers=compatibility_headers) + await _add_finding_async( + memory=sqlite_instance, + operation=seeded_async.operation, + title="Added after Check", + parent_finding_id=seeded_async.parent.id, + ) + + response = _publish(seeded=seeded_async, headers=compatibility_headers, plan_digest=preview.json()["plan_digest"]) + + assert response.status_code == 409 + assert response.json()["type"] == "/errors/publish-plan-changed" + assert response.json()["detail"] == "The findings changed since Check; check again." + assert publisher.created == [] + + +@pytest.mark.parametrize("plan_digest", ["", "0" * 63, "0" * 65, "A" * 64, "g" * 64]) +def test_publish_rejects_a_malformed_plan_digest( + registry: FindingPublisherRegistry, compatibility_headers: dict[str, str], plan_digest: str +) -> None: + body = {"finding_ids": [str(uuid4())], "publisher_name": "fake", "destination": "1", "plan_digest": plan_digest} + + response = _post(f"/api/operations/{uuid4()}/findings/publish", body, compatibility_headers) + + assert response.status_code == 422 + assert response.json()["type"] == "/errors/validation-error" + + +@pytest.mark.usefixtures("public_origin") +@pytest.mark.parametrize("endpoint", ["preview", "publish"]) +@pytest.mark.parametrize(("sub_findings", "status_code"), [(99, 200), (100, 422)]) +async def test_one_request_takes_at_most_100_findings_counting_sub_findings( + registry: FindingPublisherRegistry, + compatibility_headers: dict[str, str], + sqlite_instance: SQLiteMemory, + endpoint: str, + sub_findings: int, + status_code: int, +) -> None: + publisher = _FakePublisher() + _register(registry, publisher) + operation = await sqlite_instance.add_operation_async(Operation(name="Large")) + parent = await _add_finding_async(memory=sqlite_instance, operation=operation, title="Parent") + for index in range(sub_findings): + await _add_finding_async( + memory=sqlite_instance, operation=operation, title=f"Step {index}", parent_finding_id=parent.id + ) + body: dict[str, object] = {"finding_ids": [str(parent.id)], "publisher_name": "fake", "destination": "12345"} + path = f"/api/operations/{operation.id}/findings/publish/preview" + if endpoint == "publish": + preview = _post(path, body, compatibility_headers) + body["plan_digest"] = preview.json().get("plan_digest", "0" * 64) + path = path.removesuffix("/preview") + + response = _post(path, body, compatibility_headers) + + assert response.status_code == status_code, response.text + if status_code == 422: + assert response.json()["type"] == "/errors/publish-too-many" + assert response.json()["detail"] == "Publish at most 100 findings at a time, counting sub-findings." + assert publisher.created == [] + + +@pytest.mark.parametrize("endpoint", ["preview", "publish"]) +@pytest.mark.parametrize("configured", [False, True]) +async def test_publishing_needs_a_public_origin( + registry: FindingPublisherRegistry, + compatibility_headers: dict[str, str], + seeded_async: _Seeded, + endpoint: str, + configured: bool, +) -> None: + publisher = _FakePublisher() + _register(registry, publisher) + # None is what the runtime stores for a missing or invalid value; before startup there is no value at all. + state = patch.object(app.state, "public_origin", None, create=True) if configured else _without_public_origin() + with state: + if endpoint == "preview": + response = _check(seeded=seeded_async, headers=compatibility_headers) + else: + response = _publish(seeded=seeded_async, headers=compatibility_headers, plan_digest="0" * 64) + + assert response.status_code == 503 + assert response.json()["type"] == "/errors/public-origin" + assert response.json()["detail"] == ( + "Publishing needs the deployment's public address. Ask an administrator to set PYRIT_PUBLIC_ORIGIN." + ) + assert publisher.deadlines == [] + + +@pytest.mark.parametrize("value", [PUBLIC_ORIGIN, f"{PUBLIC_ORIGIN}/", f" {PUBLIC_ORIGIN} "]) +def test_read_public_origin_accepts_an_origin_with_or_without_trailing_slash( + value: str, caplog: pytest.LogCaptureFixture +) -> None: + with patch.dict(os.environ, {"PYRIT_PUBLIC_ORIGIN": value}), caplog.at_level(logging.WARNING): + origin = finding_publish.read_public_origin() + + assert origin is not None + assert str(origin).rstrip("/") == PUBLIC_ORIGIN + assert caplog.records == [] + + +@pytest.mark.parametrize("value", [None, "", " "]) +def test_read_public_origin_is_none_when_unset(value: str | None, caplog: pytest.LogCaptureFixture) -> None: + with patch.dict(os.environ, {"PYRIT_PUBLIC_ORIGIN": value or ""}), caplog.at_level(logging.WARNING): + if value is None: + del os.environ["PYRIT_PUBLIC_ORIGIN"] + origin = finding_publish.read_public_origin() + + assert origin is None + assert caplog.records == [] + + +@pytest.mark.parametrize( + "value", ["copyrit.example.test", "ftp://copyrit.example.test", "https://copyrit.example.test/app"] +) +def test_read_public_origin_warns_about_a_value_that_is_not_an_origin( + value: str, caplog: pytest.LogCaptureFixture +) -> None: + with patch.dict(os.environ, {"PYRIT_PUBLIC_ORIGIN": value}), caplog.at_level(logging.WARNING): + origin = finding_publish.read_public_origin() + + assert origin is None + expected = "PYRIT_PUBLIC_ORIGIN is not an origin, such as https://pyrit.example.com, so publishing findings is " + assert [record.getMessage() for record in caplog.records] == [f"{expected}unavailable."] + + +def test_runtime_publishes_the_public_origin_when_it_applies_its_configuration(tmp_path: Path) -> None: + lifecycle = RuntimeLifecycle( + app=FastAPI(), source=ConfigurationFileService(config_file_value=str(tmp_path / "config.yaml")) + ) + config = MagicMock(spec=ConfigurationLoader, initializer_configs=[], operator=None, operation=None) + + with patch.dict(os.environ, {"PYRIT_PUBLIC_ORIGIN": PUBLIC_ORIGIN}): + lifecycle._publish(config) + + assert lifecycle.app.state.public_origin == ORIGIN + + +@pytest.mark.usefixtures("public_origin") +async def test_publish_links_evidence_to_the_runtime_public_origin( + registry: FindingPublisherRegistry, compatibility_headers: dict[str, str], seeded_async: _Seeded +) -> None: + publisher = _FakePublisher() + _register(registry, publisher) + + # The environment is read only when the runtime applies its configuration, never per request. + with patch.dict(os.environ, {"PYRIT_PUBLIC_ORIGIN": "https://elsewhere.example.test"}): + response = _publish(seeded=seeded_async, headers=compatibility_headers) + + assert response.status_code == 200, response.text + assert publisher.links[0] is not None + assert publisher.links[0].startswith(f"{PUBLIC_ORIGIN}/attack/chat/") + + +@pytest.mark.usefixtures("public_origin") +@pytest.mark.parametrize("endpoint", ["preview", "publish"]) +async def test_each_request_gets_one_deadline_from_admission( + registry: FindingPublisherRegistry, seeded_async: _Seeded, endpoint: str +) -> None: + publisher = _FakePublisher() + _register(registry, publisher) + preview_request = FindingPublishPreviewRequest( + finding_ids=[seeded_async.parent.id], publisher_name="fake", destination="12345" + ) + operation_id = seeded_async.operation.id + preview = await finding_publish.preview_finding_publish_async( + operation_id=operation_id, request=preview_request, public_origin=ORIGIN + ) + publisher.deadlines.clear() + + # The publisher compares the deadline with the same clock. + with patch(CLOCK, return_value=1_000.0), patch(PUBLISHER_CLOCK, return_value=1_000.0): + if endpoint == "preview": + await finding_publish.preview_finding_publish_async( + operation_id=operation_id, request=preview_request, public_origin=ORIGIN + ) + else: + await finding_publish.publish_findings_async( + operation_id=operation_id, + request=FindingPublishRequest(**preview_request.model_dump(), plan_digest=preview.plan_digest), + requested_by=None, + public_origin=ORIGIN, + ) + + assert publisher.deadlines == [1_000.0 + finding_publish.PUBLISH_BUDGET_SECONDS] + + +def test_publish_budget_leaves_30_seconds_of_front_door_timeout() -> None: + match = re.search(r"originResponseTimeoutSeconds:\s*(\d+)", FRONT_DOOR_BICEP.read_text(encoding="utf-8")) + assert match is not None + + front_door_timeout = int(match[1]) + + assert front_door_timeout - finding_publish.PUBLISH_BUDGET_SECONDS >= 30 + + +def test_contract_fixture_matches_the_api_types() -> None: + parent_id, child_id, orphan_id, skipped_id = (UUID(int=value) for value in range(1, 5)) + preview = FindingPublishPreview( + destination=DESTINATION, + planned=( + FindingPublishPreviewItem(finding_id=parent_id, title="Leaks the system prompt"), + FindingPublishPreviewItem(finding_id=child_id, title="Decodes Base64", parent_finding_id=parent_id), + FindingPublishPreviewItem(finding_id=orphan_id, title="Writes the payload", part_of="Earlier finding"), + ), + skipped=(FindingPublishSkip(finding_id=skipped_id, title="Role-play", reason="Not demonstrated"),), + problems=(), + plan_digest="a" * 64, + ) + result = FindingPublishResult( + run_id="0f" * 16, + destination=DESTINATION, + created=( + FindingPublishedItem( + finding_id=parent_id, + title="Leaks the system prompt", + external_id="101", + url="https://tracker.example.test/101", + parent_external_id="12345", + ), + ), + skipped=preview.skipped, + failure=FindingPublishFailure( + finding_id=child_id, title="Decodes Base64", message="The service didn't answer.", outcome_unknown=True + ), + not_attempted=(FindingPublishReference(finding_id=orphan_id, title="Writes the payload"),), + ) + + contract = json.loads(CONTRACT.read_text(encoding="utf-8")) + + assert contract["preview"] == preview.model_dump(mode="json") + assert contract["result"] == result.model_dump(mode="json") + + +def test_contract_fixture_classifies_every_problem_a_publish_can_return() -> None: + contract = json.loads(CONTRACT.read_text(encoding="utf-8"))["problem_types"] + check_again, nothing_created = set(contract["check_again"]), set(contract["nothing_created"]) + # Each problem the routes map, all raised before anything is created, and FastAPI's invalid-request problem. The + # app's catch-all types for unexpected errors stay unclassified, because such an error could follow a create. + classified = {entry[2] for entry in operation_routes._PUBLISH_PROBLEMS} | {"/errors/validation-error"} + + assert check_again.isdisjoint(nothing_created) + assert check_again | nothing_created == classified + assert {"/errors/internal-error", "/errors/bad-request"}.isdisjoint(classified) + # These need a different selection or a new Check; the rest can be published again once the cause is fixed. + assert check_again == { + "/errors/publish-plan-changed", + "/errors/publish-problems", + "/errors/publish-too-many", + "/errors/validation-error", + } diff --git a/tests/unit/backend/test_operations.py b/tests/unit/backend/test_operations.py index b5872eb46a..541422aa5c 100644 --- a/tests/unit/backend/test_operations.py +++ b/tests/unit/backend/test_operations.py @@ -15,7 +15,7 @@ from pyrit.backend.main import app from pyrit.backend.models.common import MAX_ITEMS from pyrit.backend.models.operations import EvidenceAvailability, FindingEvidenceCreateRequest -from pyrit.backend.services.operation_service import FindingNotFoundError, OperationNotFoundError, OperationService +from pyrit.backend.services.operation_service import FindingNotFoundError, OperationService from pyrit.memory import AttackResultEntry, CentralMemory, PromptMemoryEntry, SQLiteMemory from pyrit.memory.memory_models import Base from pyrit.models import ( @@ -1064,66 +1064,6 @@ async def test_evidence_page_batches_sources_and_counts_async( assert counts.call_args.kwargs["finding_ids"] == [finding.id] -@pytest.fixture -async def selected_findings_async(sqlite_instance: SQLiteMemory) -> tuple[Operation, list[Finding]]: - operation = await sqlite_instance.add_operation_async(Operation(name="Selected")) - findings = [] - for severity in ["low", "critical", "moderate"]: - finding = await sqlite_instance.add_finding_async( - finding=Finding(operation_id=operation.id, title=severity.title(), severity=severity) - ) - for index in range(2): - conversation_id = f"{severity}-{index}" - attack = AttackResult(conversation_id=conversation_id, objective=conversation_id, operation_id=operation.id) - await sqlite_instance.add_attack_results_to_memory_async(attack_results=[attack]) - await sqlite_instance.add_message_to_memory_async( - request=Message( - message_pieces=[ - MessagePiece(role="user", original_value=conversation_id, conversation_id=conversation_id) - ] - ) - ) - await sqlite_instance.add_finding_evidence_async( - evidence=FindingEvidence(finding_id=finding.id, attack_result_id=UUID(attack.attack_result_id)) - ) - findings.append(finding) - return operation, findings - - -async def test_findings_with_evidence_read_in_constant_queries_async( - sqlite_instance: SQLiteMemory, - selected_findings_async: tuple[Operation, list[Finding]], -) -> None: - operation, findings = selected_findings_async - service = OperationService() - with ( - patch.object( - sqlite_instance, "get_attack_results_async", wraps=sqlite_instance.get_attack_results_async - ) as owners, - patch.object( - sqlite_instance, "get_conversation_stats_async", wraps=sqlite_instance.get_conversation_stats_async - ) as stats, - patch.object( - sqlite_instance, "get_finding_evidence_async", wraps=sqlite_instance.get_finding_evidence_async - ) as evidence_pages, - patch.object(sqlite_instance, "get_findings_async", wraps=sqlite_instance.get_findings_async) as finding_pages, - ): - selected = await service.get_findings_with_evidence_async( - operation_id=operation.id, finding_ids=[finding.id for finding in findings] - ) - owners.assert_called_once() - stats.assert_called_once() - evidence_pages.assert_not_called() - finding_pages.assert_not_called() - assert [finding.title for finding, _ in selected] == ["Critical", "Moderate", "Low"] - for finding, items in selected: - page = await service.list_finding_evidence_async( - operation_id=operation.id, finding_id=finding.id, limit=10, offset=0 - ) - assert len(items) == 2 - assert items == page.items - - async def _store_shared_conversation_attacks_async( sqlite_instance: SQLiteMemory, ) -> tuple[Operation, list[AttackResult]]: @@ -1144,36 +1084,6 @@ async def _store_shared_conversation_attacks_async( return operation, attacks -async def test_findings_with_evidence_keep_an_older_attack_sharing_a_conversation_async( - sqlite_instance: SQLiteMemory, -) -> None: - operation, attacks = await _store_shared_conversation_attacks_async(sqlite_instance) - findings = [] - for attack in attacks: - finding = await sqlite_instance.add_finding_async( - finding=Finding(operation_id=operation.id, title=attack.objective, severity="low") - ) - await sqlite_instance.add_finding_evidence_async( - evidence=FindingEvidence(finding_id=finding.id, attack_result_id=UUID(attack.attack_result_id)) - ) - findings.append(finding) - service = OperationService() - - selected = await service.get_findings_with_evidence_async( - operation_id=operation.id, finding_ids=[finding.id for finding in findings] - ) - - assert {finding.title: [(item.objective, item.availability) for item in items] for finding, items in selected} == { - "First run": [("First run", EvidenceAvailability.AVAILABLE)], - "Second run": [("Second run", EvidenceAvailability.AVAILABLE)], - } - for finding, items in selected: - page = await service.list_finding_evidence_async( - operation_id=operation.id, finding_id=finding.id, limit=10, offset=0 - ) - assert items == page.items - - async def test_finding_evidence_page_keeps_attacks_sharing_a_conversation_async( sqlite_instance: SQLiteMemory, ) -> None: @@ -1195,40 +1105,3 @@ async def test_finding_evidence_page_keeps_attacks_sharing_a_conversation_async( ("First run", EvidenceAvailability.AVAILABLE), ("Second run", EvidenceAvailability.AVAILABLE), } - - -async def test_findings_with_evidence_resolve_in_batches_async( - sqlite_instance: SQLiteMemory, - selected_findings_async: tuple[Operation, list[Finding]], -) -> None: - operation, findings = selected_findings_async - service = OperationService() - finding_ids = [finding.id for finding in findings] - unbatched = await service.get_findings_with_evidence_async(operation_id=operation.id, finding_ids=finding_ids) - with ( - patch("pyrit.backend.services.operation_service._EVIDENCE_BATCH_SIZE", 2), - patch.object( - sqlite_instance, "get_attack_results_async", wraps=sqlite_instance.get_attack_results_async - ) as owners, - ): - batched = await service.get_findings_with_evidence_async(operation_id=operation.id, finding_ids=finding_ids) - assert batched == unbatched - assert owners.call_count == 3 - - -async def test_findings_with_evidence_reject_missing_and_foreign_findings_async( - sqlite_instance: SQLiteMemory, - selected_findings_async: tuple[Operation, list[Finding]], -) -> None: - operation, findings = selected_findings_async - other = await sqlite_instance.add_operation_async(Operation(name="Other")) - foreign = await sqlite_instance.add_finding_async( - finding=Finding(operation_id=other.id, title="Foreign", severity="low") - ) - unknown = uuid4() - service = OperationService() - for finding_ids, named in [([findings[0].id, foreign.id, unknown], foreign.id), ([unknown, foreign.id], unknown)]: - with pytest.raises(FindingNotFoundError, match=f"Finding '{named}' not found in operation '{operation.id}'"): - await service.get_findings_with_evidence_async(operation_id=operation.id, finding_ids=finding_ids) - with pytest.raises(OperationNotFoundError): - await service.get_findings_with_evidence_async(operation_id=MISSING_ID, finding_ids=[findings[0].id]) diff --git a/tests/unit/infra/test_bicep_topology.py b/tests/unit/infra/test_bicep_topology.py index 1604879f42..76bcceb0c2 100644 --- a/tests/unit/infra/test_bicep_topology.py +++ b/tests/unit/infra/test_bicep_topology.py @@ -228,6 +228,22 @@ def test_application_reads_existing_state_and_preserves_authentication(self) -> assert "deployInfra" not in json.dumps(template) assert "deployApp" not in json.dumps(template) + def test_application_lets_requests_finish_and_names_its_public_origin(self) -> None: + application = _compile_bicep(APPLICATION_BICEP, self.output_directory / "application-runtime.json") + front_door = _compile_bicep(FRONT_DOOR_BICEP, self.output_directory / "front-door-timeout.json") + + template = _resources(application, "Microsoft.App/containerApps")[0]["properties"]["template"] + timeout = _resources(front_door, "Microsoft.Cdn/profiles")[0]["properties"]["originResponseTimeoutSeconds"] + # A request still running at SIGTERM can finish before ACA's SIGKILL; ACA allows at most 600 seconds. + assert timeout < template["terminationGracePeriodSeconds"] <= 600 + environment = { + value["name"]: value["value"] for value in template["containers"][0]["env"] if isinstance(value, dict) + } + public_origin = environment["PYRIT_PUBLIC_ORIGIN"] + assert "parameters('enableFrontDoor')" in public_origin + assert ".hostName" in public_origin + assert ".defaultDomain" in public_origin + def test_aca_nat_network_is_static_and_delegated(self): template = _compile_bicep(NETWORK_BICEP, self.output_directory / "network.json") diff --git a/tests/unit/infra/test_code_deployment.py b/tests/unit/infra/test_code_deployment.py index 11e2e8f108..30da49dcbc 100644 --- a/tests/unit/infra/test_code_deployment.py +++ b/tests/unit/infra/test_code_deployment.py @@ -4,6 +4,7 @@ import json import os +import re import shlex import shutil import subprocess @@ -16,6 +17,7 @@ REPO_ROOT = Path(__file__).resolve().parents[3] PIPELINES = REPO_ROOT / "infra" / "pipelines" +APPLICATION_BICEP = REPO_ROOT / "infra" / "application.bicep" SUBSCRIPTION = "11111111-1111-1111-1111-111111111111" RESOURCE_GROUP = f"/subscriptions/{SUBSCRIPTION}/resourceGroups/copyrit-test" IMAGE = f"copyritacr.azurecr.io/pyrit@sha256:{'a' * 64}" @@ -907,6 +909,28 @@ def test_stop_app_timeout_does_not_start_migration(self) -> None: assert "shutdown was not confirmed" in result.stdout assert "migration-started" not in result.stdout + def test_stop_app_waits_out_the_termination_grace_period(self) -> None: + grace = re.search(r"terminationGracePeriodSeconds:\s*(\d+)", APPLICATION_BICEP.read_text(encoding="utf-8")) + assert grace is not None + result = self._run( + script="deploy_app.sh", + inputs=APP_INPUTS, + command=""" +sleep() { echo "slept $1"; } +az() { + case "$2 $3" in + "revision list") echo '[{"name":"app--old","properties":{"active":false,"replicas":1}}]' ;; + *) exit 97 ;; + esac +} +stop_app +""", + ) + assert result.returncode == 1 + sleeps = [int(line.split()[1]) for line in result.stdout.splitlines() if line.startswith("slept ")] + # The last wait follows the last check, so only the waits before it can see the app stop. + assert sum(sleeps[:-1]) > int(grace[1]) + def test_stop_app_accepts_already_stopped_revision(self) -> None: result = self._run( script="deploy_app.sh", diff --git a/tests/unit/memory/test_resolved_finding_evidence.py b/tests/unit/memory/test_resolved_finding_evidence.py new file mode 100644 index 0000000000..9640063543 --- /dev/null +++ b/tests/unit/memory/test_resolved_finding_evidence.py @@ -0,0 +1,107 @@ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT license. + +from datetime import UTC, datetime +from unittest.mock import patch +from uuid import UUID, uuid4 + +import pytest + +from pyrit.memory import SQLiteMemory +from pyrit.models import AttackOutcome, AttackResult, FindingEvidence, Message, MessagePiece, ResolvedFindingEvidence + +pytestmark = pytest.mark.usefixtures("patch_central_database") + + +async def _save_attacks_async(*, memory: SQLiteMemory, count: int) -> list[AttackResult]: + """Save attacks that each have one saved message, so their evidence is available.""" + attacks = [ + AttackResult(conversation_id=f"conversation-{index}", objective=f"Objective {index}") for index in range(count) + ] + await memory.add_attack_results_to_memory_async(attack_results=attacks) + for attack in attacks: + await memory.add_message_to_memory_async( + request=Message( + message_pieces=[ + MessagePiece(role="user", original_value="Saved", conversation_id=attack.conversation_id) + ] + ) + ) + return attacks + + +def _evidence_for(attacks: list[AttackResult]) -> list[FindingEvidence]: + return [FindingEvidence(finding_id=uuid4(), attack_result_id=UUID(attack.attack_result_id)) for attack in attacks] + + +async def test_get_resolved_finding_evidence_reads_in_constant_queries(sqlite_instance: SQLiteMemory) -> None: + evidence = _evidence_for(await _save_attacks_async(memory=sqlite_instance, count=3)) + with ( + patch.object( + sqlite_instance, "get_attack_results_async", wraps=sqlite_instance.get_attack_results_async + ) as owners, + patch.object( + sqlite_instance, "get_conversation_stats_async", wraps=sqlite_instance.get_conversation_stats_async + ) as stats, + ): + resolved = await sqlite_instance.get_resolved_finding_evidence_async(evidence=evidence) + + owners.assert_called_once() + stats.assert_called_once() + assert [(item.evidence, item.objective, item.available) for item in resolved] == [ + (item, f"Objective {index}", True) for index, item in enumerate(evidence) + ] + + +async def test_get_resolved_finding_evidence_marks_missing_and_messageless_attacks_unavailable( + sqlite_instance: SQLiteMemory, +) -> None: + messageless = AttackResult(conversation_id="nothing-saved", objective="Messageless") + await sqlite_instance.add_attack_results_to_memory_async(attack_results=[messageless]) + evidence = [ + FindingEvidence(finding_id=uuid4(), attack_result_id=uuid4()), + FindingEvidence(finding_id=uuid4(), attack_result_id=UUID(messageless.attack_result_id)), + ] + + gone, saved = await sqlite_instance.get_resolved_finding_evidence_async(evidence=evidence) + + assert gone == ResolvedFindingEvidence(evidence=evidence[0], available=False) + assert (saved.available, saved.objective, saved.outcome, saved.conversation_id) == ( + False, + "Messageless", + AttackOutcome.UNDETERMINED, + "nothing-saved", + ) + + +async def test_get_resolved_finding_evidence_keeps_an_older_attack_sharing_a_conversation( + sqlite_instance: SQLiteMemory, +) -> None: + attacks = [ + AttackResult(conversation_id="shared", objective=objective, timestamp=datetime(2026, 1, day, tzinfo=UTC)) + for day, objective in [(1, "First run"), (2, "Second run")] + ] + await sqlite_instance.add_attack_results_to_memory_async(attack_results=attacks) + await sqlite_instance.add_message_to_memory_async( + request=Message(message_pieces=[MessagePiece(role="user", original_value="Shared", conversation_id="shared")]) + ) + + resolved = await sqlite_instance.get_resolved_finding_evidence_async(evidence=_evidence_for(attacks)) + + assert [(item.objective, item.available) for item in resolved] == [("First run", True), ("Second run", True)] + + +async def test_get_resolved_finding_evidence_reads_in_batches(sqlite_instance: SQLiteMemory) -> None: + evidence = _evidence_for(await _save_attacks_async(memory=sqlite_instance, count=6)) + unbatched = await sqlite_instance.get_resolved_finding_evidence_async(evidence=evidence) + with ( + patch.object(sqlite_instance, "_RESOLVED_EVIDENCE_BATCH_SIZE", 2), + patch.object( + sqlite_instance, "get_attack_results_async", wraps=sqlite_instance.get_attack_results_async + ) as owners, + ): + batched = await sqlite_instance.get_resolved_finding_evidence_async(evidence=evidence) + + assert batched == unbatched + assert [item.evidence for item in batched] == evidence + assert owners.call_count == 3 diff --git a/tests/unit/output/finding_publisher/test_azure_devops.py b/tests/unit/output/finding_publisher/test_azure_devops.py new file mode 100644 index 0000000000..4054bcbe2f --- /dev/null +++ b/tests/unit/output/finding_publisher/test_azure_devops.py @@ -0,0 +1,913 @@ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT license. + +import asyncio +import json +import logging +from collections.abc import Iterator +from types import SimpleNamespace +from typing import Any +from unittest.mock import AsyncMock, patch +from uuid import uuid4 + +import httpx +import pytest +import respx + +from pyrit.models import ( + AttackOutcome, + DecompositionPath, + Finding, + FindingEvidence, + FindingField, + FindingFields, + FindingPublishDestination, + FindingPublishRequester, + FindingPublishResult, + ResolvedFindingEvidence, +) +from pyrit.output import ( + AzureDevOpsField, + AzureDevOpsFieldKind, + AzureDevOpsFindingPublisher, + FindingPublishDeadlineError, + FindingPublishDestinationError, + FindingPublisherConfigurationError, + FindingPublisherUnavailableError, + FindingPublishValidationError, + FindingSelection, +) + +ORG = "https://dev.azure.com/contoso" +WORK_ITEM_URL = f"{ORG}/_apis/wit/workitems/12345" +CREATE_URL = f"{ORG}/Red%20Team/_apis/wit/workitems/$Finding" +API_VERSION = {"api-version": "7.1"} +TOKEN = "secret-token-value" +CLOCK = "pyrit.output.finding_publisher.azure_devops.monotonic" +HTML = AzureDevOpsFieldKind.HTML +TEXT = AzureDevOpsFieldKind.TEXT +CHOICE = AzureDevOpsFieldKind.CHOICE +OPERATION_ID = uuid4() +REQUESTER = FindingPublishRequester(name="Ada Lovelace", email="ada@example.com") + +FIELDS = FindingFields( + severity=FindingField( + key="severity", label="Severity", type="choice", options=[("Critical", "Critical"), ("Low", "Low")] + ), + fields=[ + FindingField(key="summary", label="Summary", type="text"), + FindingField(key="description", label="Description", type="multiline"), + FindingField(key="evidence", label="Evidence", type="multiline"), + FindingField( + key="risk", + label="Risk", + type="choice", + levels=[("subrisk", "Subrisk")], + options={("Privacy", "Privacy"): [("Personal data", "Personal data")]}, + ), + FindingField(key="notes", label="Notes", type="multiline"), + FindingField(key="steps", label="Steps to reproduce", type="multiline"), + ], +) +FIELD_MAP = { + "severity": AzureDevOpsField(reference_name="Custom.Severity", kind=CHOICE), + "summary": AzureDevOpsField(reference_name="Custom.Summary", kind=TEXT), + "description": AzureDevOpsField(reference_name="System.Description", kind=HTML), + "evidence": AzureDevOpsField(reference_name="Custom.Evidence", kind=HTML), + "steps": AzureDevOpsField(reference_name="Custom.Steps", kind=HTML), + "risk": AzureDevOpsField(reference_name="Custom.Risk", kind=CHOICE), + "subrisk": AzureDevOpsField(reference_name="Custom.Subrisk", kind=CHOICE), +} + + +def _publisher(**overrides: Any) -> AzureDevOpsFindingPublisher: + settings: dict[str, Any] = { + "organization_url": ORG, + "project": "Red Team", + "work_item_type": "Finding", + "destination_work_item_types": ("Operation",), + "field_map": FIELD_MAP, + "evidence_field": "Custom.Evidence", + "unmapped_keys": ("notes",), + "fixed_fields": {"Custom.Linked": "yes", "Custom.UsedPyRIT": True}, + "token_provider": AsyncMock(return_value=TOKEN), + } + return AzureDevOpsFindingPublisher(**{**settings, **overrides}) + + +def _finding(title: str = "Encoded instructions bypass the refusal policy", **values: Any) -> Finding: + return Finding(operation_id=OPERATION_ID, severity=values.pop("severity", "Critical"), title=title, **values) + + +def _selection(*findings: Finding, **extra: Any) -> FindingSelection: + return FindingSelection( + operation_id=OPERATION_ID, + operation_name="Operation", + findings=findings or (_finding(),), + evidence=extra.get("evidence", {}), + part_of=extra.get("part_of", {}), + ) + + +def _resolved(finding: Finding, *, objective: str, conversation_id: str, **values: Any) -> ResolvedFindingEvidence: + values.setdefault("source_operation_id", uuid4()) + return ResolvedFindingEvidence( + evidence=FindingEvidence(finding_id=finding.id, attack_result_id=uuid4()), + available=True, + objective=objective, + outcome=AttackOutcome.SUCCESS, + conversation_id=conversation_id, + **values, + ) + + +def _work_item(*, project: str = "Red Team", work_item_type: str = "Operation") -> dict[str, Any]: + return { + "id": 12345, + "fields": { + "System.TeamProject": project, + "System.WorkItemType": work_item_type, + "System.Title": "Operation Contoso", + "System.AreaPath": "Red Team\\AI", + "System.IterationPath": "Red Team\\2026", + }, + "_links": {"html": {"href": f"{ORG}/Red%20Team/_workitems/edit/12345"}}, + } + + +def _created(work_item_id: int) -> httpx.Response: + return httpx.Response( + 200, json={"id": work_item_id, "_links": {"html": {"href": f"{ORG}/_workitems/edit/{work_item_id}"}}} + ) + + +def _short_timeout_for_request(number: int) -> Any: + """ + Shorten the request timeout of only the adapter's ``number``-th request, the one whose answer never arrives. + + Returns: + Any: A patch of the adapter's ``asyncio`` that keeps every other request's real timeout. + """ + requests = 0 + + def timeout(delay: float) -> asyncio.Timeout: + nonlocal requests + requests += 1 + return asyncio.timeout(0.05 if requests == number else delay) + + return patch("pyrit.output.finding_publisher.azure_devops.asyncio", new=SimpleNamespace(timeout=timeout)) + + +def _sent_fields(request: httpx.Request) -> dict[str, Any]: + return { + operation["path"].removeprefix("/fields/"): operation["value"] + for operation in json.loads(request.content) + if operation["path"].startswith("/fields/") + } + + +@pytest.fixture +def ado() -> Iterator[respx.MockRouter]: + with respx.mock(assert_all_called=False) as router: + yield router + + +@pytest.fixture +def destination_route(ado: respx.MockRouter) -> respx.Route: + return ado.get(WORK_ITEM_URL, params=API_VERSION).respond(200, json=_work_item()) + + +@pytest.fixture +def create_route(ado: respx.MockRouter) -> respx.Route: + return ado.post(CREATE_URL, params=API_VERSION).mock(side_effect=[_created(501), _created(502), _created(503)]) + + +async def _publish(publisher: AzureDevOpsFindingPublisher, *findings: Finding, **kwargs: Any) -> FindingPublishResult: + return await publisher.publish_async( + selection=_selection(*findings), fields=FIELDS, destination="12345", requested_by=REQUESTER, **kwargs + ) + + +# Construction + + +@pytest.mark.parametrize( + "organization_url", + [ + "http://dev.azure.com/contoso", + "https://dev.azure.com/contoso/project", + "https://dev.azure.com/", + "https://contoso.example.com", + "https://contoso.visualstudio.com/project", + "", + ], +) +def test_init_rejects_other_organization_urls(organization_url: str) -> None: + with pytest.raises(ValueError, match="organization_url must be"): + _publisher(organization_url=organization_url) + + +@pytest.mark.parametrize(("setting", "value"), [("project", " "), ("work_item_type", ""), ("evidence_field", "")]) +def test_init_rejects_empty_required_values(setting: str, value: str) -> None: + with pytest.raises(ValueError, match=f"{setting} must not be empty"): + _publisher(**{setting: value}) + + +def test_init_rejects_no_destination_types() -> None: + with pytest.raises(ValueError, match="at least one work item type"): + _publisher(destination_work_item_types=()) + + +@pytest.mark.parametrize("setting", ["destination_work_item_types", "unmapped_keys"]) +def test_init_rejects_a_single_string_for_a_collection(setting: str) -> None: + with pytest.raises(TypeError, match="not a single string"): + _publisher(**{setting: "Operation"}) + + +def test_construction_and_check_fields_get_no_token() -> None: + provider = AsyncMock(return_value=TOKEN) + with patch("pyrit.auth.get_azure_async_token_provider") as default_provider: + _publisher(token_provider=provider).check_fields(fields=FIELDS) + _publisher(token_provider=None).check_fields(fields=FIELDS) + + provider.assert_not_called() + default_provider.assert_not_called() + + +def test_identifier_records_the_configuration_without_credentials_or_labels() -> None: + publisher = _publisher(destination_label="Operation work item") + + params = publisher.get_identifier().params + + assert params["organization_url"] == ORG + assert params["field_map"]["severity"] == {"reference_name": "Custom.Severity", "kind": "choice"} + assert params["fixed_fields"] == {"Custom.Linked": "yes", "Custom.UsedPyRIT": True} + assert params["nest_sub_findings"] is True + serialized = json.dumps(publisher.get_identifier().model_dump(mode="json")) + assert TOKEN not in serialized + assert "Operation work item" not in serialized + assert _publisher(nest_sub_findings=False).get_identifier().hash != publisher.get_identifier().hash + + +def test_info_carries_the_destination_label_and_hint() -> None: + info = _publisher(destination_label="Operation work item", destination_hint="Paste its ID.").info + + assert (info.destination_label, info.destination_hint) == ("Operation work item", "Paste its ID.") + + +# check_fields + + +def test_check_fields_accepts_a_complete_map() -> None: + _publisher().check_fields(fields=FIELDS) + + +def _with_field(field: FindingField) -> FindingFields: + return FindingFields(severity=FIELDS.severity, fields=[*FIELDS.fields, field]) + + +@pytest.mark.parametrize( + ("overrides", "fields", "message"), + [ + ({"unmapped_keys": ()}, FIELDS, "Map 'notes' in field_map, or list it in unmapped_keys."), + ({"unmapped_keys": ("notes", "summary")}, FIELDS, "'summary' is in both field_map and unmapped_keys."), + ({"unmapped_keys": ("notes", "retired")}, FIELDS, "'retired' in field_map or unmapped_keys isn't"), + ( + {"field_map": {**FIELD_MAP, "notes": FIELD_MAP["summary"]}, "unmapped_keys": ()}, + FIELDS, + "Only one key can map to 'custom.summary'.", + ), + ( + {"field_map": {**FIELD_MAP, "summary": AzureDevOpsField(reference_name="System.Title", kind=TEXT)}}, + FIELDS, + "'System.Title' is set by the publisher", + ), + ({"fixed_fields": {"System.AssignedTo": "x"}}, FIELDS, "'System.AssignedTo' is set by the publisher"), + ({"fixed_fields": {"System.Description": "x"}}, FIELDS, "Fixed field 'System.Description' is also written"), + ({"fixed_fields": {"Custom.Risk": "x"}}, FIELDS, "Fixed field 'Custom.Risk' is also written"), + ({"evidence_field": "System.Description"}, FIELDS, "evidence_field can't be 'System.Description'."), + ( + { + "field_map": { + **FIELD_MAP, + "description": AzureDevOpsField(reference_name="System.Description", kind=TEXT), + } + }, + FIELDS, + "'description' maps to 'System.Description', which takes kind html.", + ), + ( + {"field_map": {**FIELD_MAP, "summary": AzureDevOpsField(reference_name="Custom.Summary", kind=CHOICE)}}, + FIELDS, + "'summary' is a text field, which kind choice can't publish", + ), + ( + {"field_map": {**FIELD_MAP, "subrisk": AzureDevOpsField(reference_name="Custom.Subrisk", kind=TEXT)}}, + FIELDS, + "'subrisk' is a level of choice field 'risk', which kind text can't publish", + ), + ( + {"field_map": {**FIELD_MAP, "risk": AzureDevOpsField(reference_name="Custom.Risk", kind=HTML)}}, + FIELDS, + "'risk' is a choice field, which kind html can't publish", + ), + ( + {"field_map": {**FIELD_MAP, "notes": AzureDevOpsField(reference_name="Custom.Notes", kind=TEXT)}}, + FIELDS, + "'notes' is a multiline field, which kind text can't publish", + ), + ( + {"field_map": {**FIELD_MAP, "harm": AzureDevOpsField(reference_name="Custom.Harm", kind=CHOICE)}}, + _with_field(FindingField(key="harm", label="Harm", type="choice", options=[("a", "A")], allow_other=True)), + "'harm' is a choice field that takes Other text", + ), + ( + {"field_map": {**FIELD_MAP, "harm": AzureDevOpsField(reference_name="Custom.Harm", kind=CHOICE)}}, + _with_field(FindingField(key="harm", label="Harm", type="choice", options=[("x" * 256, "Long")])), + "must be one line of at most 255 characters", + ), + ( + {"field_map": {**FIELD_MAP, "harm": AzureDevOpsField(reference_name="Custom.Harm", kind=CHOICE)}}, + _with_field(FindingField(key="harm", label="Harm", type="choice", options=[("a\tb", "Tabbed")])), + "must be one line of at most 255 characters", + ), + ], +) +def test_check_fields_rejects_each_rule(overrides: dict[str, Any], fields: FindingFields, message: str) -> None: + with pytest.raises(FindingPublisherConfigurationError, match=message.replace("(", r"\(").replace(")", r"\)")): + _publisher(**overrides).check_fields(fields=fields) + + +def test_check_fields_reports_every_offending_key_at_once() -> None: + with pytest.raises(FindingPublisherConfigurationError) as raised: + _publisher(unmapped_keys=("summary",)).check_fields(fields=FIELDS) + + assert "Map 'notes'" in str(raised.value) + assert "'summary' is in both" in str(raised.value) + + +# Destination + + +@pytest.mark.parametrize( + "destination", + [ + "12345", + " 12345 ", + f"{ORG}/Red%20Team/_workitems/edit/12345", + f"{ORG}/Red%20Team/_workitems/edit/12345/?fullScreen=true#comments", + "https://DEV.azure.com/Contoso/_workitems/edit/12345", + "https://contoso.visualstudio.com/Red%20Team/_workitems/edit/12345", + ], +) +async def test_preview_reads_the_destination_from_an_id_or_url( + destination: str, destination_route: respx.Route +) -> None: + preview = await _publisher().preview_async(selection=_selection(), fields=FIELDS, destination=destination) + + assert preview.destination == FindingPublishDestination( + id="12345", + title="Operation Contoso", + url=f"{ORG}/Red%20Team/_workitems/edit/12345", + location="contoso / Red Team", + ) + assert destination_route.call_count == 1 + assert destination_route.calls.last.request.headers["Authorization"] == f"Bearer {TOKEN}" + + +async def test_preview_accepts_the_largest_work_item_id(ado: respx.MockRouter) -> None: + route = ado.get(f"{ORG}/_apis/wit/workitems/2147483647", params=API_VERSION).respond(200, json=_work_item()) + + await _publisher().preview_async(selection=_selection(), fields=FIELDS, destination="2147483647") + + assert route.called + + +@pytest.mark.parametrize( + "destination", + [ + "0", + "2147483648", + "1" * 5000, + f"{ORG}/_workitems/edit/{'1' * 5000}", + "-5", + "12a", + "", + "https://dev.azure.com/contoso-other/_workitems/edit/12345", + "http://dev.azure.com/contoso/_workitems/edit/12345", + "https://evil.example.com/contoso/_workitems/edit/12345", + "https://contoso.visualstudio.com.evil.example.com/_workitems/edit/12345", + "https://other.visualstudio.com/_workitems/edit/12345", + "https://user@dev.azure.com/contoso/_workitems/edit/12345", + "https://dev.azure.com:8443/contoso/_workitems/edit/12345", + "https://dev.azure.com/contoso/_workitems/12345", + "javascript:alert(12345)", + ], +) +async def test_preview_rejects_destinations_outside_the_organization_without_a_request( + destination: str, ado: respx.MockRouter +) -> None: + with pytest.raises(FindingPublishDestinationError, match="Paste a work item ID, or a link from"): + await _publisher().preview_async(selection=_selection(), fields=FIELDS, destination=destination) + + assert not ado.calls + + +async def test_preview_rejects_a_destination_in_another_project_without_naming_it(ado: respx.MockRouter) -> None: + ado.get(WORK_ITEM_URL, params=API_VERSION).respond(200, json=_work_item(project="Secret Project")) + + with pytest.raises(FindingPublishDestinationError) as raised: + await _publisher().preview_async(selection=_selection(), fields=FIELDS, destination="12345") + + assert str(raised.value) == "Work item 12345 isn't in the Red Team project." + + +async def test_preview_rejects_a_destination_of_another_type(ado: respx.MockRouter) -> None: + ado.get(WORK_ITEM_URL, params=API_VERSION).respond(200, json=_work_item(work_item_type="Task")) + + with pytest.raises( + FindingPublishDestinationError, match="is of type Task. Paste a work item of type Operation or Epic" + ): + await _publisher(destination_work_item_types=("Operation", "Epic")).preview_async( + selection=_selection(), fields=FIELDS, destination="12345" + ) + + +async def test_preview_compares_project_and_type_ignoring_case(ado: respx.MockRouter) -> None: + ado.get(WORK_ITEM_URL, params=API_VERSION).respond( + 200, json=_work_item(project="RED TEAM", work_item_type="operation") + ) + + preview = await _publisher().preview_async(selection=_selection(), fields=FIELDS, destination="12345") + + assert preview.destination.location == "contoso / RED TEAM" + + +async def test_preview_reports_a_missing_destination(ado: respx.MockRouter) -> None: + ado.get(WORK_ITEM_URL, params=API_VERSION).respond(404, json={"message": "TF401232: Work item does not exist."}) + + with pytest.raises(FindingPublishDestinationError, match="doesn't exist, or the publishing identity can't see it"): + await _publisher().preview_async(selection=_selection(), fields=FIELDS, destination="12345") + + +@pytest.mark.parametrize( + ("response", "message"), + [ + (httpx.Response(401), "didn't accept the publishing identity (HTTP 401)"), + (httpx.Response(403), "isn't allowed to do this in Azure DevOps (HTTP 403)"), + (httpx.Response(429), "is throttling the publishing identity (HTTP 429)"), + (httpx.Response(400, json={"message": "VS403: Bad query."}), "rejected the request (HTTP 400): VS403: Bad"), + (httpx.Response(503), "Couldn't get an answer from Azure DevOps (HTTP 503)"), + (httpx.Response(200, text=""), "Couldn't get an answer from Azure DevOps (unreadable response)"), + (httpx.Response(200, json={"id": 12345}), "Couldn't get an answer from Azure DevOps (unreadable response)"), + (httpx.ConnectError("refused"), "Couldn't reach Azure DevOps"), + (httpx.ConnectTimeout("slow"), "Couldn't reach Azure DevOps"), + (httpx.ReadTimeout("slow"), "Couldn't get an answer from Azure DevOps (timed out)"), + (httpx.RemoteProtocolError("dropped"), "Couldn't get an answer from Azure DevOps (no response)"), + ], +) +async def test_preview_reports_azure_devops_as_unavailable( + response: httpx.Response | Exception, message: str, ado: respx.MockRouter +) -> None: + ado.get(WORK_ITEM_URL, params=API_VERSION).mock(side_effect=[response]) + + with pytest.raises(FindingPublisherUnavailableError, match=message.replace("(", r"\(").replace(")", r"\)")): + await _publisher().preview_async(selection=_selection(), fields=FIELDS, destination="12345") + + +async def test_preview_reports_a_token_error_and_logs_it( + ado: respx.MockRouter, caplog: pytest.LogCaptureFixture +) -> None: + provider = AsyncMock(side_effect=RuntimeError("No managed identity endpoint.")) + + with ( + caplog.at_level(logging.WARNING), + pytest.raises(FindingPublisherUnavailableError, match="couldn't get an Azure"), + ): + await _publisher(token_provider=provider).preview_async( + selection=_selection(), fields=FIELDS, destination="12345" + ) + + assert not ado.calls + assert any(record.exc_info for record in caplog.records) + + +async def test_preview_reports_a_token_that_never_arrives(ado: respx.MockRouter) -> None: + async def hang() -> str: + await asyncio.Event().wait() + return TOKEN + + with ( + patch.object(AzureDevOpsFindingPublisher, "REQUEST_TIMEOUT_SECONDS", 0.01), + pytest.raises(FindingPublisherUnavailableError, match="couldn't get an Azure DevOps token"), + ): + await _publisher(token_provider=hang).preview_async(selection=_selection(), fields=FIELDS, destination="12345") + + assert not ado.calls + + +async def test_preview_stops_before_the_token_when_less_than_a_request_timeout_is_left(ado: respx.MockRouter) -> None: + provider = AsyncMock(return_value=TOKEN) + + with patch(CLOCK, return_value=100.0), pytest.raises(FindingPublishDeadlineError): + await _publisher(token_provider=provider).preview_async( + selection=_selection(), fields=FIELDS, destination="12345", deadline=129.9 + ) + + provider.assert_not_called() + assert not ado.calls + + +async def test_preview_sends_a_request_when_exactly_a_request_timeout_is_left(destination_route: respx.Route) -> None: + with ( + patch("pyrit.output.finding_publisher.base.monotonic", return_value=100.0), + patch(CLOCK, return_value=100.0), + ): + await _publisher().preview_async(selection=_selection(), fields=FIELDS, destination="12345", deadline=130.0) + + assert destination_route.called + + +async def test_default_token_provider_uses_the_azure_devops_scope_once(destination_route: respx.Route) -> None: + with patch("pyrit.auth.get_azure_async_token_provider", return_value=AsyncMock(return_value=TOKEN)) as factory: + publisher = _publisher(token_provider=None) + await publisher.preview_async(selection=_selection(), fields=FIELDS, destination="12345") + await publisher.preview_async(selection=_selection(), fields=FIELDS, destination="12345") + + factory.assert_called_once_with("499b84ac-1321-427f-aa17-267ca6975798/.default") + + +# Plan checks + + +@pytest.mark.parametrize( + ("finding", "message"), + [ + (_finding("\U0001f600" * 128), "Title is 256 characters long, as Azure DevOps counts them"), + (_finding("Two\nlines"), "Title contains a line break or tab. Azure DevOps titles hold one line."), + (_finding(field_values={"summary": "Tab\there"}), "Summary contains a line break or tab."), + (_finding(field_values={"summary": "x" * 256}), "Summary is 256 characters long"), + (_finding("Next\u2028line"), "Title contains a line break"), + (_finding("Lone \ud800 surrogate"), "Title contains a line break"), + ], +) +async def test_preview_reports_values_azure_devops_cannot_hold( + finding: Finding, message: str, destination_route: respx.Route +) -> None: + preview = await _publisher().preview_async(selection=_selection(finding), fields=FIELDS, destination="12345") + + assert len(preview.problems) == 1 + assert preview.problems[0].message.startswith(message) + + +async def test_preview_accepts_a_title_of_exactly_255_code_units(destination_route: respx.Route) -> None: + title = "\U0001f600" * 127 + "x" + + preview = await _publisher().preview_async( + selection=_selection(_finding(title)), fields=FIELDS, destination="12345" + ) + + assert preview.problems == () + + +async def test_publish_with_problems_sends_no_create(destination_route: respx.Route, create_route: respx.Route) -> None: + with pytest.raises(FindingPublishValidationError): + await _publish(_publisher(), _finding("Two\nlines")) + + assert not destination_route.called + assert not create_route.called + + +# Creating work items + + +async def test_publish_sends_one_json_patch_document_per_finding( + destination_route: respx.Route, create_route: respx.Route +) -> None: + finding = _finding( + field_values={ + "summary": "Model follows text", + "description": "The model follows\nencoded input.", + "evidence": "See the run & transcript.", + "risk": "Privacy", + "subrisk": "Personal data", + "notes": "Not published", + "steps": '1. Send \n2. Read the reply', + } + ) + + result = await _publish(_publisher(), finding) + + request = create_route.calls.last.request + assert request.headers["Content-Type"] == "application/json-patch+json" + assert request.headers["Authorization"] == f"Bearer {TOKEN}" + assert dict(request.url.params) == API_VERSION + document = json.loads(request.content) + assert all(operation["op"] == "add" for operation in document) + assert _sent_fields(request) == { + "System.Title": "Encoded instructions bypass the refusal policy", + "Custom.Severity": "Critical", + "Custom.Summary": "Model follows text", + "Custom.Risk": "Privacy", + "Custom.Subrisk": "Personal data", + "Custom.Steps": "1. Send <img src=x onerror="alert(1)">
    2. Read the reply", + "System.Description": "The model follows
    <b>encoded</b> input.", + "Custom.Evidence": "See the run & transcript.", + "Custom.Linked": "yes", + "Custom.UsedPyRIT": True, + "System.AreaPath": "Red Team\\AI", + "System.IterationPath": "Red Team\\2026", + "System.AssignedTo": "ada@example.com", + "System.History": ( + f"Published from CoPyRIT by Ada Lovelace (ada@example.com). Run {result.run_id}, finding {finding.id}." + ), + } + assert document[-1] == { + "op": "add", + "path": "/relations/-", + "value": {"rel": "System.LinkTypes.Hierarchy-Reverse", "url": f"{ORG}/_apis/wit/workItems/12345"}, + } + assert "bypassRules" not in str(request.url) + assert [(item.external_id, item.url, item.parent_external_id) for item in result.created] == [ + ("501", f"{ORG}/_workitems/edit/501", "12345") + ] + + +async def test_publish_omits_empty_values(destination_route: respx.Route, create_route: respx.Route) -> None: + await _publish(_publisher(fixed_fields={"Custom.Empty": ""}), _finding(field_values={"summary": " "})) + + assert set(_sent_fields(create_route.calls.last.request)) == { + "System.Title", + "Custom.Severity", + "System.AreaPath", + "System.IterationPath", + "System.AssignedTo", + "System.History", + } + + +async def test_publish_links_a_sub_finding_to_its_parents_new_work_item( + destination_route: respx.Route, create_route: respx.Route +) -> None: + parent = _finding("Parent") + child = _finding("Child", parent_finding_id=parent.id) + + await _publish(_publisher(), parent, child) + + relation = json.loads(create_route.calls[1].request.content)[-1]["value"] + assert relation["url"] == f"{ORG}/_apis/wit/workItems/501" + + +async def test_publish_appends_part_of_paths_and_retired_fields_to_the_description( + destination_route: respx.Route, create_route: respx.Route +) -> None: + parent = _finding("Parent ", demonstrated=False) + step = _finding("Step", parent_finding_id=uuid4(), demonstrated=False) + finding = Finding( + operation_id=OPERATION_ID, + title="Child", + severity="Critical", + parent_finding_id=parent.id, + field_values={"description": "Main text", "old_key": "Old & value"}, + paths=(DecompositionPath(name="Chain", description="Two steps", steps=(step.id,)),), + ) + step = step.model_copy(update={"parent_finding_id": finding.id}) + + await _publish(_publisher(), parent, finding, step) + + assert _sent_fields(create_route.calls.last.request)["System.Description"] == ( + "Main text

    Part of: Parent <one>

    " + "

    Attack paths

    • Chain (Partial)
      Two steps" + "
      Steps: Step (not demonstrated)
    " + "

    Retired fields

    • old_key: Old & value
    " + ) + + +async def test_publish_lists_evidence_with_only_web_links( + destination_route: respx.Route, create_route: respx.Route +) -> None: + finding = _finding() + gone = uuid4() + evidence = ( + _resolved(finding, objective="Run <1>", conversation_id="run", source_operation_name="Other "), + _resolved(finding, objective="Script", conversation_id="script", source_operation_id=OPERATION_ID), + ResolvedFindingEvidence( + evidence=FindingEvidence(finding_id=finding.id, attack_result_id=gone), available=False + ), + ) + links = {"run": 'https://copyrit.example.com/run?a=1&b="2"', "script": "javascript:alert(1)"} + + await _publisher().publish_async( + selection=_selection(finding, evidence={finding.id: evidence}), + fields=FIELDS, + destination="12345", + link_for=lambda target: links[target.conversation_id], + ) + + assert _sent_fields(create_route.calls.last.request)["Custom.Evidence"] == ( + '
    • Run <1>' + "
      Outcome: Success · Score: Not scored
      From operation: Other <op>
    • " + "
    • Script
      Outcome: Success · Score: Not scored
    • " + f"
    • {gone}
      Evidence unavailable
    " + ) + + +@pytest.mark.parametrize( + ("requester", "author", "assigned"), + [ + (FindingPublishRequester(name="Ada", email="ada@example.com"), "Ada (ada@example.com)", "ada@example.com"), + (FindingPublishRequester(name="Ada"), "Ada", None), + (FindingPublishRequester(email="ada@example.com"), "ada@example.com", "ada@example.com"), + (FindingPublishRequester(name=" ", email=""), "a CoPyRIT user", None), + (None, "a CoPyRIT user", None), + ], +) +async def test_publish_names_the_requester_in_the_history( + requester: FindingPublishRequester | None, + author: str, + assigned: str | None, + destination_route: respx.Route, + create_route: respx.Route, +) -> None: + finding = _finding() + + result = await _publisher().publish_async( + selection=_selection(finding), fields=FIELDS, destination="12345", requested_by=requester + ) + + fields = _sent_fields(create_route.calls.last.request) + assert fields["System.History"] == f"Published from CoPyRIT by {author}. Run {result.run_id}, finding {finding.id}." + assert fields.get("System.AssignedTo") == assigned + + +async def test_publish_escapes_the_requester_in_the_history( + destination_route: respx.Route, create_route: respx.Route +) -> None: + requester = FindingPublishRequester(name="Ada