diff --git a/.github/instructions/output.instructions.md b/.github/instructions/output.instructions.md index dcd227e52b..e71ddd8c3c 100644 --- a/.github/instructions/output.instructions.md +++ b/.github/instructions/output.instructions.md @@ -20,7 +20,7 @@ When reviewing: reject any `print()` call outside `StdoutSink`. ### Data fetching belongs in leaf classes only -Format classes (`PrettyAttackResultPrinter`, `MarkdownAttackResultPrinter`) must not import or reference `CentralMemory`. Only `*MemoryPrinter` leaf classes do data I/O. +Format classes (`PrettyAttackResultPrinter`, `MarkdownAttackResultPrinter`) must not import or reference `CentralMemory`. Only `*MemoryPrinter` leaf classes and the builders and sources that gather a report's input, such as `build_finding_selection_async` (`finding_report/selection.py`) and `MemoryConversationSource`, read memory; publishers never do. When reviewing: reject any `CentralMemory` import in a non-leaf file (`pretty.py`, `markdown.py`, `json.py`). @@ -32,7 +32,7 @@ When reviewing: reject synchronous `open()`, `write()`, or network calls inside ## Three-Layer Hierarchy -Every domain follows this structure. Do not mix responsibilities across layers. +Every printer domain follows this structure. Do not mix responsibilities across layers. Finding report builders and [publishers](#publishers) aren't printers and sit outside it. | Layer | File | Responsibility | May import CentralMemory? | |-------|------|---------------|---------------------------| @@ -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 all four abstract members: `info` (the destination input's label and hint), `_open_destination_async`, `_create_item_async`, and `_build_identifier`, which records every setting that shapes the items and never a label or credential. 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. An unexpected (unclassified) error keeps its traceback (`exc_info=True`), its only diagnostic, but PyRIT's own credentials never reach a log or an error. + +When reviewing: reject a subclass that overrides `preview_async`, `publish_async` or the create loop. diff --git a/doc/code/framework.md b/doc/code/framework.md index a1abfc8b1e..ede2c57be1 100644 --- a/doc/code/framework.md +++ b/doc/code/framework.md @@ -288,10 +288,11 @@ These modules support every component. ## [Output](./output/0_output) -**Responsibility**: Render results (attack and scenario results, conversations, scores, and findings) in any format to any destination. +**Responsibility**: Render results (attack and scenario results, conversations, scores, and findings) in any format to any destination, and publish selected findings to another system. - Keep the format (pretty, Markdown, JSON, or HTML) separate from the sink (stdout, a file, or a notebook). Surfaces use these renderers instead of writing their own. -- **Does not own**: what or when to render. Formatters turn data into strings and sinks write them. Formatters never fetch data, touch `CentralMemory`, or print; only `*MemoryPrinter` classes read memory. +- A finding publisher creates items in another system and returns what it created and every finding's outcome, so it isn't a sink. +- **Does not own**: what or when to render. Formatters turn data into strings and sinks write them. Formatters never fetch data, touch `CentralMemory`, or print; only `*MemoryPrinter` classes and the builders and sources that gather a report's input, such as `build_finding_selection_async` and `MemoryConversationSource`, read memory. **Contributing (difficulty low)**: Adding a format or sink is well-defined. Give every new domain printer a matching convenience function in `helpers.py`. diff --git a/doc/code/output/0_output.ipynb b/doc/code/output/0_output.ipynb index e828edaa7d..899b833a24 100644 --- a/doc/code/output/0_output.ipynb +++ b/doc/code/output/0_output.ipynb @@ -763,6 +763,225 @@ "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", + "the destination, or the publisher changed, it raises `FindingPublishPlanChangedError` before writing\n", + "anything. Pass `link_for` to `publish_async` to link each piece of evidence, as `build_finding_report`\n", + "does. Links don't change the digest, so the preview takes none.\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 are `severity`,\n", + "`harm_type`, and `description`, and `severity` and `harm_type` take Other text, so with the defaults,\n", + "map only `description` and list `severity` and `harm_type` 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 its four abstract members: `info`,\n", + "the label and hint a surface shows for the destination; `_open_destination_async`, which reads the\n", + "destination; `_create_item_async`, which creates one item; and `_build_identifier`, which records every\n", + "setting that shapes the items and never a label or credential. The base class plans the items, checks\n", + "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..4a8602959e 100644 --- a/doc/code/output/0_output.py +++ b/doc/code/output/0_output.py @@ -247,6 +247,163 @@ # 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, +# the destination, or the publisher 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. +# +# `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 are `severity`, +# `harm_type`, and `description`, and `severity` and `harm_type` take Other text, so with the defaults, +# map only `description` and list `severity` and `harm_type` 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 its four abstract members: `info`, +# the label and hint a surface shows for the destination; `_open_destination_async`, which reads the +# destination; `_create_item_async`, which creates one item; and `_build_identifier`, which records every +# setting that shapes the items and never a label or credential. 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/pyrit/backend/routes/operations.py b/pyrit/backend/routes/operations.py index 3b900799f3..fe723240b4 100644 --- a/pyrit/backend/routes/operations.py +++ b/pyrit/backend/routes/operations.py @@ -24,7 +24,7 @@ OperationListResponse, OperationUpdateRequest, ) -from pyrit.backend.services.finding_export import FindingExportTooLargeError, export_findings_async +from pyrit.backend.services.finding_export import export_findings_async from pyrit.backend.services.operation_service import ( DuplicateOperationError, FindingConflictError, @@ -37,6 +37,7 @@ from pyrit.memory.memory_interface import OperationInUseError from pyrit.models import Finding, FindingFields, FindingValuesError, Operation from pyrit.models.harm_category import HarmCategory +from pyrit.output import FindingSelectionNotFoundError, FindingSelectionTooLargeError from pyrit.setup.finding_fields import get_active_finding_fields T = TypeVar("T") @@ -244,12 +245,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, diff --git a/pyrit/backend/services/finding_export.py b/pyrit/backend/services/finding_export.py index 6b3ad754ef..c00299dba0 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,77 +106,18 @@ 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, - ) - - -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)), + selection=selection, + fields=fields, + link_for=partial(_conversation_link, dashboard_origin=request.dashboard_origin), ) - 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. @@ -198,11 +126,11 @@ def _conversation_link(*, dashboard_origin: AnyHttpUrl, item: FindingEvidenceIte ``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 +144,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/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/memory/memory_interface.py b/pyrit/memory/memory_interface.py index ab96f4b927..66d16b2bae 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 @@ -1866,6 +1870,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 e2ff6d4c8b..ea52920d6a 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 @@ -581,12 +595,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..b01573ea70 --- /dev/null +++ b/pyrit/output/finding_publisher/azure_devops.py @@ -0,0 +1,945 @@ +# 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 = ( + "Couldn't get a valid Azure DevOps token from the token provider. Make sure the Azure credential it uses can " + "sign in." +) +_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. " + "Look for it in 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, diagnostics=_error_type(exc)) from exc + except httpx.TimeoutException as exc: + raise _RequestFailedError( + kind=_FailureKind.NO_ANSWER, detail="timed out", diagnostics=_error_type(exc) + ) from exc + except httpx.RequestError as exc: + raise _RequestFailedError( + kind=_FailureKind.NO_ANSWER, detail="no response", diagnostics=_error_type(exc) + ) 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) + # A token that isn't a valid header value would fail inside httpx, whose error can quote the header. + if not token.isascii() or not token.isprintable() or token != token.strip(): + logger.warning("The Azure DevOps token provider returned a token that can't be sent in a header.") + 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 "an unknown requester" + return f"Published from PyRIT 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. " + "Look for it in 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 _error_type(exc: httpx.RequestError) -> dict[str, str]: + """ + Name a transport error by its type only: its message can quote the request, including its headers. + + Returns: + dict[str, str]: The error's class name, such as ``RemoteProtocolError``. + """ + return {"error": type(exc).__name__} + + +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..d76f905d20 --- /dev/null +++ b/pyrit/output/finding_publisher/base.py @@ -0,0 +1,435 @@ +# 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 findings, the destination or the publisher changed since the + preview that returned ``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..65eafc1179 --- /dev/null +++ b/pyrit/output/finding_publisher/errors.py @@ -0,0 +1,94 @@ +# 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, its + rate-limit headers or a transport error's type. They never hold names, emails, titles, field values, credentials + 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 findings, the destination or the publisher changed since the preview, so nothing is published. + + The plan digest covers the planned findings with their parents, the skipped findings, the destination as written + and the publisher's identifier, so a change to any of them gives a different digest. + """ + + def __init__(self) -> None: + """Initialize the error with its message.""" + super().__init__("The findings, the destination or the publisher changed since the preview. Preview 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/tests/unit/backend/test_finding_export.py b/tests/unit/backend/test_finding_export.py index 8a7efd861e..f2a180e673 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", @@ -1027,20 +976,13 @@ def test_conversation_links_match_the_dashboard_route_contract() -> None: 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, + 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_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/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..9301fe5f44 --- /dev/null +++ b/tests/unit/output/finding_publisher/test_azure_devops.py @@ -0,0 +1,997 @@ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT license. + +import asyncio +import json +import logging +import traceback +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") + + +@pytest.mark.parametrize("error", [httpx.ConnectError, httpx.ReadTimeout, httpx.RemoteProtocolError, httpx.WriteError]) +async def test_preview_names_a_transport_error_by_its_type_only( + error: type[httpx.RequestError], ado: respx.MockRouter +) -> None: + ado.get(WORK_ITEM_URL, params=API_VERSION).mock(side_effect=[error(f"Illegal header value b'Bearer {TOKEN}'")]) + + with pytest.raises(FindingPublisherUnavailableError) as raised: + await _publisher().preview_async(selection=_selection(), fields=FIELDS, destination="12345") + + assert raised.value.diagnostics == {"error": error.__name__} + assert TOKEN not in str(raised.value) + + +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 a valid Azure DevOps token"), + ): + 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 a valid Azure DevOps token"), + ): + await _publisher(token_provider=hang).preview_async(selection=_selection(), fields=FIELDS, destination="12345") + + assert not ado.calls + + +@pytest.mark.parametrize( + "token", + [f"{TOKEN}\n", f"{TOKEN} ", f" {TOKEN}", f"{TOKEN}\t", f"{TOKEN}\x00", f"{TOKEN}\x7f", f"{TOKEN}é"], + ids=["newline", "trailing space", "leading space", "tab", "nul", "delete", "non-ascii"], +) +async def test_preview_rejects_a_token_that_is_not_a_header_value_without_showing_it( + token: str, ado: respx.MockRouter, caplog: pytest.LogCaptureFixture +) -> None: + with ( + caplog.at_level(logging.DEBUG, logger="pyrit"), + pytest.raises(FindingPublisherUnavailableError, match="Couldn't get a valid Azure DevOps token") as raised, + ): + await _publisher(token_provider=AsyncMock(return_value=token)).preview_async( + selection=_selection(), fields=FIELDS, destination="12345" + ) + + assert not ado.calls + assert TOKEN not in "".join(traceback.format_exception(raised.value)) + assert TOKEN not in caplog.text + + +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 PyRIT 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\r\ntext\x07", "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 <b> (Partial)
      Two & steps" + "
      Steps: Step <img src=x> (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( + "link", + [ + "ftp://copyrit.example.com/run", + "https://copyrit.example.com/a b", + "https://copyrit.example.com/a\tb", + " https://copyrit.example.com/run", + "java\nscript:alert(1)", + "JavaScript:alert(1)", + "//copyrit.example.com/run", + "https:///run", + ], +) +async def test_publish_writes_evidence_without_a_link_unless_it_is_an_absolute_web_link( + link: str, destination_route: respx.Route, create_route: respx.Route +) -> None: + finding = _finding() + evidence = (_resolved(finding, objective="Run", conversation_id="run", source_operation_id=OPERATION_ID),) + + await _publisher().publish_async( + selection=_selection(finding, evidence={finding.id: evidence}), + fields=FIELDS, + destination="12345", + link_for=lambda target: link, + ) + + assert _sent_fields(create_route.calls.last.request)["Custom.Evidence"] == ( + "
    • Run
      Outcome: Success · Score: Not scored
    " + ) + + +@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=""), "an unknown requester", None), + (None, "an unknown requester", 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 PyRIT 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