From 162c6a3552c32ad48b52511ea0ca4fb47bd20b02 Mon Sep 17 00:00:00 2001 From: Hannah Westra Date: Fri, 4 Dec 2026 11:26:28 -0500 Subject: [PATCH 01/22] FEAT: Gather an Operation's selected findings in pyrit.output Move reading a finding selection from the backend into pyrit/output/finding_report/selection.py, so export, the planned findings publisher, and notebooks share one builder (step 2b of the Azure DevOps findings publisher design). - build_finding_selection_async follows export's existing steps in the same order, with an optional max_findings cap and a link_for callback. resolve_finding_evidence_async returns domain types and reads evidence in batches of 500. - report.py adds FindingSelection and FindingReportEntry.finding_id. - Export passes its dashboard link builder as link_for. The export route maps FindingSelectionNotFoundError to 404 and keeps its 422 text. The evidence page maps resolved evidence with ScoreView.from_domain, so neither changes. - Remove the OperationService methods that only export used, and move their tests to the library. - Document building a report from a selection in the output guide. Co-Authored-By: Claude Opus 5.5 --- doc/code/output/0_output.ipynb | 33 ++ doc/code/output/0_output.py | 28 ++ pyrit/backend/routes/operations.py | 17 +- pyrit/backend/services/finding_export.py | 102 ++---- pyrit/backend/services/operation_service.py | 200 ++--------- pyrit/output/__init__.py | 17 + pyrit/output/finding_report/report.py | 22 +- pyrit/output/finding_report/selection.py | 281 ++++++++++++++++ tests/unit/backend/test_finding_export.py | 99 +----- tests/unit/backend/test_operations.py | 129 +------- .../unit/output/finding_report/test_report.py | 31 +- .../output/finding_report/test_selection.py | 312 ++++++++++++++++++ 12 files changed, 792 insertions(+), 479 deletions(-) create mode 100644 pyrit/output/finding_report/selection.py create mode 100644 tests/unit/output/finding_report/test_selection.py diff --git a/doc/code/output/0_output.ipynb b/doc/code/output/0_output.ipynb index e828edaa7d..18b5097f88 100644 --- a/doc/code/output/0_output.ipynb +++ b/doc/code/output/0_output.ipynb @@ -763,6 +763,39 @@ "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 a report from the\n", + "selection and print it with `output_finding_report_async`:\n", + "\n", + "```python\n", + "from pyrit.output import build_finding_selection_async, output_finding_report_async\n", + "from pyrit.output.finding_report.report import build_finding_report\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", + "report = build_finding_report(\n", + " operation_name=selection.operation_name,\n", + " findings=selection.findings,\n", + " fields=fields,\n", + " evidence=selection.evidence,\n", + " part_of=selection.part_of,\n", + ")\n", + "await output_finding_report_async(report)\n", + "```\n", + "\n", + "Pass `link_for` to link each piece of evidence whose conversation can be opened, for example to\n", + "your dashboard. Without it, the report lists evidence without links, as unavailable. Pass\n", + "`max_findings` to cap the selection, counting sub-findings." + ] + }, { "cell_type": "markdown", "id": "19", diff --git a/doc/code/output/0_output.py b/doc/code/output/0_output.py index cafafaef5c..5eae5d7f97 100644 --- a/doc/code/output/0_output.py +++ b/doc/code/output/0_output.py @@ -247,6 +247,34 @@ # 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 a report from the +# selection and print it with `output_finding_report_async`: +# +# ```python +# from pyrit.output import build_finding_selection_async, output_finding_report_async +# from pyrit.output.finding_report.report import build_finding_report +# 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) +# report = build_finding_report( +# operation_name=selection.operation_name, +# findings=selection.findings, +# fields=fields, +# evidence=selection.evidence, +# part_of=selection.part_of, +# ) +# await output_finding_report_async(report) +# ``` +# +# Pass `link_for` to link each piece of evidence whose conversation can be opened, for example to +# your dashboard. Without it, the report lists evidence without links, as unavailable. Pass +# `max_findings` to cap the selection, counting sub-findings. + # %% [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..0f8730950a 100644 --- a/pyrit/backend/services/finding_export.py +++ b/pyrit/backend/services/finding_export.py @@ -22,16 +22,12 @@ 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_selection_async from pyrit.output.finding_report.markdown import MarkdownFindingReportPrinter from pyrit.output.finding_report.report import ( DETAIL_SEPARATOR, @@ -52,8 +48,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 +68,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 +80,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 +108,24 @@ 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( + fields = get_active_finding_fields() + selection = await build_finding_selection_async( operation_id=operation_id, - finding_ids=list( - {finding.parent_finding_id for finding in included if finding.parent_finding_id} - finding_ids - ), + finding_ids=request.finding_ids, + fields=fields, + link_for=partial(_conversation_link, dashboard_origin=request.dashboard_origin), + 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)), + operation_name=selection.operation_name, + findings=selection.findings, + fields=fields, + evidence=selection.evidence, + part_of=selection.part_of, ) - 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 +134,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)}" diff --git a/pyrit/backend/services/operation_service.py b/pyrit/backend/services/operation_service.py index 54fcf0c598..7503a59d2f 100644 --- a/pyrit/backend/services/operation_service.py +++ b/pyrit/backend/services/operation_service.py @@ -26,8 +26,6 @@ from pyrit.memory import CentralMemory from pyrit.memory.memory_interface import FindingHierarchyError from pyrit.models import ( - AttackResult, - AttackResultSelection, Finding, FindingCreate, FindingEvidence, @@ -36,11 +34,9 @@ OperationCreate, is_finding_path_complete, ) +from pyrit.output import ResolvedFindingEvidence, resolve_finding_evidence_async 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,13 @@ async def list_finding_evidence_async( finding_id=finding_id, limit=limit + 1, offset=offset ) has_more = len(evidence) > limit + resolved = await resolve_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 +497,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/output/__init__.py b/pyrit/output/__init__.py index dc7847952b..9a2f5ce535 100644 --- a/pyrit/output/__init__.py +++ b/pyrit/output/__init__.py @@ -10,6 +10,7 @@ - **PrinterBase** that all printers inherit from - Domain printers for attack results, scenario results, and scorer information - **Convenience functions** (e.g., ``output_attack_async``) +- **Finding selection** (``build_finding_selection_async``), which gathers an Operation's findings for a report 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 +22,15 @@ if TYPE_CHECKING: from pyrit.output.base import PrinterBase + from pyrit.output.finding_report.report import FindingSelection + from pyrit.output.finding_report.selection import ( + FindingEvidenceLinkTarget, + FindingSelectionNotFoundError, + FindingSelectionTooLargeError, + ResolvedFindingEvidence, + build_finding_selection_async, + resolve_finding_evidence_async, + ) from pyrit.output.helpers import ( output_attack_async, output_conversation_async, @@ -37,7 +47,12 @@ from pyrit.output.sink import FileSink, IPythonMarkdownSink, OutputFormat, Sink, StdoutSink, get_default_sink _LAZY_EXPORTS: dict[str, str | tuple[str, str | None]] = { + "build_finding_selection_async": "pyrit.output.finding_report.selection", "FileSink": "pyrit.output.sink", + "FindingEvidenceLinkTarget": "pyrit.output.finding_report.selection", + "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", @@ -53,6 +68,8 @@ "output_scorer_async": "pyrit.output.helpers", "output_scorer_selection_report_async": "pyrit.output.helpers", "PrinterBase": "pyrit.output.base", + "resolve_finding_evidence_async": "pyrit.output.finding_report.selection", + "ResolvedFindingEvidence": "pyrit.output.finding_report.selection", "Sink": "pyrit.output.sink", "StdoutSink": "pyrit.output.sink", } diff --git a/pyrit/output/finding_report/report.py b/pyrit/output/finding_report/report.py index c091c22ef9..da5054414e 100644 --- a/pyrit/output/finding_report/report.py +++ b/pyrit/output/finding_report/report.py @@ -5,7 +5,7 @@ import re from collections.abc import Mapping, Sequence -from dataclasses import dataclass, replace +from dataclasses import dataclass, field, replace from enum import StrEnum from uuid import UUID @@ -109,7 +109,8 @@ 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. """ title: str @@ -120,6 +121,7 @@ class FindingReportEntry: demonstrated: bool = True paths: tuple[FindingReportPath, ...] = () children: tuple["FindingReportEntry", ...] = () + finding_id: UUID | None = None @property def heading(self) -> str: @@ -140,6 +142,21 @@ class FindingReport: findings: tuple[FindingReportEntry, ...] +@dataclass(frozen=True) +class FindingSelection: + """ + An Operation's selected findings with their evidence: the inputs of ``build_finding_report``. + + ``evidence`` is keyed by finding ID, and ``part_of`` holds the titles of parents outside the selection, keyed by + the parent's ID. Missing evidence means none, so a selection can be built from findings alone. + """ + + operation_name: str + findings: tuple[Finding, ...] + evidence: Mapping[UUID, tuple[FindingReportEvidence, ...]] = field(default_factory=dict) + part_of: Mapping[UUID, str] = field(default_factory=dict) + + def finding_report_entry( *, finding: FindingCreate, fields: FindingFields, evidence: Sequence[FindingReportEvidence] = () ) -> FindingReportEntry: @@ -249,6 +266,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..97358b14ed --- /dev/null +++ b/pyrit/output/finding_report/selection.py @@ -0,0 +1,281 @@ +# 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 Callable, Sequence +from dataclasses import dataclass +from uuid import UUID + +from pyrit.models import ( + AttackOutcome, + AttackResult, + AttackResultSelection, + FindingEvidence, + FindingFields, + Score, + ScoreStatus, +) +from pyrit.output.finding_report.report import FindingReportEvidence, FindingReportField, FindingSelection + +# Keeps every ID list a batch reads within SQL Server's 2100-parameter limit. +_EVIDENCE_BATCH_SIZE = 500 +_HUMAN_SCORER = "ManualScorer" +_UNKNOWN_SCORER = "Unknown" +_BOOLEAN_SCORES = {"true": "True", "false": "False"} + + +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 + + +@dataclass(frozen=True) +class ResolvedFindingEvidence: + """ + 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. + """ + + 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 + + +@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 + + +async def resolve_finding_evidence_async(*, 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), _EVIDENCE_BATCH_SIZE): + resolved.extend(await _resolve_batch_async(evidence=evidence[start : start + _EVIDENCE_BATCH_SIZE])) + return resolved + + +async def build_finding_selection_async( + *, + operation_id: UUID, + finding_ids: Sequence[UUID], + fields: FindingFields, + link_for: Callable[[FindingEvidenceLinkTarget], str] | None = None, + 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 appears as + its attack's objective, outcome, and score, newest link first. + + 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. + link_for (Callable[[FindingEvidenceLinkTarget], str] | None): Builds the link for evidence whose + conversation can be opened. Defaults to None, for evidence without links. + 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 resolve_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} + evidence = { + finding.id: tuple( + _project_evidence(resolved=by_id[item.id], operation_id=operation_id, link_for=link_for) + for item in linked.get(finding.id, []) + ) + for finding in findings + } + 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_name=operation.name, + findings=tuple(findings), + evidence=evidence, + part_of={parent.id: parent.title for parent in parents}, + ) + + +async def _resolve_batch_async(*, evidence: Sequence[FindingEvidence]) -> list[ResolvedFindingEvidence]: + from pyrit.memory import CentralMemory + + 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 _score_conversations_async(attacks=attacks) + stats = await memory.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(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 _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. + """ + from pyrit.memory import CentralMemory + + 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 + + +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 + ) + 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 selection'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) + + +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})" diff --git a/tests/unit/backend/test_finding_export.py b/tests/unit/backend/test_finding_export.py index 8a7efd861e..6e936f7236 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, @@ -565,6 +561,7 @@ async def test_report_selects_findings_beyond_the_first_dashboard_page_in_dashbo ), ), number="1", + finding_id=named["Critical finding"].id, ), FindingReportEntry( title="Included finding", @@ -572,6 +569,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 +577,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 +601,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") @@ -740,6 +695,7 @@ def make_score(*, conversation_id: str, scorer: str, value: str) -> Score: ), ), number="1", + finding_id=finding.id, ), ) @@ -833,6 +789,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", @@ -847,6 +804,7 @@ async def test_report_projects_optional_and_custom_fields(sqlite_instance: SQLit ), ), number="2", + finding_id=custom.id, ), ) @@ -865,28 +823,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( @@ -1027,20 +967,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 +1187,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/output/finding_report/test_report.py b/tests/unit/output/finding_report/test_report.py index cbf5aef9b2..88862ebd4f 100644 --- a/tests/unit/output/finding_report/test_report.py +++ b/tests/unit/output/finding_report/test_report.py @@ -1,12 +1,16 @@ # Copyright (c) Microsoft Corporation. # Licensed under the MIT license. -from pyrit.models import FindingCreate, FindingField, FindingFields +from datetime import UTC, datetime, timedelta +from uuid import uuid4 + +from pyrit.models import Finding, FindingCreate, FindingField, FindingFields from pyrit.output.finding_report.report import ( FindingReportColumn, FindingReportEntry, FindingReportEvidence, FindingReportField, + build_finding_report, finding_report_entry, ) @@ -71,3 +75,28 @@ def test_finding_report_entry_places_fields_by_type_and_retired_values_last() -> ), evidence=(EVIDENCE,), ) + + +def test_build_finding_report_identifies_each_entry_by_its_finding() -> None: + operation_id = uuid4() + created = datetime(2026, 11, 6, tzinfo=UTC) + root = Finding(operation_id=operation_id, title="Root", severity="sev1", created_at=created) + child = Finding( + operation_id=operation_id, + title="Child", + severity="sev2", + parent_finding_id=root.id, + created_at=created + timedelta(minutes=1), + ) + + report = build_finding_report( + operation_name="Synthetic evaluation", + findings=[root, child], + fields=FIELDS, + evidence={root.id: (), child.id: ()}, + part_of={}, + ) + + (entry,) = report.findings + assert (entry.finding_id, entry.number) == (root.id, "1") + assert [(sub.finding_id, sub.number) for sub in entry.children] == [(child.id, "1.1")] diff --git a/tests/unit/output/finding_report/test_selection.py b/tests/unit/output/finding_report/test_selection.py new file mode 100644 index 0000000000..3d154bcea3 --- /dev/null +++ b/tests/unit/output/finding_report/test_selection.py @@ -0,0 +1,312 @@ +# 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, + ComponentIdentifier, + Finding, + FindingEvidence, + Message, + MessagePiece, + Operation, + Score, +) +from pyrit.output import ( + FindingEvidenceLinkTarget, + FindingSelection, + FindingSelectionNotFoundError, + FindingSelectionTooLargeError, + ResolvedFindingEvidence, + build_finding_selection_async, + resolve_finding_evidence_async, +) +from pyrit.output.finding_report import selection +from pyrit.output.finding_report.report import FindingReportEvidence, FindingReportField +from pyrit.setup.finding_fields import get_active_finding_fields + +pytestmark = pytest.mark.usefixtures("patch_central_database") + +MISSING_ID = UUID(int=404) +NOT_SCORED = FindingReportField(label="Score", value="Not scored") + + +async def _add_attack_async(*, memory: SQLiteMemory, conversation_id: str, **fields: object) -> AttackResult: + attack = AttackResult(conversation_id=conversation_id, objective=conversation_id, **fields) + await memory.add_attack_results_to_memory_async(attack_results=[attack]) + await memory.add_message_to_memory_async( + request=Message( + message_pieces=[MessagePiece(role="user", original_value=conversation_id, conversation_id=conversation_id)] + ) + ) + return attack + + +async def _link_async(*, memory: SQLiteMemory, finding: Finding, attack_result_id: str | UUID) -> FindingEvidence: + return await memory.add_finding_evidence_async( + evidence=FindingEvidence(finding_id=finding.id, attack_result_id=UUID(str(attack_result_id))) + ) + + +@pytest.fixture +async def selected_findings_async(sqlite_instance: SQLiteMemory) -> tuple[Operation, list[Finding]]: + """Save a low, a critical, and a moderate finding, each with two available pieces of evidence.""" + 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): + attack = await _add_attack_async( + memory=sqlite_instance, conversation_id=f"{severity}-{index}", operation_id=operation.id + ) + await _link_async(memory=sqlite_instance, finding=finding, attack_result_id=attack.attack_result_id) + findings.append(finding) + return operation, findings + + +async def _select_async(*, operation_id: UUID, finding_ids: list[UUID], **kwargs: object) -> FindingSelection: + return await build_finding_selection_async( + operation_id=operation_id, finding_ids=finding_ids, fields=get_active_finding_fields(), **kwargs + ) + + +async def test_build_finding_selection_reads_findings_once_in_listing_order( + sqlite_instance: SQLiteMemory, selected_findings_async: tuple[Operation, list[Finding]] +) -> None: + operation, findings = selected_findings_async + finding_ids = [finding.id for finding in findings] + with ( + patch.object( + sqlite_instance, "get_finding_subtrees_async", wraps=sqlite_instance.get_finding_subtrees_async + ) as subtrees, + 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", side_effect=AssertionError("paged evidence read")), + patch.object(sqlite_instance, "get_findings_async", side_effect=AssertionError("paged findings read")), + ): + selected = await _select_async(operation_id=operation.id, finding_ids=finding_ids) + + subtrees.assert_called_once() + assert subtrees.call_args.kwargs["finding_ids"] == finding_ids + owners.assert_called_once() + stats.assert_called_once() + assert selected.operation_name == "Selected" + assert [finding.title for finding in selected.findings] == ["Critical", "Moderate", "Low"] + assert {finding_id: len(items) for finding_id, items in selected.evidence.items()} == dict.fromkeys(finding_ids, 2) + assert selected.part_of == {} + + +async def test_build_finding_selection_names_parents_outside_the_selection(sqlite_instance: SQLiteMemory) -> None: + operation = await sqlite_instance.add_operation_async(Operation(name="Nested")) + parent = await sqlite_instance.add_finding_async( + finding=Finding(operation_id=operation.id, title="Parent", severity="low") + ) + child = await sqlite_instance.add_finding_async( + finding=Finding(operation_id=operation.id, title="Child", severity="low", parent_finding_id=parent.id) + ) + grandchild = await sqlite_instance.add_finding_async( + finding=Finding(operation_id=operation.id, title="Grandchild", severity="low", parent_finding_id=child.id) + ) + + selected = await _select_async(operation_id=operation.id, finding_ids=[child.id]) + + assert {finding.id for finding in selected.findings} == {child.id, grandchild.id} + assert selected.evidence == {child.id: (), grandchild.id: ()} + assert selected.part_of == {parent.id: "Parent"} + + +async def test_build_finding_selection_rejects_missing_and_foreign_findings( + 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() + for finding_ids, named in [([findings[0].id, foreign.id, unknown], foreign.id), ([unknown, foreign.id], unknown)]: + with pytest.raises( + FindingSelectionNotFoundError, match=f"Finding '{named}' not found in operation '{operation.id}'" + ): + await _select_async(operation_id=operation.id, finding_ids=finding_ids) + with pytest.raises(FindingSelectionNotFoundError, match=f"Operation '{MISSING_ID}' not found."): + await _select_async(operation_id=MISSING_ID, finding_ids=[findings[0].id]) + + +async def test_build_finding_selection_counts_sub_findings_before_reading_evidence( + sqlite_instance: SQLiteMemory, +) -> None: + operation = await sqlite_instance.add_operation_async(Operation(name="Capped")) + parent = await sqlite_instance.add_finding_async( + finding=Finding(operation_id=operation.id, title="Parent", severity="low") + ) + await sqlite_instance.add_finding_async( + finding=Finding(operation_id=operation.id, title="Child", severity="low", parent_finding_id=parent.id) + ) + + within = await _select_async(operation_id=operation.id, finding_ids=[parent.id], max_findings=2) + with ( + patch.object( + sqlite_instance, + "get_finding_evidence_for_findings_async", + side_effect=AssertionError("evidence read"), + ), + pytest.raises(FindingSelectionTooLargeError, match="Select at most 1 findings") as raised, + ): + await _select_async(operation_id=operation.id, finding_ids=[parent.id], max_findings=1) + + assert len(within.findings) == 2 + assert raised.value.max_findings == 1 + + +async def test_build_finding_selection_links_only_available_evidence_with_a_conversation( + sqlite_instance: SQLiteMemory, +) -> None: + operation = await sqlite_instance.add_operation_async(Operation(name="Links")) + finding = await sqlite_instance.add_finding_async( + finding=Finding(operation_id=operation.id, title="Linked", severity="low") + ) + scenario_result_id = uuid4() + available = await _add_attack_async( + memory=sqlite_instance, + conversation_id="main", + operation_id=operation.id, + outcome=AttackOutcome.SUCCESS, + attribution_parent_id=str(scenario_result_id), + ) + messageless = AttackResult(conversation_id="nothing-saved", objective="Messageless", operation_id=operation.id) + await sqlite_instance.add_attack_results_to_memory_async(attack_results=[messageless]) + gone = uuid4() + linked = await _link_async(memory=sqlite_instance, finding=finding, attack_result_id=available.attack_result_id) + await _link_async(memory=sqlite_instance, finding=finding, attack_result_id=messageless.attack_result_id) + await _link_async(memory=sqlite_instance, finding=finding, attack_result_id=gone) + targets: list[FindingEvidenceLinkTarget] = [] + + def link_for(target: FindingEvidenceLinkTarget) -> str: + targets.append(target) + return f"link-{len(targets)}" + + with_links = await _select_async(operation_id=operation.id, finding_ids=[finding.id], link_for=link_for) + without_links = await _select_async(operation_id=operation.id, finding_ids=[finding.id]) + + assert targets == [ + FindingEvidenceLinkTarget( + evidence_id=linked.id, + attack_result_id=UUID(available.attack_result_id), + conversation_id="main", + scenario_result_id=scenario_result_id, + ) + ] + assert set(with_links.evidence[finding.id]) == { + FindingReportEvidence( + title="main", + summary=(FindingReportField(label="Outcome", value="Success"), NOT_SCORED), + details=(), + link_url="link-1", + ), + FindingReportEvidence( + title="Messageless", + summary=(FindingReportField(label="Outcome", value="Undetermined"), NOT_SCORED), + details=(), + link_url=None, + ), + FindingReportEvidence(title=str(gone), summary=(), details=(), link_url=None), + } + assert all(evidence.link_url is None for evidence in without_links.evidence[finding.id]) + + +async def test_resolve_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 resolve_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_resolve_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")]) + ) + evidence = [ + FindingEvidence(finding_id=uuid4(), attack_result_id=UUID(attack.attack_result_id)) for attack in attacks + ] + + resolved = await resolve_finding_evidence_async(evidence=evidence) + + assert [(item.objective, item.available) for item in resolved] == [("First run", True), ("Second run", True)] + + +async def test_resolve_finding_evidence_reads_in_batches( + sqlite_instance: SQLiteMemory, selected_findings_async: tuple[Operation, list[Finding]] +) -> None: + _, findings = selected_findings_async + linked = await sqlite_instance.get_finding_evidence_for_findings_async( + finding_ids=[finding.id for finding in findings] + ) + evidence = [item for items in linked.values() for item in items] + unbatched = await resolve_finding_evidence_async(evidence=evidence) + with ( + patch.object(selection, "_EVIDENCE_BATCH_SIZE", 2), + patch.object( + sqlite_instance, "get_attack_results_async", wraps=sqlite_instance.get_attack_results_async + ) as owners, + ): + batched = await resolve_finding_evidence_async(evidence=evidence) + + assert len(evidence) == 6 + assert batched == unbatched + assert [item.evidence for item in batched] == evidence + assert owners.call_count == 3 + + +@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 selection._score_text(score) == expected From 9184c4de81120dfcc661436a0650b2d7383a8878 Mon Sep 17 00:00:00 2001 From: Hannah Westra Date: Fri, 4 Dec 2026 11:45:02 -0500 Subject: [PATCH 02/22] FIX: Keep evidence availability in finding reports built without links A notebook report built without link_for showed intact evidence as "Evidence unavailable", because availability was derived from the link. Its opening note also promised dashboard links that the report didn't have. - FindingReportEvidence gains a required available flag, which selection sets from the resolved evidence. unavailable now reads that flag. - The opening note leaves out the dashboard clause when available evidence is listed without links. Every export links its available evidence, so export output is unchanged. - build_finding_report treats a finding without an evidence entry as having none, so a FindingSelection built from findings alone works. - Keep resolve_finding_evidence_async and ResolvedFindingEvidence module-level. Only the backend evidence page uses them. - Correct the output guide's sentence about reports without links. Co-Authored-By: Claude Opus 5.5 --- doc/code/output/0_output.ipynb | 2 +- doc/code/output/0_output.py | 2 +- pyrit/backend/services/finding_export.py | 3 +- pyrit/backend/services/operation_service.py | 2 +- pyrit/output/__init__.py | 4 -- pyrit/output/finding_report/markdown.py | 3 +- pyrit/output/finding_report/report.py | 26 +++++++-- pyrit/output/finding_report/selection.py | 10 +++- tests/unit/backend/test_finding_export.py | 13 ++++- .../output/finding_report/test_markdown.py | 11 +++- .../unit/output/finding_report/test_report.py | 55 ++++++++++++++++++- .../output/finding_report/test_selection.py | 54 ++++++++++++++++-- 12 files changed, 158 insertions(+), 27 deletions(-) diff --git a/doc/code/output/0_output.ipynb b/doc/code/output/0_output.ipynb index 18b5097f88..f2ca551daa 100644 --- a/doc/code/output/0_output.ipynb +++ b/doc/code/output/0_output.ipynb @@ -792,7 +792,7 @@ "```\n", "\n", "Pass `link_for` to link each piece of evidence whose conversation can be opened, for example to\n", - "your dashboard. Without it, the report lists evidence without links, as unavailable. Pass\n", + "your dashboard. Without it, the report lists evidence without links. Pass\n", "`max_findings` to cap the selection, counting sub-findings." ] }, diff --git a/doc/code/output/0_output.py b/doc/code/output/0_output.py index 5eae5d7f97..13165cdbe5 100644 --- a/doc/code/output/0_output.py +++ b/doc/code/output/0_output.py @@ -272,7 +272,7 @@ # ``` # # Pass `link_for` to link each piece of evidence whose conversation can be opened, for example to -# your dashboard. Without it, the report lists evidence without links, as unavailable. Pass +# your dashboard. Without it, the report lists evidence without links. Pass # `max_findings` to cap the selection, counting sub-findings. # %% [markdown] diff --git a/pyrit/backend/services/finding_export.py b/pyrit/backend/services/finding_export.py index 0f8730950a..01743ae94b 100644 --- a/pyrit/backend/services/finding_export.py +++ b/pyrit/backend/services/finding_export.py @@ -31,7 +31,6 @@ from pyrit.output.finding_report.markdown import MarkdownFindingReportPrinter from pyrit.output.finding_report.report import ( DETAIL_SEPARATOR, - EVIDENCE_NOTE, NO_EVIDENCE, UNAVAILABLE_EVIDENCE, FindingReport, @@ -152,7 +151,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 7503a59d2f..7dd5dd0855 100644 --- a/pyrit/backend/services/operation_service.py +++ b/pyrit/backend/services/operation_service.py @@ -34,7 +34,7 @@ OperationCreate, is_finding_path_complete, ) -from pyrit.output import ResolvedFindingEvidence, resolve_finding_evidence_async +from pyrit.output.finding_report.selection import ResolvedFindingEvidence, resolve_finding_evidence_async from pyrit.setup.finding_fields import get_active_finding_fields diff --git a/pyrit/output/__init__.py b/pyrit/output/__init__.py index 9a2f5ce535..c493f07967 100644 --- a/pyrit/output/__init__.py +++ b/pyrit/output/__init__.py @@ -27,9 +27,7 @@ FindingEvidenceLinkTarget, FindingSelectionNotFoundError, FindingSelectionTooLargeError, - ResolvedFindingEvidence, build_finding_selection_async, - resolve_finding_evidence_async, ) from pyrit.output.helpers import ( output_attack_async, @@ -68,8 +66,6 @@ "output_scorer_async": "pyrit.output.helpers", "output_scorer_selection_report_async": "pyrit.output.helpers", "PrinterBase": "pyrit.output.base", - "resolve_finding_evidence_async": "pyrit.output.finding_report.selection", - "ResolvedFindingEvidence": "pyrit.output.finding_report.selection", "Sink": "pyrit.output.sink", "StdoutSink": "pyrit.output.sink", } 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 da5054414e..e4313cb35b 100644 --- a/pyrit/output/finding_report/report.py +++ b/pyrit/output/finding_report/report.py @@ -20,6 +20,7 @@ ) 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" @@ -55,18 +56,20 @@ 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. """ title: str summary: tuple[FindingReportField, ...] details: tuple[FindingReportField, ...] link_url: str | None + available: bool @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.""" + return not self.available @dataclass(frozen=True) @@ -141,6 +144,18 @@ class FindingReport: operation_name: str findings: tuple[FindingReportEntry, ...] + @property + def evidence_note(self) -> str: + """The report's opening note. It mentions dashboard links unless available evidence is listed without one.""" + # Depth-first without recursion, so a deep decomposition cannot exhaust the stack. + pending = list(self.findings) + while pending: + entry = pending.pop() + if any(item.available and item.link_url is None for item in entry.evidence): + return UNLINKED_EVIDENCE_NOTE + pending.extend(entry.children) + return EVIDENCE_NOTE + @dataclass(frozen=True) class FindingSelection: @@ -209,7 +224,8 @@ def build_finding_report( operation_name (str): The report's operation name. findings (Sequence[Finding]): Complete selected subtrees, without repeated findings. fields (FindingFields): The finding fields that label each finding's values. - evidence (Mapping[UUID, tuple[FindingReportEvidence, ...]]): Projected evidence for each finding. + evidence (Mapping[UUID, tuple[FindingReportEvidence, ...]]): Projected evidence for each finding. A + finding without an entry has no evidence. part_of (Mapping[UUID, str]): Titles of parents outside the selected subtrees. Returns: @@ -252,7 +268,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( diff --git a/pyrit/output/finding_report/selection.py b/pyrit/output/finding_report/selection.py index 97358b14ed..79edc13c9e 100644 --- a/pyrit/output/finding_report/selection.py +++ b/pyrit/output/finding_report/selection.py @@ -241,7 +241,7 @@ def _project_evidence( 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 + 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 = ( @@ -266,7 +266,13 @@ def _project_evidence( scenario_result_id=resolved.scenario_result_id, ) ) - return FindingReportEvidence(title=objective, summary=summary, details=tuple(details), link_url=link_url) + return FindingReportEvidence( + title=objective, + summary=summary, + details=tuple(details), + link_url=link_url, + available=resolved.available, + ) def _score_text(score: Score | None) -> str: diff --git a/tests/unit/backend/test_finding_export.py b/tests/unit/backend/test_finding_export.py index 6e936f7236..f2a180e673 100644 --- a/tests/unit/backend/test_finding_export.py +++ b/tests/unit/backend/test_finding_export.py @@ -558,6 +558,7 @@ 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", @@ -629,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) } @@ -692,6 +694,7 @@ 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", @@ -731,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, ), ) @@ -750,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, ), } @@ -801,6 +806,7 @@ 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", @@ -848,14 +854,16 @@ async def test_report_labels_findings_with_the_active_fields(sqlite_instance: SQ ), 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( @@ -922,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", diff --git a/tests/unit/output/finding_report/test_markdown.py b/tests/unit/output/finding_report/test_markdown.py index b28ddbc2fe..60306ac0e9 100644 --- a/tests/unit/output/finding_report/test_markdown.py +++ b/tests/unit/output/finding_report/test_markdown.py @@ -46,14 +46,16 @@ ), 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( @@ -178,6 +180,7 @@ async def test_multi_line_values_stay_prose() -> None: summary=(FindingReportField(label="Outcome", value="Success"), NOT_SCORED), details=(FindingReportField(label="Rationale", value="one\n\ntwo"),), link_url=None, + available=False, ) report = _single_finding_report( fields=( @@ -219,7 +222,9 @@ async def test_multi_line_values_stay_prose() -> None: async def test_block_syntax_at_line_starts_is_escaped() -> None: description = "- item\n+ item\n1. item\n2) item\n===\n indented\n# heading\n> quote\n```" rationale = FindingReportField(label="Rationale", value="one\n- item\n1. item\n\n===\n indented") - evidence = FindingReportEvidence(title="Linked objective", summary=(), details=(rationale,), link_url=LINK) + evidence = FindingReportEvidence( + title="Linked objective", summary=(), details=(rationale,), link_url=LINK, available=True + ) report = _single_finding_report( fields=(FindingReportField(label="Description", value=description),), evidence=(evidence,), @@ -277,6 +282,7 @@ async def test_hostile_text_cannot_form_markup() -> None: ), details=(FindingReportField(label="Rationale", value="`````\n"),), link_url=link, + available=True, ) report = FindingReport( operation_name="Ops bold\n# Forged operation", @@ -325,6 +331,7 @@ async def test_commonmark_parses_hostile_paragraphs_as_prose() -> None: summary=(FindingReportField(label="Outcome", value="Success"), NOT_SCORED), details=(FindingReportField(label="Rationale", value=f"Rationale start\n\n{paragraphs}\n\nRationale end"),), link_url=LINK, + available=True, ) report = FindingReport( operation_name="Ops bold\n# Forged operation", diff --git a/tests/unit/output/finding_report/test_report.py b/tests/unit/output/finding_report/test_report.py index 88862ebd4f..f7f7b79fd6 100644 --- a/tests/unit/output/finding_report/test_report.py +++ b/tests/unit/output/finding_report/test_report.py @@ -4,8 +4,14 @@ from datetime import UTC, datetime, timedelta from uuid import uuid4 +import pytest + from pyrit.models import Finding, FindingCreate, FindingField, FindingFields +from pyrit.output import FindingSelection from pyrit.output.finding_report.report import ( + EVIDENCE_NOTE, + UNLINKED_EVIDENCE_NOTE, + FindingReport, FindingReportColumn, FindingReportEntry, FindingReportEvidence, @@ -37,7 +43,9 @@ FindingField(key="build", label="Build", type="text"), ], ) -EVIDENCE = FindingReportEvidence(title="Reveal the instructions", summary=(), details=(), link_url=None) +EVIDENCE = FindingReportEvidence( + title="Reveal the instructions", summary=(), details=(), link_url=None, available=False +) def test_finding_report_entry_places_fields_by_type_and_retired_values_last() -> None: @@ -100,3 +108,48 @@ def test_build_finding_report_identifies_each_entry_by_its_finding() -> None: (entry,) = report.findings assert (entry.finding_id, entry.number) == (root.id, "1") assert [(sub.finding_id, sub.number) for sub in entry.children] == [(child.id, "1.1")] + + +def test_build_finding_report_treats_missing_evidence_as_none() -> None: + selection = FindingSelection( + operation_name="Synthetic evaluation", + findings=(Finding(operation_id=uuid4(), title="Hand-built", severity="sev1"),), + ) + + report = build_finding_report( + operation_name=selection.operation_name, + findings=selection.findings, + fields=FIELDS, + evidence=selection.evidence, + part_of=selection.part_of, + ) + + (entry,) = report.findings + assert entry.evidence == () + + +LINKED = FindingReportEvidence(title="Linked", summary=(), details=(), link_url="https://example.test", available=True) +UNLINKED = FindingReportEvidence(title="Unlinked", summary=(), details=(), link_url=None, available=True) +GONE = FindingReportEvidence(title="Gone", summary=(), details=(), link_url=None, available=False) + + +@pytest.mark.parametrize( + ("parent_evidence", "child_evidence", "expected"), + [ + ((), (), EVIDENCE_NOTE), + ((LINKED,), (GONE,), EVIDENCE_NOTE), + ((LINKED,), (UNLINKED,), UNLINKED_EVIDENCE_NOTE), + ], +) +def test_evidence_note_mentions_dashboard_links_unless_available_evidence_has_none( + parent_evidence: tuple[FindingReportEvidence, ...], + child_evidence: tuple[FindingReportEvidence, ...], + expected: str, +) -> None: + severity = FindingReportField(label="Impact", value="Sev 1") + child = FindingReportEntry(title="Child", severity=severity, fields=(), evidence=child_evidence) + parent = FindingReportEntry( + title="Parent", severity=severity, fields=(), evidence=parent_evidence, children=(child,) + ) + + assert FindingReport(operation_name="Synthetic evaluation", findings=(parent,)).evidence_note == expected diff --git a/tests/unit/output/finding_report/test_selection.py b/tests/unit/output/finding_report/test_selection.py index 3d154bcea3..06e90b564d 100644 --- a/tests/unit/output/finding_report/test_selection.py +++ b/tests/unit/output/finding_report/test_selection.py @@ -24,12 +24,19 @@ FindingSelection, FindingSelectionNotFoundError, FindingSelectionTooLargeError, - ResolvedFindingEvidence, build_finding_selection_async, - resolve_finding_evidence_async, ) from pyrit.output.finding_report import selection -from pyrit.output.finding_report.report import FindingReportEvidence, FindingReportField +from pyrit.output.finding_report.markdown import MarkdownFindingReportPrinter +from pyrit.output.finding_report.report import ( + EVIDENCE_NOTE, + UNAVAILABLE_EVIDENCE, + UNLINKED_EVIDENCE_NOTE, + FindingReportEvidence, + FindingReportField, + build_finding_report, +) +from pyrit.output.finding_report.selection import ResolvedFindingEvidence, resolve_finding_evidence_async from pyrit.setup.finding_fields import get_active_finding_fields pytestmark = pytest.mark.usefixtures("patch_central_database") @@ -216,18 +223,57 @@ def link_for(target: FindingEvidenceLinkTarget) -> str: summary=(FindingReportField(label="Outcome", value="Success"), NOT_SCORED), details=(), link_url="link-1", + available=True, ), FindingReportEvidence( title="Messageless", summary=(FindingReportField(label="Outcome", value="Undetermined"), NOT_SCORED), details=(), link_url=None, + available=False, ), - FindingReportEvidence(title=str(gone), summary=(), details=(), link_url=None), + FindingReportEvidence(title=str(gone), summary=(), details=(), link_url=None, available=False), } assert all(evidence.link_url is None for evidence in without_links.evidence[finding.id]) +@pytest.mark.parametrize("linked", [False, True]) +async def test_finding_report_keeps_available_evidence_available_with_or_without_links( + sqlite_instance: SQLiteMemory, linked: bool +) -> None: + operation = await sqlite_instance.add_operation_async(Operation(name="Notebook")) + finding = await sqlite_instance.add_finding_async( + finding=Finding(operation_id=operation.id, title="Intact", severity="low") + ) + attack = await _add_attack_async( + memory=sqlite_instance, conversation_id="main", operation_id=operation.id, outcome=AttackOutcome.SUCCESS + ) + await _link_async(memory=sqlite_instance, finding=finding, attack_result_id=attack.attack_result_id) + fields = get_active_finding_fields() + selected = await build_finding_selection_async( + operation_id=operation.id, + finding_ids=[finding.id], + fields=fields, + link_for=(lambda target: f"https://pyrit.example.test/{target.evidence_id}") if linked else None, + ) + + report = build_finding_report( + operation_name=selected.operation_name, + findings=selected.findings, + fields=fields, + evidence=selected.evidence, + part_of=selected.part_of, + ) + rendered = await MarkdownFindingReportPrinter().render_async(report) + + ((evidence,),) = selected.evidence.values() + assert evidence.available + assert (evidence.link_url is not None) == linked + assert report.evidence_note == (EVIDENCE_NOTE if linked else UNLINKED_EVIDENCE_NOTE) + assert report.evidence_note in rendered + assert UNAVAILABLE_EVIDENCE not in rendered + + async def test_resolve_finding_evidence_marks_missing_and_messageless_attacks_unavailable( sqlite_instance: SQLiteMemory, ) -> None: From 13e27a21658bf4ed42e990d399e584b9814aca9b Mon Sep 17 00:00:00 2001 From: Hannah Westra Date: Fri, 4 Dec 2026 12:43:16 -0500 Subject: [PATCH 03/22] FEAT: Publish findings through a FindingPublisher contract, with an Azure DevOps adapter Add a destination-neutral FindingPublisher in pyrit.output: preview_async shows where every selected finding would go, and publish_async creates the items, parents first, and reports every finding's outcome exactly once. The pure planner orders findings as the reports do, skips findings that weren't demonstrated and decides nesting; the plan digest lets a publish create only what its preview showed. Errors propagate until the first create; after that, only cancellation escapes. Add the generic, opt-in AzureDevOpsFindingPublisher: REST API 7.1 with a 30-second timeout per request, destinations parsed (never fetched) within the configured organization, JSON Patch creates with a parent link, the requester assigned, and a History note with the run and finding IDs. A 4xx or a connection that never opened is a known failure; a 5xx, a timeout after sending or an unreadable response marks the item as possibly created. Co-Authored-By: Claude Opus 5.5 --- .github/instructions/output.instructions.md | 11 + doc/code/output/0_output.ipynb | 97 ++ doc/code/output/0_output.py | 92 ++ pyrit/models/__init__.py | 24 + pyrit/models/finding_publication.py | 118 +++ pyrit/output/__init__.py | 34 + pyrit/output/finding_publisher/__init__.py | 4 + .../output/finding_publisher/azure_devops.py | 927 ++++++++++++++++++ pyrit/output/finding_publisher/base.py | 394 ++++++++ pyrit/output/finding_publisher/errors.py | 88 ++ pyrit/output/finding_publisher/plan.py | 152 +++ .../finding_publisher/test_azure_devops.py | 838 ++++++++++++++++ .../output/finding_publisher/test_base.py | 380 +++++++ .../output/finding_publisher/test_plan.py | 189 ++++ 14 files changed, 3348 insertions(+) create mode 100644 pyrit/models/finding_publication.py create mode 100644 pyrit/output/finding_publisher/__init__.py create mode 100644 pyrit/output/finding_publisher/azure_devops.py create mode 100644 pyrit/output/finding_publisher/base.py create mode 100644 pyrit/output/finding_publisher/errors.py create mode 100644 pyrit/output/finding_publisher/plan.py create mode 100644 tests/unit/output/finding_publisher/test_azure_devops.py create mode 100644 tests/unit/output/finding_publisher/test_base.py create mode 100644 tests/unit/output/finding_publisher/test_plan.py diff --git a/.github/instructions/output.instructions.md b/.github/instructions/output.instructions.md index dcd227e52b..e77cc80f7b 100644 --- a/.github/instructions/output.instructions.md +++ b/.github/instructions/output.instructions.md @@ -68,3 +68,14 @@ await output_attack_async(result, format="pretty") `helpers.py` resolves `format` → printer class, `sink` → Sink, and calls `write_async`. When reviewing: if a new domain printer is added without a helper function, request one. + +## Publishers + +Finding publishers (`pyrit/output/finding_publisher/`) write findings to another system and return what they created. They aren't printers: they have no sink and no `helpers.py` function, and they never touch `CentralMemory`; callers pass a `FindingSelection`. + +- Subclass `FindingPublisher` and implement `_open_destination_async` and `_create_item_async`. The base class owns planning, value checks, the plan digest, the create loop, outcome accounting and the run summary; don't rebuild them in a subclass. +- Use async I/O, and keep every request within a timeout and the caller's `deadline`. +- Once the base calls `_create_item_async`, every outcome goes in the result and only cancellation escapes. Raise `FindingPublishCreateError` with `outcome_unknown=False` only when nothing was sent or the response proves nothing was created, and never retry a create that might have succeeded. +- Never log tokens, names, emails, titles, field values or the service's message text. + +When reviewing: reject a publisher that lets an exception other than cancellation escape after its first create. diff --git a/doc/code/output/0_output.ipynb b/doc/code/output/0_output.ipynb index f2ca551daa..cef94d7c17 100644 --- a/doc/code/output/0_output.ipynb +++ b/doc/code/output/0_output.ipynb @@ -796,6 +796,103 @@ "`max_findings` to cap the selection, counting sub-findings." ] }, + { + "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\", expected_plan_digest=preview.plan_digest\n", + ")\n", + "```\n", + "\n", + "Pass the preview's `plan_digest` so the publish creates only what the preview showed; if the findings\n", + "or the destination changed, it raises `FindingPublishPlanChangedError` before writing anything.\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", + "Each work item copies its Area and Iteration from the destination, is assigned to the email of\n", + "`requested_by`, and notes the requester, the run ID, and the finding ID in its History. Titles and\n", + "`text` values must fit on one line of at most 255 characters as Azure DevOps counts them; the preview\n", + "lists any that don't, and nothing is shortened.\n", + "\n", + "To publish somewhere else, subclass `FindingPublisher` and implement `_open_destination_async`, which\n", + "reads the destination, and `_create_item_async`, which creates one item. The base class plans the\n", + "items, checks the values, and accounts for every outcome:\n", + "\n", + "```python\n", + "from pyrit.models import ComponentIdentifier, FindingPublishDestination, FindingPublishedItem, FindingPublisherInfo\n", + "from pyrit.output import FindingPublisher\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", + "```" + ] + }, { "cell_type": "markdown", "id": "19", diff --git a/doc/code/output/0_output.py b/doc/code/output/0_output.py index 13165cdbe5..16ca4253cc 100644 --- a/doc/code/output/0_output.py +++ b/doc/code/output/0_output.py @@ -275,6 +275,98 @@ # your dashboard. Without it, the report lists evidence without links. Pass # `max_findings` to cap the selection, counting sub-findings. +# %% [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", expected_plan_digest=preview.plan_digest +# ) +# ``` +# +# Pass the preview's `plan_digest` so the publish creates only what the preview showed; if the findings +# or the destination changed, it raises `FindingPublishPlanChangedError` before writing anything. +# +# `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) +# ``` +# +# Each work item copies its Area and Iteration from the destination, is assigned to the email of +# `requested_by`, and notes the requester, the run ID, and the finding ID in its History. Titles and +# `text` values must fit on one line of at most 255 characters as Azure DevOps counts them; the preview +# lists any that don't, and nothing is shortened. +# +# To publish somewhere else, subclass `FindingPublisher` and implement `_open_destination_async`, which +# reads the destination, and `_create_item_async`, which creates one item. The base class plans the +# items, checks the values, and accounts for every outcome: +# +# ```python +# from pyrit.models import ComponentIdentifier, FindingPublishDestination, FindingPublishedItem, FindingPublisherInfo +# from pyrit.output import FindingPublisher +# +# +# 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, +# ) +# ``` + # %% [markdown] # ## Sinks — Redirecting Output # diff --git a/pyrit/models/__init__.py b/pyrit/models/__init__.py index e81d7711a8..16dc5aa320 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, @@ -586,6 +599,17 @@ "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/output/__init__.py b/pyrit/output/__init__.py index c493f07967..75ced7b9a0 100644 --- a/pyrit/output/__init__.py +++ b/pyrit/output/__init__.py @@ -11,6 +11,8 @@ - Domain printers for attack results, scenario results, and scorer information - **Convenience functions** (e.g., ``output_attack_async``) - **Finding selection** (``build_finding_selection_async``), which gathers an Operation's findings for a report +- **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). @@ -22,6 +24,23 @@ 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 FindingSelection from pyrit.output.finding_report.selection import ( FindingEvidenceLinkTarget, @@ -45,9 +64,23 @@ 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_selection_async": "pyrit.output.finding_report.selection", "FileSink": "pyrit.output.sink", "FindingEvidenceLinkTarget": "pyrit.output.finding_report.selection", + "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", @@ -65,6 +98,7 @@ "output_score_async": "pyrit.output.helpers", "output_scorer_async": "pyrit.output.helpers", "output_scorer_selection_report_async": "pyrit.output.helpers", + "plan_finding_publish": "pyrit.output.finding_publisher.plan", "PrinterBase": "pyrit.output.base", "Sink": "pyrit.output.sink", "StdoutSink": "pyrit.output.sink", diff --git a/pyrit/output/finding_publisher/__init__.py b/pyrit/output/finding_publisher/__init__.py new file mode 100644 index 0000000000..e55474c484 --- /dev/null +++ b/pyrit/output/finding_publisher/__init__.py @@ -0,0 +1,4 @@ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT license. + +"""Finding publishers, which create items for selected findings in other systems.""" diff --git a/pyrit/output/finding_publisher/azure_devops.py b/pyrit/output/finding_publisher/azure_devops.py new file mode 100644 index 0000000000..bc3060e294 --- /dev/null +++ b/pyrit/output/finding_publisher/azure_devops.py @@ -0,0 +1,927 @@ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT license. + +"""Publish findings as Azure DevOps work items under an existing work item.""" + +import asyncio +import html +import json +import logging +import re +import unicodedata +from collections import Counter +from collections.abc import Awaitable, Callable, Collection, Iterator, Mapping +from dataclasses import dataclass +from enum import StrEnum +from time import monotonic +from typing import Any +from urllib.parse import quote, urlsplit + +import httpx + +from pyrit.common.net_utility import get_httpx_client +from pyrit.models import ( + ComponentIdentifier, + FindingField, + FindingFields, + FindingFieldType, + FindingPublishDestination, + FindingPublishedItem, + FindingPublisherInfo, + FindingPublishProblem, + FindingPublishRequester, +) +from pyrit.models.finding_fields import FindingFieldOption +from pyrit.output.finding_publisher.base import FindingPublisher +from pyrit.output.finding_publisher.errors import ( + FindingPublishCreateError, + FindingPublishDeadlineError, + FindingPublishDestinationError, + FindingPublisherConfigurationError, + FindingPublisherUnavailableError, +) +from pyrit.output.finding_publisher.plan import FindingPublishPlan, FindingPublishPlanItem +from pyrit.output.finding_report.report import ( + DETAIL_SEPARATOR, + PATH_STEP_SEPARATOR, + STEP_NOT_DEMONSTRATED, + UNAVAILABLE_EVIDENCE, + FindingReportEvidence, + FindingReportField, + FindingReportPath, + plain_text, +) + +logger = logging.getLogger(__name__) + +_TITLE = "System.Title" +_DESCRIPTION = "System.Description" +_AREA_PATH = "System.AreaPath" +_ITERATION_PATH = "System.IterationPath" +_ASSIGNED_TO = "System.AssignedTo" +_HISTORY = "System.History" +_SET_BY_PUBLISHER = (_TITLE, _AREA_PATH, _ITERATION_PATH, _ASSIGNED_TO, _HISTORY) +_PARENT_LINK = "System.LinkTypes.Hierarchy-Reverse" +_MAX_WORK_ITEM_ID = 2_147_483_647 +_ORGANIZATION = r"[A-Za-z0-9](?:[A-Za-z0-9-]*[A-Za-z0-9])?" +_DEV_AZURE_URL = re.compile(rf"https://dev\.azure\.com/(?P{_ORGANIZATION})/?", re.IGNORECASE) +_VISUAL_STUDIO_URL = re.compile(rf"https://(?P{_ORGANIZATION})\.visualstudio\.com/?", re.IGNORECASE) +_WORK_ITEM_PATH = re.compile(r"/_workitems/edit/([0-9]{1,10})(?:/|$)", re.IGNORECASE) +_SERVICE_CODE = re.compile(r"^(?:TF|VS)[0-9]+") +_RATE_LIMIT_HEADERS = ( + "Retry-After", + "X-RateLimit-Resource", + "X-RateLimit-Delay", + "X-RateLimit-Limit", + "X-RateLimit-Remaining", + "X-RateLimit-Reset", +) + +_TOKEN_MESSAGE = ( + "The server couldn't get an Azure DevOps token for its publishing identity. Ask an administrator to check the " + "deployment's identity." +) +_UNREACHABLE_MESSAGE = "Couldn't reach Azure DevOps. Try again in a few minutes." +_STATUS_MESSAGES = { + 401: ( + "Azure DevOps didn't accept the publishing identity (HTTP 401). Ask an administrator to check that it " + "belongs to the organization." + ), + 403: ( + "The publishing identity isn't allowed to do this in Azure DevOps (HTTP 403). Ask an administrator to check " + "its permissions on the project's area." + ), + 429: "Azure DevOps is throttling the publishing identity (HTTP 429). Try again in a few minutes.", +} + + +class AzureDevOpsFieldKind(StrEnum): + """How a finding value is written to an Azure DevOps field.""" + + HTML = "html" + """Escaped HTML, keeping line breaks.""" + TEXT = "text" + """One line, sent as written.""" + CHOICE = "choice" + """An option key, sent as written, so each key must equal an Azure DevOps value.""" + + +@dataclass(frozen=True) +class AzureDevOpsField: + """An Azure DevOps field that a finding value is written to, such as ``Custom.FindingSeverity``.""" + + reference_name: str + kind: AzureDevOpsFieldKind + + +@dataclass(frozen=True) +class _DestinationContext: + area_path: str + iteration_path: str + + +class _FailureKind(StrEnum): + TOKEN = "token" + UNREACHABLE = "unreachable" + NO_ANSWER = "no_answer" + REJECTED = "rejected" + + +class _RequestFailedError(Exception): + """A request that failed, classified by whether Azure DevOps could have acted on it.""" + + def __init__( + self, + *, + kind: _FailureKind, + detail: str = "", + status: int | None = None, + service_message: str = "", + diagnostics: Mapping[str, str] | None = None, + ) -> None: + super().__init__(kind.value) + self.kind = kind + self.detail = detail + self.status = status + self.service_message = service_message + self.diagnostics: Mapping[str, str] = dict(diagnostics or {}) + + +class AzureDevOpsFindingPublisher(FindingPublisher): + """ + Publishes findings as Azure DevOps work items under an existing work item, through REST API 7.1. + + Each finding becomes a work item of ``work_item_type``, linked as a child of the destination or of its parent + finding's new work item. Its Area and Iteration are copied from the destination, it is assigned to the requester, + and its History notes the requester, the run ID and the finding ID. ``bypassRules`` is never set, so the project's + rules apply. Titles and single-line values are never shortened; a value Azure DevOps can't hold is a problem. + + The constructor does no I/O. Requests use the publishing identity's Azure DevOps token, by default from + ``DefaultAzureCredential``, and each request has at most ``REQUEST_TIMEOUT_SECONDS``. + """ + + API_VERSION: str = "7.1" + AZURE_DEVOPS_SCOPE: str = "499b84ac-1321-427f-aa17-267ca6975798/.default" + REQUEST_TIMEOUT_SECONDS: float = 30.0 + MAX_SINGLE_LINE_LENGTH: int = 255 + + def __init__( + self, + *, + organization_url: str, + project: str, + work_item_type: str, + destination_work_item_types: Collection[str], + field_map: Mapping[str, AzureDevOpsField], + evidence_field: str, + unmapped_keys: Collection[str] = (), + fixed_fields: Mapping[str, str | bool] | None = None, + nest_sub_findings: bool = True, + destination_label: str = "Parent work item", + destination_hint: str = "Paste the parent work item's ID or URL.", + token_provider: Callable[[], Awaitable[str]] | None = None, + ) -> None: + """ + Configure the publisher without contacting Azure DevOps. + + Args: + organization_url (str): ``https://dev.azure.com/{organization}`` or + ``https://{organization}.visualstudio.com``. + project (str): The project that new work items, and the destination, belong to. + work_item_type (str): The type of the new work items. + destination_work_item_types (Collection[str]): The types a destination work item may have. + field_map (Mapping[str, AzureDevOpsField]): The Azure DevOps field for each finding field or level key, + including ``severity``. + evidence_field (str): The field that holds the evidence references, after any mapped evidence text. + unmapped_keys (Collection[str]): Finding field and level keys that are deliberately not published. + Defaults to none. + fixed_fields (Mapping[str, str | bool] | None): Values written to every new work item, by field + reference name. Defaults to None. + nest_sub_findings (bool): Whether a sub-finding goes under its parent finding's new work item when both + are published in one run. Otherwise every finding goes under the destination. Defaults to True. + destination_label (str): The label of the destination input. Defaults to "Parent work item". + destination_hint (str): The hint under the destination input. Defaults to + "Paste the parent work item's ID or URL.". + token_provider (Callable[[], Awaitable[str]] | None): Returns an Azure DevOps access token. Defaults to + None, which uses ``get_azure_async_token_provider`` with ``AZURE_DEVOPS_SCOPE`` on the first request. + + Raises: + ValueError: If ``organization_url`` has another form, or a required value is empty. + TypeError: If ``destination_work_item_types`` or ``unmapped_keys`` is a single string. + """ + self._organization_url, self._organization = _parse_organization_url(organization_url) + self._project = _require_text(name="project", value=project) + self._work_item_type = _require_text(name="work_item_type", value=work_item_type) + self._evidence_field = _require_text(name="evidence_field", value=evidence_field) + self._destination_types = tuple( + _require_text(name="destination_work_item_types", value=value) + for value in _require_collection(name="destination_work_item_types", value=destination_work_item_types) + ) + if not self._destination_types: + raise ValueError("destination_work_item_types needs at least one work item type.") + self._unmapped_keys = frozenset(_require_collection(name="unmapped_keys", value=unmapped_keys)) + self._field_map: dict[str, AzureDevOpsField] = dict(field_map) + self._fixed_fields: dict[str, str | bool] = dict(fixed_fields or {}) + self._nest_sub_findings = nest_sub_findings + self._info = FindingPublisherInfo(destination_label=destination_label, destination_hint=destination_hint) + self._token_provider = token_provider + + @property + def info(self) -> FindingPublisherInfo: + """The destination input's label and hint.""" + return self._info + + @property + def nest_sub_findings(self) -> bool: + """Whether a sub-finding goes under its parent finding's new work item when both are published.""" + return self._nest_sub_findings + + def check_fields(self, *, fields: FindingFields) -> None: + """ + Check that every finding field has one deliberate mapping that Azure DevOps can hold. + + Args: + fields (FindingFields): The active finding fields. + + Raises: + FindingPublisherConfigurationError: Listing every key or field that breaks a rule. + """ + errors = [*self._coverage_errors(fields), *self._target_errors(), *self._kind_errors(fields)] + if errors: + raise FindingPublisherConfigurationError( + "The Azure DevOps publisher can't publish these finding fields. " + " ".join(errors) + ) + + def _check_plan(self, *, plan: FindingPublishPlan, fields: FindingFields) -> list[FindingPublishProblem]: + """ + Report titles and single-line values that Azure DevOps can't hold as written. + + Args: + plan (FindingPublishPlan): The planned findings. + fields (FindingFields): The active finding fields. + + Returns: + list[FindingPublishProblem]: A problem for each value that has a line break or is too long. + """ + labels = _field_labels(fields) + problems = [] + for item in plan.items: + finding = item.finding + for label, noun, value in self._single_line_values(item=item, labels=labels): + message = self._single_line_problem(label=label, noun=noun, value=value) + if message is not None: + problems.append(FindingPublishProblem(finding_id=finding.id, title=finding.title, message=message)) + return problems + + async def _open_destination_async( + self, *, destination: str, deadline: float | None + ) -> tuple[FindingPublishDestination, object]: + """ + Parse the destination's ID or URL, then read the work item and check its project and type. + + Args: + destination (str): A work item ID, or a work item URL in the configured organization. + deadline (float | None): The ``time.monotonic()`` value by which the call must finish, or None. + + Returns: + tuple[FindingPublishDestination, object]: The destination, and its Area and Iteration to copy. + + Raises: + FindingPublishDestinationError: If the destination is invalid, missing, not visible, in another project + or of another type. + FindingPublisherUnavailableError: If Azure DevOps can't be used. + FindingPublishDeadlineError: If too little time is left to send the request. + """ + work_item_id = self._parse_destination(destination) + try: + body = await self._request_async( + method="GET", url=f"{self._organization_url}/_apis/wit/workitems/{work_item_id}", deadline=deadline + ) + except _RequestFailedError as failure: + raise self._destination_failure(failure=failure, work_item_id=work_item_id) from failure + return self._read_destination(work_item_id=work_item_id, body=body) + + async def _create_item_async( + self, + *, + item: FindingPublishPlanItem, + parent_external_id: str, + context: object, + run_id: str, + requested_by: FindingPublishRequester | None, + deadline: float | None, + ) -> FindingPublishedItem: + """ + Create one work item under its parent with a JSON Patch document. + + Args: + item (FindingPublishPlanItem): The planned finding. + parent_external_id (str): The parent work item's ID. + context (object): The destination's Area and Iteration. + run_id (str): The run's ID, written to the History. + requested_by (FindingPublishRequester | None): The person the work item is assigned to, or None. + deadline (float | None): The ``time.monotonic()`` value by which the call must finish, or None. + + Returns: + FindingPublishedItem: The new work item. + + Raises: + FindingPublishDeadlineError: Before sending, if too little time is left. + FindingPublishCreateError: If the work item wasn't created, or might have been. + TypeError: If ``context`` didn't come from ``_open_destination_async``. + """ + if not isinstance(context, _DestinationContext): + raise TypeError("The context must come from _open_destination_async.") + document = self._work_item_document( + item=item, parent_external_id=parent_external_id, context=context, run_id=run_id, requested_by=requested_by + ) + url = ( + f"{self._organization_url}/{quote(self._project, safe='')}/_apis/wit/workitems/" + f"${quote(self._work_item_type, safe='')}" + ) + try: + body = await self._request_async( + method="POST", url=url, deadline=deadline, document=document, run_id=run_id + ) + except _RequestFailedError as failure: + raise self._create_failure(failure=failure, requested_by=requested_by) from failure + external_id, html_url = _created_work_item(body) + return FindingPublishedItem( + finding_id=item.finding.id, + title=item.finding.title, + external_id=external_id, + url=html_url, + parent_external_id=parent_external_id, + ) + + def _build_identifier(self) -> ComponentIdentifier: + """ + Record every setting that shapes the work items, without labels or credentials. + + Returns: + ComponentIdentifier: The publisher's identity. + """ + return ComponentIdentifier.of( + self, + params={ + "organization_url": self._organization_url, + "project": self._project, + "work_item_type": self._work_item_type, + "destination_work_item_types": sorted(self._destination_types), + "field_map": { + key: {"reference_name": target.reference_name, "kind": target.kind.value} + for key, target in sorted(self._field_map.items()) + }, + "unmapped_keys": sorted(self._unmapped_keys), + "fixed_fields": dict(sorted(self._fixed_fields.items())), + "evidence_field": self._evidence_field, + "nest_sub_findings": self._nest_sub_findings, + }, + ) + + # Configuration checks + + def _coverage_errors(self, fields: FindingFields) -> Iterator[str]: + keys = fields.field_keys | {"severity"} + mapped = set(self._field_map) + for key in sorted(keys - mapped - self._unmapped_keys): + yield f"Map '{key}' in field_map, or list it in unmapped_keys." + for key in sorted(mapped & self._unmapped_keys): + yield f"'{key}' is in both field_map and unmapped_keys." + for key in sorted((mapped | self._unmapped_keys) - keys): + yield f"'{key}' in field_map or unmapped_keys isn't a finding field or level." + + def _target_errors(self) -> Iterator[str]: + targets = Counter(target.reference_name.casefold() for target in self._field_map.values()) + for name, count in sorted(targets.items()): + if count > 1: + yield f"Only one key can map to '{name}'." + written = [*(target.reference_name for target in self._field_map.values()), *self._fixed_fields] + for name in written: + if _is_one_of(name, names=_SET_BY_PUBLISHER): + yield f"'{name}' is set by the publisher, so no key or fixed field can target it." + for name in self._fixed_fields: + if _is_one_of(name, names=(_DESCRIPTION, self._evidence_field, *targets)): + yield f"Fixed field '{name}' is also written from the findings." + if _is_one_of(self._evidence_field, names=(_DESCRIPTION, *_SET_BY_PUBLISHER)): + yield f"evidence_field can't be '{self._evidence_field}'." + + def _kind_errors(self, fields: FindingFields) -> Iterator[str]: + sources = dict(_field_sources(fields)) + for key, target in sorted(self._field_map.items()): + if key not in sources: + continue + field, depth = sources[key] + takes_html = _is_one_of(target.reference_name, names=(_DESCRIPTION, self._evidence_field)) + if takes_html and target.kind != AzureDevOpsFieldKind.HTML: + yield f"'{key}' maps to '{target.reference_name}', which takes kind html." + continue + yield from self._kind_error(key=key, kind=target.kind, field=field, depth=depth) + + def _kind_error(self, *, key: str, kind: AzureDevOpsFieldKind, field: FindingField, depth: int) -> Iterator[str]: + if kind == AzureDevOpsFieldKind.CHOICE and field.type == FindingFieldType.CHOICE and not field.allow_other: + for option in _options_at(options=field.options, depth=depth): + if self._single_line_problem(label="", noun="", value=option.key) is not None: + yield f"Option key {option.key!r} of '{key}' must be one line of at most 255 characters." + return + accepted = { + AzureDevOpsFieldKind.TEXT: (FindingFieldType.TEXT, FindingFieldType.NUMBER), + AzureDevOpsFieldKind.HTML: (FindingFieldType.MULTILINE, FindingFieldType.TEXT), + } + if depth == 0 and field.type in accepted.get(kind, ()): + return + source = f"a level of {field.type} field '{field.key}'" if depth else f"a {field.type} field" + if field.allow_other: + source += " that takes Other text" + yield f"'{key}' is {source}, which kind {kind} can't publish; list it in unmapped_keys instead." + + # Plan checks + + def _single_line_values( + self, *, item: FindingPublishPlanItem, labels: Mapping[str, str] + ) -> Iterator[tuple[str, str, str]]: + yield "Title", "titles", item.finding.title + for key, target in self._field_map.items(): + value = _stored_value(item=item, key=key) + if target.kind == AzureDevOpsFieldKind.TEXT and value: + yield labels.get(key, key), "single-line fields", value + + def _single_line_problem(self, *, label: str, noun: str, value: str) -> str | None: + if any(unicodedata.category(character) in ("Cc", "Cs") or character in "\u2028\u2029" for character in value): + return f"{label} contains a line break or tab. Azure DevOps {noun} hold one line." + length = len(value.encode("utf-16-le", "surrogatepass")) // 2 + if length > self.MAX_SINGLE_LINE_LENGTH: + return ( + f"{label} is {length} characters long, as Azure DevOps counts them; emoji and some symbols count as " + f"two. Azure DevOps accepts at most {self.MAX_SINGLE_LINE_LENGTH}." + ) + return None + + # Destination + + def _parse_destination(self, destination: str) -> int: + text = destination.strip() + # At most ten digits, the length of the largest ID, so a huge number can't reach int(). + work_item_id = text if re.fullmatch(r"[0-9]{1,10}", text) else self._work_item_id_from_url(text) + if work_item_id is None or not 1 <= int(work_item_id) <= _MAX_WORK_ITEM_ID: + raise FindingPublishDestinationError( + f"Paste a work item ID, or a link from {self._organization_url}, such as " + f"{self._organization_url}/{quote(self._project)}/_workitems/edit/12345." + ) + return int(work_item_id) + + def _work_item_id_from_url(self, text: str) -> str | None: + try: + parts = urlsplit(text) + port = parts.port + except ValueError: + return None + host = (parts.hostname or "").casefold() + if parts.scheme.casefold() != "https" or parts.username is not None or port is not None: + return None + path = parts.path + organization = self._organization.casefold() + if host == "dev.azure.com": + first, _, path = path.lstrip("/").partition("/") + if first.casefold() != organization: + return None + path = "/" + path + elif host != f"{organization}.visualstudio.com": + return None + match = _WORK_ITEM_PATH.search(path) + return str(match.group(1)) if match else None + + def _read_destination( + self, *, work_item_id: int, body: Mapping[str, Any] + ) -> tuple[FindingPublishDestination, _DestinationContext]: + fields = body.get("fields") + html_url = _nested_text(body, "_links", "html", "href") + if not isinstance(fields, Mapping) or not html_url: + raise FindingPublisherUnavailableError(_no_answer_message("unreadable response")) + project = _text(fields.get("System.TeamProject")) + if project.casefold() != self._project.casefold(): + raise FindingPublishDestinationError(f"Work item {work_item_id} isn't in the {self._project} project.") + work_item_type = _text(fields.get("System.WorkItemType")) + if not _is_one_of(work_item_type, names=self._destination_types): + raise FindingPublishDestinationError( + f"Work item {work_item_id} is of type {work_item_type or 'unknown'}. Paste a work item of type " + f"{' or '.join(self._destination_types)}." + ) + destination = FindingPublishDestination( + id=str(work_item_id), + title=_text(fields.get(_TITLE)), + url=html_url, + location=f"{self._organization} / {project}", + ) + context = _DestinationContext( + area_path=_text(fields.get(_AREA_PATH)), iteration_path=_text(fields.get(_ITERATION_PATH)) + ) + return destination, context + + def _destination_failure(self, *, failure: _RequestFailedError, work_item_id: int) -> Exception: + if failure.status == 404: + return FindingPublishDestinationError( + f"Work item {work_item_id} doesn't exist, or the publishing identity can't see it.", + diagnostics=failure.diagnostics, + ) + return FindingPublisherUnavailableError(_failure_message(failure), diagnostics=failure.diagnostics) + + # Work items + + def _work_item_document( + self, + *, + item: FindingPublishPlanItem, + parent_external_id: str, + context: _DestinationContext, + run_id: str, + requested_by: FindingPublishRequester | None, + ) -> list[dict[str, Any]]: + email = _non_blank(requested_by.email) if requested_by else None + values: dict[str, str | bool] = { + _TITLE: item.finding.title, + **self._mapped_values(item), + _DESCRIPTION: self._description_html(item), + self._evidence_field: _join_with_rule( + main=self._mapped_html(item=item, reference_name=self._evidence_field), + appendix=_evidence_html(item.entry.evidence), + ), + **self._fixed_fields, + _AREA_PATH: context.area_path, + _ITERATION_PATH: context.iteration_path, + _ASSIGNED_TO: email or "", + _HISTORY: _html(_history_note(run_id=run_id, finding_id=str(item.finding.id), requested_by=requested_by)), + } + document: list[dict[str, Any]] = [ + {"op": "add", "path": f"/fields/{name}", "value": value} for name, value in values.items() if value != "" + ] + parent_url = f"{self._organization_url}/_apis/wit/workItems/{parent_external_id}" + document.append({"op": "add", "path": "/relations/-", "value": {"rel": _PARENT_LINK, "url": parent_url}}) + return document + + def _mapped_values(self, item: FindingPublishPlanItem) -> dict[str, str]: + values = {} + for key, target in self._field_map.items(): + value = _stored_value(item=item, key=key) + if not value or _is_one_of(target.reference_name, names=(_DESCRIPTION, self._evidence_field)): + continue + values[target.reference_name] = _html(value) if target.kind == AzureDevOpsFieldKind.HTML else value + return values + + def _mapped_html(self, *, item: FindingPublishPlanItem, reference_name: str) -> str: + for key, target in self._field_map.items(): + if _is_one_of(target.reference_name, names=(reference_name,)): + return _html(_stored_value(item=item, key=key)) + return "" + + def _description_html(self, item: FindingPublishPlanItem) -> str: + appendix = "" + if item.part_of: + appendix += f"

Part of: {_html(item.part_of)}

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

    Retired fields

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

    Attack paths

      {''.join(items)}
    " + + +def _evidence_html(evidence: tuple[FindingReportEvidence, ...]) -> str: + if not evidence: + return "" + items = [] + for reference in evidence: + title = _html(reference.title) + link = _safe_link(reference.link_url) + lines = [f'{title}' if link else f"{title}"] + if reference.summary: + lines.append(DETAIL_SEPARATOR.join(_labelled_html(field) for field in reference.summary)) + lines.extend(_labelled_html(field) for field in reference.details) + if reference.unavailable: + lines.append(UNAVAILABLE_EVIDENCE) + items.append(f"
  • {'
    '.join(lines)}
  • ") + return f"
      {''.join(items)}
    " + + +def _labelled_html(field: FindingReportField) -> str: + return f"{_html(field.label)}: {_html(field.value)}" + + +def _safe_link(url: str | None) -> str | None: + """ + Accept only an absolute ``http`` or ``https`` link without whitespace or control characters. + + Returns: + str | None: The link escaped for an ``href`` attribute, or None to show the title without a link. + """ + if not url or any(character.isspace() or unicodedata.category(character) in ("Cc", "Cs") for character in url): + return None + try: + parts = urlsplit(url) + except ValueError: + return None + if parts.scheme.casefold() not in ("http", "https") or not parts.netloc: + return None + return html.escape(url, quote=True) + + +def _history_note(*, run_id: str, finding_id: str, requested_by: FindingPublishRequester | None) -> str: + name = _non_blank(requested_by.name) if requested_by else None + email = _non_blank(requested_by.email) if requested_by else None + who = f"{name} ({email})" if name and email else name or email or "a CoPyRIT user" + return f"Published from CoPyRIT by {who}. Run {run_id}, finding {finding_id}." + + +def _created_work_item(body: Mapping[str, Any]) -> tuple[str, str]: + work_item_id = body.get("id") + html_url = _nested_text(body, "_links", "html", "href") + valid_id = isinstance(work_item_id, int) and not isinstance(work_item_id, bool) + if not valid_id or not 1 <= work_item_id <= _MAX_WORK_ITEM_ID or not html_url: + raise FindingPublishCreateError( + "Couldn't get an answer from Azure DevOps (unreadable response). This work item might exist anyway. " + "Check Azure DevOps before publishing this finding again.", + outcome_unknown=True, + ) + return str(work_item_id), html_url + + +def _read_response(response: httpx.Response) -> Mapping[str, Any]: + status = response.status_code + body = _json_object(response) + if 200 <= status < 300: + if body is None: + raise _RequestFailedError( + kind=_FailureKind.NO_ANSWER, + detail="unreadable response", + status=status, + diagnostics=_diagnostics(response), + ) + return body + message = _text((body or {}).get("message")).strip() + kind = _FailureKind.REJECTED if 400 <= status < 500 else _FailureKind.NO_ANSWER + raise _RequestFailedError( + kind=kind, detail=f"HTTP {status}", status=status, service_message=message, diagnostics=_diagnostics(response) + ) + + +def _json_object(response: httpx.Response) -> Mapping[str, Any] | None: + try: + body = response.json() + except ValueError: + return None + return body if isinstance(body, dict) else None + + +def _diagnostics(response: httpx.Response) -> dict[str, str]: + """ + Collect what helps an administrator read a failure: never the service's message text, which can quote values. + + Returns: + dict[str, str]: The HTTP status, the service's type key and TF or VS code, and the rate-limit headers. + """ + diagnostics = {"HTTP": str(response.status_code)} + body = _json_object(response) or {} + type_key = _text(body.get("typeKey")) + if type_key: + diagnostics["typeKey"] = type_key + code = _SERVICE_CODE.match(_text(body.get("message"))) + if code: + diagnostics["code"] = code.group(0) + diagnostics.update({name: response.headers[name] for name in _RATE_LIMIT_HEADERS if name in response.headers}) + return diagnostics + + +def _warn_if_slowed(*, method: str, response: httpx.Response, run_id: str | None) -> None: + delay = response.headers.get("X-RateLimit-Delay") + if "Retry-After" not in response.headers and not _is_nonzero(delay): + return + headers = ", ".join(f"{name} {response.headers[name]}" for name in _RATE_LIMIT_HEADERS if name in response.headers) + run = f", run {run_id}" if run_id else "" + logger.warning( + "Azure DevOps is slowing the publishing identity: %s HTTP %s, %s%s.", method, response.status_code, headers, run + ) + + +def _is_nonzero(value: str | None) -> bool: + if value is None: + return False + try: + return float(value) != 0 + except ValueError: + return True + + +def _failure_message(failure: _RequestFailedError) -> str: + if failure.kind == _FailureKind.TOKEN: + return _TOKEN_MESSAGE + if failure.kind == _FailureKind.UNREACHABLE: + return _UNREACHABLE_MESSAGE + if failure.kind == _FailureKind.NO_ANSWER: + return _no_answer_message(failure.detail) + if failure.status in _STATUS_MESSAGES: + return _STATUS_MESSAGES[failure.status] + if failure.service_message: + return f"Azure DevOps rejected the request (HTTP {failure.status}): {failure.service_message}" + return f"Azure DevOps rejected the request (HTTP {failure.status})." + + +def _no_answer_message(detail: str) -> str: + return f"Couldn't get an answer from Azure DevOps ({detail}). Try again in a few minutes." diff --git a/pyrit/output/finding_publisher/base.py b/pyrit/output/finding_publisher/base.py new file mode 100644 index 0000000000..7ad806ec9a --- /dev/null +++ b/pyrit/output/finding_publisher/base.py @@ -0,0 +1,394 @@ +# 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 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 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. + + 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, + 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. + requested_by (FindingPublishRequester | None): The person the publish is for. Defaults to None. + expected_plan_digest (str | None): The digest that ``preview_async`` returned. Defaults to None, which + skips the comparison. + deadline (float | None): The ``time.monotonic()`` value by which the call must finish. Defaults to None, + for no overall limit. + + Returns: + FindingPublishResult: The run ID and every finding's outcome. + + Raises: + FindingPublishPlanChangedError: If the plan differs from ``expected_plan_digest``. + FindingPublishValidationError: If any planned finding has a problem. + FindingPublisherConfigurationError: If the publisher can't represent the fields. + FindingPublishDestinationError: If the destination is invalid, missing or not one the publisher takes. + FindingPublisherUnavailableError: If the destination's service can't be used. + FindingPublishDeadlineError: If too little time is left before the first item is created. + """ + self.check_fields(fields=fields) + plan = plan_finding_publish(selection=selection, fields=fields, 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))) + return [*problems, *self._check_plan(plan=plan, fields=fields)] + + 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.stopped_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] + 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, + ) + except FindingPublishDeadlineError: + run.stopped_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 + run.add(item=item, published=published) + 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 + + def add(self, *, item: FindingPublishPlanItem, published: FindingPublishedItem) -> None: + self.created.append(published) + self.external_ids[item.finding.id] = published.external_id + + 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 {} + + @property + def not_attempted(self) -> tuple[FindingPublishPlanItem, ...]: + attempted = len(self.created) + (1 if self.failure is not None else 0) + return self.plan.items[attempted:] + + 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.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 _deadline_passed(deadline: float | None) -> bool: + return deadline is not None and monotonic() >= deadline diff --git a/pyrit/output/finding_publisher/errors.py b/pyrit/output/finding_publisher/errors.py new file mode 100644 index 0000000000..9444aaf8d2 --- /dev/null +++ b/pyrit/output/finding_publisher/errors.py @@ -0,0 +1,88 @@ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT license. + +"""Errors that finding publishers raise.""" + +from collections.abc import Mapping, Sequence + +from pyrit.models import FindingPublishProblem + + +class FindingPublishError(Exception): + """ + Base class of finding publishing errors. + + ``diagnostics`` hold what helps an administrator read a log, such as an HTTP status, the service's error code and + its rate-limit headers. They never hold names, emails, titles, field values or the service's message text. + """ + + def __init__(self, message: str, *, diagnostics: Mapping[str, str] | None = None) -> None: + """ + Initialize the error. + + Args: + message (str): What happened, for the operator. + diagnostics (Mapping[str, str] | None): Details for logs only. Defaults to None. + """ + super().__init__(message) + self.diagnostics: Mapping[str, str] = dict(diagnostics or {}) + + +class FindingPublishPlanChangedError(FindingPublishError): + """Raised when the plan differs from the one the preview returned, so nothing is published.""" + + def __init__(self) -> None: + """Initialize the error with its message.""" + super().__init__("The findings changed since Check; check again.") + + +class FindingPublishValidationError(FindingPublishError): + """Raised when a publish finds problems, before it writes anything.""" + + def __init__(self, *, problems: Sequence[FindingPublishProblem]) -> None: + """ + Initialize the error with the problems to fix. + + Args: + problems (Sequence[FindingPublishProblem]): Each problem, in plan order. + """ + count = len(problems) + super().__init__(f"Fix {count} {'problem' if count == 1 else 'problems'} before publishing.") + self.problems: tuple[FindingPublishProblem, ...] = tuple(problems) + + +class FindingPublishDestinationError(FindingPublishError, ValueError): + """Raised when the destination can't be parsed, doesn't exist or isn't visible, or isn't one the publisher takes.""" + + +class FindingPublisherUnavailableError(FindingPublishError): + """Raised before any item is created when the service rejects the credentials, has no token or can't be reached.""" + + +class FindingPublishDeadlineError(FindingPublishError): + """Raised when the deadline passed, or too little time is left to send another request.""" + + +class FindingPublishCreateError(FindingPublishError): + """ + Raised by ``FindingPublisher._create_item_async`` when an item couldn't be created. + + ``outcome_unknown`` is True when the item might exist anyway. The base class records the error as the run's + failure, so it never escapes ``publish_async``. + """ + + def __init__(self, message: str, *, outcome_unknown: bool, diagnostics: Mapping[str, str] | None = None) -> None: + """ + Initialize the error. + + Args: + message (str): What happened, for the operator. + outcome_unknown (bool): Whether the item might exist anyway. + diagnostics (Mapping[str, str] | None): Details for logs only. Defaults to None. + """ + super().__init__(message, diagnostics=diagnostics) + self.outcome_unknown = outcome_unknown + + +class FindingPublisherConfigurationError(FindingPublishError): + """Raised when a publisher can't represent the active finding fields.""" diff --git a/pyrit/output/finding_publisher/plan.py b/pyrit/output/finding_publisher/plan.py new file mode 100644 index 0000000000..65c60147be --- /dev/null +++ b/pyrit/output/finding_publisher/plan.py @@ -0,0 +1,152 @@ +# 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 Mapping +from dataclasses import dataclass +from uuid import UUID + +from pyrit.models import Finding, FindingFields, FindingPublishPreviewItem, FindingPublishSkip +from pyrit.output.finding_report.report import 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. + + 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, 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. + + 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. + 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( + operation_name=selection.operation_name, + findings=selection.findings, + fields=fields, + evidence=selection.evidence, + part_of=selection.part_of, + ) + 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/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..ff1a59f2f4 --- /dev/null +++ b/tests/unit/output/finding_publisher/test_azure_devops.py @@ -0,0 +1,838 @@ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT license. + +import asyncio +import json +import logging +from collections.abc import Iterator +from typing import Any +from unittest.mock import AsyncMock, patch +from uuid import uuid4 + +import httpx +import pytest +import respx + +from pyrit.models import ( + DecompositionPath, + Finding, + FindingField, + FindingFields, + FindingPublishDestination, + FindingPublishRequester, + FindingPublishResult, +) +from pyrit.output import ( + AzureDevOpsField, + AzureDevOpsFieldKind, + AzureDevOpsFindingPublisher, + FindingPublishDeadlineError, + FindingPublishDestinationError, + FindingPublisherConfigurationError, + FindingPublisherUnavailableError, + FindingPublishValidationError, + FindingSelection, +) +from pyrit.output.finding_report.report import FindingReportEvidence, FindingReportField + +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"), + ], +) +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), + "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_name="Operation", findings=findings or (_finding(),), **extra) + + +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 _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://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_reports_a_missing_destination(ado: respx.MockRouter) -> None: + ado.get(WORK_ITEM_URL, params=API_VERSION).respond(404, json={"message": "TF401232: Work item does not exist."}) + + with pytest.raises(FindingPublishDestinationError, match="doesn't exist, or the publishing identity can't see it"): + await _publisher().preview_async(selection=_selection(), fields=FIELDS, destination="12345") + + +@pytest.mark.parametrize( + ("response", "message"), + [ + (httpx.Response(401), "didn't accept the publishing identity (HTTP 401)"), + (httpx.Response(403), "isn't allowed to do this in Azure DevOps (HTTP 403)"), + (httpx.Response(429), "is throttling the publishing identity (HTTP 429)"), + (httpx.Response(400, json={"message": "VS403: Bad query."}), "rejected the request (HTTP 400): VS403: Bad"), + (httpx.Response(503), "Couldn't get an answer from Azure DevOps (HTTP 503)"), + (httpx.Response(200, text=""), "Couldn't get an answer from Azure DevOps (unreadable response)"), + (httpx.Response(200, json={"id": 12345}), "Couldn't get an answer from Azure DevOps (unreadable response)"), + (httpx.ConnectError("refused"), "Couldn't reach Azure DevOps"), + (httpx.ConnectTimeout("slow"), "Couldn't reach Azure DevOps"), + (httpx.ReadTimeout("slow"), "Couldn't get an answer from Azure DevOps (timed out)"), + (httpx.RemoteProtocolError("dropped"), "Couldn't get an answer from Azure DevOps (no response)"), + ], +) +async def test_preview_reports_azure_devops_as_unavailable( + response: httpx.Response | Exception, message: str, ado: respx.MockRouter +) -> None: + ado.get(WORK_ITEM_URL, params=API_VERSION).mock(side_effect=[response]) + + with pytest.raises(FindingPublisherUnavailableError, match=message.replace("(", r"\(").replace(")", r"\)")): + await _publisher().preview_async(selection=_selection(), fields=FIELDS, destination="12345") + + +async def test_preview_reports_a_token_error_and_logs_it( + ado: respx.MockRouter, caplog: pytest.LogCaptureFixture +) -> None: + provider = AsyncMock(side_effect=RuntimeError("No managed identity endpoint.")) + + with ( + caplog.at_level(logging.WARNING), + pytest.raises(FindingPublisherUnavailableError, match="couldn't get an Azure"), + ): + await _publisher(token_provider=provider).preview_async( + selection=_selection(), fields=FIELDS, destination="12345" + ) + + assert not ado.calls + assert any(record.exc_info for record in caplog.records) + + +async def test_preview_reports_a_token_that_never_arrives(ado: respx.MockRouter) -> None: + async def hang() -> str: + await asyncio.Event().wait() + return TOKEN + + with ( + patch.object(AzureDevOpsFindingPublisher, "REQUEST_TIMEOUT_SECONDS", 0.01), + pytest.raises(FindingPublisherUnavailableError, match="couldn't get an Azure DevOps token"), + ): + await _publisher(token_provider=hang).preview_async(selection=_selection(), fields=FIELDS, destination="12345") + + assert not ado.calls + + +async def test_preview_stops_before_the_token_when_less_than_a_request_timeout_is_left(ado: respx.MockRouter) -> None: + provider = AsyncMock(return_value=TOKEN) + + with patch(CLOCK, return_value=100.0), pytest.raises(FindingPublishDeadlineError): + await _publisher(token_provider=provider).preview_async( + selection=_selection(), fields=FIELDS, destination="12345", deadline=129.9 + ) + + provider.assert_not_called() + assert not ado.calls + + +async def test_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"), + ], +) +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", + } + ) + + 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", + "System.Description": "The model follows
    <b>encoded</b> input.", + "Custom.Evidence": "See the run & transcript.", + "Custom.Linked": "yes", + "Custom.UsedPyRIT": True, + "System.AreaPath": "Red Team\\AI", + "System.IterationPath": "Red Team\\2026", + "System.AssignedTo": "ada@example.com", + "System.History": ( + f"Published from CoPyRIT by Ada Lovelace (ada@example.com). Run {result.run_id}, finding {finding.id}." + ), + } + assert document[-1] == { + "op": "add", + "path": "/relations/-", + "value": {"rel": "System.LinkTypes.Hierarchy-Reverse", "url": f"{ORG}/_apis/wit/workItems/12345"}, + } + assert "bypassRules" not in str(request.url) + assert [(item.external_id, item.url, item.parent_external_id) for item in result.created] == [ + ("501", f"{ORG}/_workitems/edit/501", "12345") + ] + + +async def test_publish_omits_empty_values(destination_route: respx.Route, create_route: respx.Route) -> None: + await _publish(_publisher(fixed_fields={"Custom.Empty": ""}), _finding(field_values={"summary": " "})) + + assert set(_sent_fields(create_route.calls.last.request)) == { + "System.Title", + "Custom.Severity", + "System.AreaPath", + "System.IterationPath", + "System.AssignedTo", + "System.History", + } + + +async def test_publish_links_a_sub_finding_to_its_parents_new_work_item( + destination_route: respx.Route, create_route: respx.Route +) -> None: + parent = _finding("Parent") + child = _finding("Child", parent_finding_id=parent.id) + + await _publish(_publisher(), parent, child) + + relation = json.loads(create_route.calls[1].request.content)[-1]["value"] + assert relation["url"] == f"{ORG}/_apis/wit/workItems/501" + + +async def test_publish_appends_part_of_paths_and_retired_fields_to_the_description( + destination_route: respx.Route, create_route: respx.Route +) -> None: + parent = _finding("Parent ", demonstrated=False) + step = _finding("Step", parent_finding_id=uuid4(), demonstrated=False) + finding = Finding( + operation_id=OPERATION_ID, + title="Child", + severity="Critical", + parent_finding_id=parent.id, + field_values={"description": "Main text", "old_key": "Old & value"}, + paths=(DecompositionPath(name="Chain", description="Two steps", steps=(step.id,)),), + ) + step = step.model_copy(update={"parent_finding_id": finding.id}) + + await _publish(_publisher(), parent, finding, step) + + assert _sent_fields(create_route.calls.last.request)["System.Description"] == ( + "Main text

    Part of: Parent <one>

    " + "

    Attack paths

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

    Retired fields

    • old_key: Old & value
    " + ) + + +async def test_publish_lists_evidence_with_only_web_links( + destination_route: respx.Route, create_route: respx.Route +) -> None: + finding = _finding() + evidence = ( + FindingReportEvidence( + title="Run <1>", + summary=( + FindingReportField(label="Outcome", value="Success"), + FindingReportField(label="Score", value="True"), + ), + details=(FindingReportField(label="Rationale", value="It complied"),), + link_url='https://copyrit.example.com/run?a=1&b="2"', + available=True, + ), + FindingReportEvidence(title="Script", summary=(), details=(), link_url="javascript:alert(1)", available=True), + FindingReportEvidence(title="Gone", summary=(), details=(), link_url=None, available=False), + ) + + await _publisher().publish_async( + selection=_selection(finding, evidence={finding.id: evidence}), fields=FIELDS, destination="12345" + ) + + assert _sent_fields(create_route.calls.last.request)["Custom.Evidence"] == ( + '
    • Run <1>' + "
      Outcome: Success · Score: True
      Rationale: It complied
    • " + "
    • Script
    • Gone
      Evidence unavailable
    " + ) + + +@pytest.mark.parametrize( + ("requester", "author", "assigned"), + [ + (FindingPublishRequester(name="Ada", email="ada@example.com"), "Ada (ada@example.com)", "ada@example.com"), + (FindingPublishRequester(name="Ada"), "Ada", None), + (FindingPublishRequester(email="ada@example.com"), "ada@example.com", "ada@example.com"), + (FindingPublishRequester(name=" ", email=""), "a CoPyRIT user", None), + (None, "a CoPyRIT user", None), + ], +) +async def test_publish_names_the_requester_in_the_history( + requester: FindingPublishRequester | None, + author: str, + assigned: str | None, + destination_route: respx.Route, + create_route: respx.Route, +) -> None: + finding = _finding() + + result = await _publisher().publish_async( + selection=_selection(finding), fields=FIELDS, destination="12345", requested_by=requester + ) + + fields = _sent_fields(create_route.calls.last.request) + assert fields["System.History"] == f"Published from CoPyRIT by {author}. Run {result.run_id}, finding {finding.id}." + assert fields.get("System.AssignedTo") == assigned + + +@pytest.mark.parametrize( + ("response", "message", "outcome_unknown"), + [ + (httpx.Response(401), "didn't accept the publishing identity (HTTP 401)", False), + (httpx.Response(403), "isn't allowed to do this in Azure DevOps (HTTP 403)", False), + (httpx.Response(429), "is throttling the publishing identity (HTTP 429)", False), + ( + httpx.Response(404, json={"message": "TF1: Missing."}), + "rejected the request (HTTP 404): TF1: Missing.", + False, + ), + ( + httpx.Response(400, json={"message": "TF401320: Rule error for field Assigned To."}), + "couldn't assign the work item to ada@example.com (HTTP 400)", + False, + ), + ( + httpx.Response(400, json={"message": "TF401326: Invalid field value."}), + "rejected the request (HTTP 400): TF401326: Invalid field value.", + False, + ), + (httpx.ConnectError("refused"), "Couldn't reach Azure DevOps", False), + (httpx.ConnectTimeout("slow"), "Couldn't reach Azure DevOps", False), + (httpx.Response(500), "Couldn't get an answer from Azure DevOps (HTTP 500). This work item might exist", True), + (httpx.ReadTimeout("slow"), "(timed out). This work item might exist anyway", True), + (httpx.Response(201, text="not json"), "(unreadable response). This work item might exist anyway", True), + (httpx.Response(200, json={"id": 7}), "(unreadable response). This work item might exist anyway", True), + ( + httpx.Response(200, json={"id": -1, "_links": {"html": {"href": f"{ORG}/_workitems/edit/-1"}}}), + "(unreadable response). This work item might exist anyway", + True, + ), + ], +) +async def test_publish_classifies_a_failed_create( + response: httpx.Response | Exception, + message: str, + outcome_unknown: bool, + destination_route: respx.Route, + ado: respx.MockRouter, +) -> None: + ado.post(CREATE_URL, params=API_VERSION).mock(side_effect=[response]) + + result = await _publish(_publisher(), _finding("First"), _finding("Second")) + + assert result.failure is not None + assert message in result.failure.message + assert result.failure.outcome_unknown is outcome_unknown + assert [item.title for item in result.not_attempted] == ["Second"] + + +async def test_publish_reports_a_create_that_times_out_after_sending_as_unknown( + destination_route: respx.Route, ado: respx.MockRouter +) -> None: + async def hang(request: httpx.Request) -> httpx.Response: + await asyncio.Event().wait() + return httpx.Response(200) + + ado.post(CREATE_URL, params=API_VERSION).mock(side_effect=hang) + + with patch.object(AzureDevOpsFindingPublisher, "REQUEST_TIMEOUT_SECONDS", 0.05): + result = await _publish(_publisher(), _finding()) + + assert result.failure is not None + assert result.failure.outcome_unknown + assert "(timed out)" in result.failure.message + + +@pytest.mark.parametrize("failure", ["raises", "hangs"]) +async def test_publish_reports_a_token_failure_at_a_later_create_as_known( + failure: str, destination_route: respx.Route, create_route: respx.Route +) -> None: + calls = 0 + + async def provider() -> str: + nonlocal calls + calls += 1 + if calls == 3: + if failure == "raises": + raise RuntimeError("Expired credential.") + await asyncio.Event().wait() + return TOKEN + + with patch.object(AzureDevOpsFindingPublisher, "REQUEST_TIMEOUT_SECONDS", 0.05): + result = await _publish(_publisher(token_provider=provider), _finding("First"), _finding("Second")) + + assert [item.title for item in result.created] == ["First"] + assert result.failure is not None + assert not result.failure.outcome_unknown + assert "couldn't get an Azure DevOps token" in result.failure.message + assert create_route.call_count == 1 + + +async def test_publish_stops_before_a_create_that_cannot_finish_in_time( + destination_route: respx.Route, create_route: respx.Route +) -> None: + provider = AsyncMock(return_value=TOKEN) + + with ( + patch("pyrit.output.finding_publisher.base.monotonic", return_value=100.0), + patch(CLOCK, side_effect=[100.0, 150.0, 175.0]), + ): + result = await _publish( + _publisher(token_provider=provider), _finding("First"), _finding("Second"), deadline=200.0 + ) + + assert [item.title for item in result.created] == ["First"] + assert result.stopped_reason is not None + assert [item.title for item in result.not_attempted] == ["Second"] + assert provider.await_count == 2 + + +async def test_publish_reports_a_deadline_at_the_first_create_as_a_stop( + destination_route: respx.Route, create_route: respx.Route +) -> None: + with ( + patch("pyrit.output.finding_publisher.base.monotonic", return_value=100.0), + patch(CLOCK, side_effect=[100.0, 175.0]), + ): + result = await _publish(_publisher(), _finding("First"), _finding("Second"), deadline=200.0) + + assert (result.created, result.failure) == ((), None) + assert result.stopped_reason is not None + assert [item.title for item in result.not_attempted] == ["First", "Second"] + assert not create_route.called + + +async def test_publish_warns_when_azure_devops_starts_slowing_requests( + destination_route: respx.Route, ado: respx.MockRouter, caplog: pytest.LogCaptureFixture +) -> None: + created = _created(501) + created.headers["Retry-After"] = "10" + ado.post(CREATE_URL, params=API_VERSION).mock(side_effect=[created]) + + with caplog.at_level(logging.WARNING): + result = await _publish(_publisher(), _finding()) + + assert any( + "Azure DevOps is slowing" in record.getMessage() + and "Retry-After 10" in record.getMessage() + and result.run_id in record.getMessage() + for record in caplog.records + ) + + +async def test_publish_logs_no_tokens_emails_or_azure_devops_messages( + destination_route: respx.Route, ado: respx.MockRouter, caplog: pytest.LogCaptureFixture +) -> None: + ado.post(CREATE_URL, params=API_VERSION).respond( + 400, json={"message": "TF401326: Value 'private field text' is invalid.", "typeKey": "RuleValidationException"} + ) + + with caplog.at_level(logging.DEBUG, logger="pyrit"): + await _publish(_publisher(), _finding()) + + logged = " ".join(record.getMessage() for record in caplog.records) + assert "HTTP 400, typeKey RuleValidationException, code TF401326" in logged + for private in (TOKEN, "ada@example.com", "Ada Lovelace", "private field text"): + assert private not in logged diff --git a/tests/unit/output/finding_publisher/test_base.py b/tests/unit/output/finding_publisher/test_base.py new file mode 100644 index 0000000000..179f36fbab --- /dev/null +++ b/tests/unit/output/finding_publisher/test_base.py @@ -0,0 +1,380 @@ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT license. + +import asyncio +import logging +from collections.abc import Callable +from datetime import UTC, datetime, timedelta +from unittest.mock import patch +from uuid import uuid4 + +import pytest + +from pyrit.models import ( + ComponentIdentifier, + Finding, + FindingField, + FindingFields, + FindingPublishDestination, + FindingPublishedItem, + FindingPublisherInfo, + FindingPublishRequester, + FindingPublishResult, +) +from pyrit.output import ( + FindingPublishCreateError, + FindingPublishDeadlineError, + FindingPublisher, + FindingPublisherConfigurationError, + FindingPublisherUnavailableError, + FindingPublishPlanChangedError, + FindingPublishPlanItem, + FindingPublishValidationError, + FindingSelection, + plan_finding_publish, +) + +OPERATION_ID = uuid4() +CREATED_AT = datetime(2026, 12, 1, tzinfo=UTC) +FIELDS = FindingFields( + severity=FindingField(key="severity", label="Severity", type="choice", options=[("high", "High"), ("low", "Low")]), + fields=[FindingField(key="description", label="Description", type="multiline")], +) +DESTINATION = FindingPublishDestination( + id="12345", title="Operation Contoso", url="https://example.com/12345", location="Example / Project" +) +REQUESTER = FindingPublishRequester(name="Ada Lovelace", email="ada@example.com") +CLOCK = "pyrit.output.finding_publisher.base.monotonic" + + +def _finding(title: str, *, parent: Finding | None = None, minutes: int = 0, **values: object) -> Finding: + return Finding( + operation_id=OPERATION_ID, + title=title, + severity=values.pop("severity", "high"), + parent_finding_id=parent.id if parent else None, + created_at=CREATED_AT + timedelta(minutes=minutes), + **values, # type: ignore[arg-type] + ) + + +ROOT = _finding("Root A", field_values={"description": "Secret description"}) +CHILD = _finding("Child B", parent=ROOT, minutes=1) +SECOND = _finding("Root C") +THIRD = _finding("Root D") +SKIPPED = _finding("Skipped E", demonstrated=False) +SELECTION = FindingSelection(operation_name="Operation", findings=(ROOT, SECOND, THIRD, SKIPPED, CHILD)) +PLAN_ORDER = [ROOT.id, CHILD.id, SECOND.id, THIRD.id] + + +class _FakePublisher(FindingPublisher): + def __init__( + self, + *, + outcomes: dict[str, BaseException] | None = None, + open_error: Exception | None = None, + configuration_error: Exception | None = None, + on_create: Callable[[], None] | None = None, + ) -> None: + self.calls: list[str] = [] + self._outcomes = outcomes or {} + self._open_error = open_error + self._configuration_error = configuration_error + self._on_create = on_create + self._next_id = 100 + + @property + def info(self) -> FindingPublisherInfo: + return FindingPublisherInfo(destination_label="Parent", destination_hint="Paste the parent's ID.") + + def check_fields(self, *, fields: FindingFields) -> None: + self.calls.append("check_fields") + if self._configuration_error is not None: + raise self._configuration_error + + def _build_identifier(self) -> ComponentIdentifier: + return ComponentIdentifier.of(self, params={"kind": "fake"}) + + async def _open_destination_async( + self, *, destination: str, deadline: float | None + ) -> tuple[FindingPublishDestination, object]: + self.calls.append(f"open {destination}") + if self._open_error is not None: + raise self._open_error + return DESTINATION, "context" + + async def _create_item_async( + self, + *, + item: FindingPublishPlanItem, + parent_external_id: str, + context: object, + run_id: str, + requested_by: FindingPublishRequester | None, + deadline: float | None, + ) -> FindingPublishedItem: + self.calls.append(f"create {item.finding.title} under {parent_external_id}") + if self._on_create is not None: + self._on_create() + outcome = self._outcomes.get(item.finding.title) + if outcome is not None: + raise outcome + self._next_id += 1 + return FindingPublishedItem( + finding_id=item.finding.id, + title=item.finding.title, + external_id=str(self._next_id), + url=f"https://example.com/{self._next_id}", + parent_external_id=parent_external_id, + ) + + +class _Clock: + """A monotonic clock that each create advances by ten seconds.""" + + def __init__(self) -> None: + self.now = 0.0 + + def __call__(self) -> float: + return self.now + + def advance(self) -> None: + self.now += 10 + + +def _outcome_ids(result: FindingPublishResult) -> list[object]: + failure = [result.failure.finding_id] if result.failure else [] + return [ + *(item.finding_id for item in result.created), + *failure, + *(item.finding_id for item in result.not_attempted), + ] + + +def _summaries(caplog: pytest.LogCaptureFixture) -> list[str]: + return [record.getMessage() for record in caplog.records if record.getMessage().startswith("Finding publish run")] + + +async def test_preview_returns_the_destination_plan_and_digest() -> None: + publisher = _FakePublisher() + + preview = await publisher.preview_async(selection=SELECTION, fields=FIELDS, destination="12345") + + plan = plan_finding_publish(selection=SELECTION, fields=FIELDS) + assert preview.destination == DESTINATION + assert [(item.title, item.parent_finding_id) for item in preview.planned] == [ + ("Root A", None), + ("Child B", ROOT.id), + ("Root C", None), + ("Root D", None), + ] + assert [(skip.title, skip.reason) for skip in preview.skipped] == [("Skipped E", "Not demonstrated")] + assert preview.problems == () + assert preview.plan_digest == plan.digest(identifier_hash=publisher.get_identifier().hash, destination="12345") + + +async def test_preview_opens_the_destination_despite_problems() -> None: + invalid = _finding("Invalid", severity="unknown") + publisher = _FakePublisher() + + preview = await publisher.preview_async( + selection=FindingSelection(operation_name="Operation", findings=(invalid,)), fields=FIELDS, destination="1" + ) + + assert [(problem.title, problem.message) for problem in preview.problems] == [ + ("Invalid", "Severity has no option 'unknown'.") + ] + assert publisher.calls == ["check_fields", "open 1"] + + +async def test_preview_leaves_retired_values_and_skipped_findings_unchecked() -> None: + retired = _finding("Retired", field_values={"old_field": "Kept from before"}) + skipped = _finding("Draft", severity="unknown", demonstrated=False) + + preview = await _FakePublisher().preview_async( + selection=FindingSelection(operation_name="Operation", findings=(retired, skipped)), + fields=FIELDS, + destination="1", + ) + + assert preview.problems == () + + +@pytest.mark.parametrize("method", ["preview_async", "publish_async"]) +async def test_configuration_error_stops_before_the_destination_is_opened(method: str) -> None: + publisher = _FakePublisher(configuration_error=FindingPublisherConfigurationError("Map 'severity'.")) + + with pytest.raises(FindingPublisherConfigurationError, match="Map 'severity'"): + await getattr(publisher, method)(selection=SELECTION, fields=FIELDS, destination="12345") + + assert publisher.calls == ["check_fields"] + + +async def test_publish_raises_problems_before_opening_the_destination() -> None: + invalid = _finding("Invalid", severity="unknown") + publisher = _FakePublisher() + + with pytest.raises(FindingPublishValidationError, match="Fix 1 problem") as raised: + await publisher.publish_async( + selection=FindingSelection(operation_name="Operation", findings=(invalid,)), fields=FIELDS, destination="1" + ) + + assert [problem.finding_id for problem in raised.value.problems] == [invalid.id] + assert publisher.calls == ["check_fields"] + + +async def test_publish_raises_plan_changed_before_any_request() -> None: + publisher = _FakePublisher() + preview = await publisher.preview_async(selection=SELECTION, fields=FIELDS, destination="12345") + publisher.calls.clear() + + with pytest.raises(FindingPublishPlanChangedError, match="check again"): + await publisher.publish_async( + selection=SELECTION, fields=FIELDS, destination="54321", expected_plan_digest=preview.plan_digest + ) + + assert publisher.calls == ["check_fields"] + + +async def test_publish_creates_parents_first_and_nests_children_under_their_new_items() -> None: + publisher = _FakePublisher() + preview = await publisher.preview_async(selection=SELECTION, fields=FIELDS, destination="12345") + publisher.calls.clear() + + result = await publisher.publish_async( + selection=SELECTION, + fields=FIELDS, + destination="12345", + requested_by=REQUESTER, + expected_plan_digest=preview.plan_digest, + ) + + assert publisher.calls == [ + "check_fields", + "open 12345", + "create Root A under 12345", + "create Child B under 101", + "create Root C under 12345", + "create Root D under 12345", + ] + assert len(result.run_id) == 32 + assert result.destination == DESTINATION + assert [item.external_id for item in result.created] == ["101", "102", "103", "104"] + assert [skip.finding_id for skip in result.skipped] == [SKIPPED.id] + assert (result.failure, result.stopped_reason, result.not_attempted) == (None, None, ()) + + +@pytest.mark.parametrize( + ("failing", "outcome", "created", "failure", "stopped"), + [ + (None, None, 4, None, False), + ("Child B", FindingPublishCreateError("Rejected.", outcome_unknown=False), 1, ("Rejected.", False), False), + ("Child B", FindingPublishCreateError("No answer.", outcome_unknown=True), 1, ("No answer.", True), False), + ("Child B", FindingPublishDeadlineError("Too late."), 1, None, True), + ("Root A", FindingPublishDeadlineError("Too late."), 0, None, True), + ("Child B", RuntimeError("Bug."), 1, (FindingPublisher.UNEXPECTED_FAILURE, True), False), + ], + ids=[ + "complete", + "known failure", + "unknown failure", + "adapter deadline", + "adapter deadline at first create", + "unexpected error", + ], +) +async def test_publish_accounts_for_every_planned_finding_exactly_once( + failing: str | None, + outcome: BaseException | None, + created: int, + failure: tuple[str, bool] | None, + stopped: bool, +) -> None: + publisher = _FakePublisher(outcomes={failing: outcome} if failing and outcome else {}) + + result = await publisher.publish_async(selection=SELECTION, fields=FIELDS, destination="12345") + + assert _outcome_ids(result) == PLAN_ORDER + assert len(result.created) == created + assert ((result.failure.message, result.failure.outcome_unknown) if result.failure else None) == failure + assert (result.stopped_reason == FindingPublisher.STOPPED_FOR_TIME) is stopped + assert not (result.failure and result.stopped_reason) + + +async def test_publish_stops_within_the_deadline_and_lists_the_rest_as_not_attempted() -> None: + clock = _Clock() + publisher = _FakePublisher(on_create=clock.advance) + + with patch(CLOCK, side_effect=clock): + result = await publisher.publish_async(selection=SELECTION, fields=FIELDS, destination="12345", deadline=15) + + assert [item.title for item in result.created] == ["Root A", "Child B"] + assert result.stopped_reason == FindingPublisher.STOPPED_FOR_TIME + assert [item.title for item in result.not_attempted] == ["Root C", "Root D"] + assert _outcome_ids(result) == PLAN_ORDER + + +async def test_publish_raises_a_deadline_before_opening_the_destination() -> None: + publisher = _FakePublisher() + + with patch(CLOCK, return_value=20.0), pytest.raises(FindingPublishDeadlineError): + await publisher.publish_async(selection=SELECTION, fields=FIELDS, destination="12345", deadline=15) + + assert publisher.calls == ["check_fields"] + + +async def test_publish_raises_a_deadline_that_passes_before_the_first_create() -> None: + publisher = _FakePublisher() + + with patch(CLOCK, side_effect=[0.0, 20.0]), pytest.raises(FindingPublishDeadlineError): + await publisher.publish_async(selection=SELECTION, fields=FIELDS, destination="12345", deadline=15) + + assert publisher.calls == ["check_fields", "open 12345"] + + +async def test_publish_propagates_a_destination_error() -> None: + publisher = _FakePublisher(open_error=FindingPublisherUnavailableError("Couldn't reach the service.")) + + with pytest.raises(FindingPublisherUnavailableError, match="Couldn't reach"): + await publisher.publish_async(selection=SELECTION, fields=FIELDS, destination="12345") + + +async def test_publish_logs_an_unexpected_create_error_with_its_traceback(caplog: pytest.LogCaptureFixture) -> None: + publisher = _FakePublisher(outcomes={"Root A": RuntimeError("Bug.")}) + + with caplog.at_level(logging.WARNING): + result = await publisher.publish_async(selection=SELECTION, fields=FIELDS, destination="12345") + + assert result.failure is not None and result.failure.outcome_unknown + assert any(record.exc_info and record.exc_info[1] is not None for record in caplog.records) + + +async def test_publish_logs_the_summary_when_cancelled_then_propagates(caplog: pytest.LogCaptureFixture) -> None: + publisher = _FakePublisher(outcomes={"Child B": asyncio.CancelledError()}) + + with caplog.at_level(logging.WARNING), pytest.raises(asyncio.CancelledError): + await publisher.publish_async(selection=SELECTION, fields=FIELDS, destination="12345") + + [summary] = _summaries(caplog) + assert "created 1 (101)" in summary + assert summary.endswith("stopped: cancelled.") + + +async def test_publish_writes_one_summary_line_without_personal_data(caplog: pytest.LogCaptureFixture) -> None: + publisher = _FakePublisher( + outcomes={"Root C": FindingPublishCreateError("Rejected.", outcome_unknown=False, diagnostics={"HTTP": "400"})} + ) + + with caplog.at_level(logging.WARNING): + result = await publisher.publish_async( + selection=SELECTION, fields=FIELDS, destination="12345", requested_by=REQUESTER + ) + + expected = ( + f"Finding publish run {result.run_id} to destination 12345 by _FakePublisher: created 2 (101, 102), " + "skipped 1, not attempted 1; failure with known outcome (HTTP 400); stopped: no." + ) + assert _summaries(caplog) == [expected] + logged = " ".join(record.getMessage() for record in caplog.records) + for private in ("Ada", "ada@example.com", "Root A", "Secret description", "Rejected."): + assert private not in logged diff --git a/tests/unit/output/finding_publisher/test_plan.py b/tests/unit/output/finding_publisher/test_plan.py new file mode 100644 index 0000000000..33ef1023e0 --- /dev/null +++ b/tests/unit/output/finding_publisher/test_plan.py @@ -0,0 +1,189 @@ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT license. + +from datetime import UTC, datetime, timedelta +from uuid import UUID, uuid4 + +import pytest + +from pyrit.models import DecompositionPath, Finding, FindingField, FindingFields, FindingPublishSkip +from pyrit.output import FindingPublishPlan, FindingSelection, plan_finding_publish +from pyrit.output.finding_report.report import FindingReportEvidence + +OPERATION_ID = uuid4() +CREATED_AT = datetime(2026, 12, 1, tzinfo=UTC) +FIELDS = FindingFields( + severity=FindingField(key="severity", label="Severity", type="choice", options=[("high", "High"), ("low", "Low")]), + fields=[FindingField(key="description", label="Description", type="multiline")], +) +EVIDENCE = FindingReportEvidence(title="Crescendo run", summary=(), details=(), link_url=None, available=True) + + +def _finding( + title: str, + *, + parent: Finding | None = None, + demonstrated: bool = True, + minutes: int = 0, + field_values: dict[str, str] | None = None, + finding_id: UUID | None = None, +) -> Finding: + return Finding( + id=finding_id or uuid4(), + operation_id=OPERATION_ID, + title=title, + severity="high", + field_values=field_values or {}, + parent_finding_id=parent.id if parent else None, + demonstrated=demonstrated, + created_at=CREATED_AT + timedelta(minutes=minutes), + ) + + +def _plan(*findings: Finding, nest_sub_findings: bool = True, **selection: object) -> FindingPublishPlan: + return plan_finding_publish( + selection=FindingSelection(operation_name="Operation", findings=findings, **selection), # type: ignore[arg-type] + fields=FIELDS, + nest_sub_findings=nest_sub_findings, + ) + + +def _layout(plan: FindingPublishPlan) -> list[tuple[str, str | None, str | None]]: + titles = {item.finding.id: item.finding.title for item in plan.items} + return [ + (item.finding.title, titles.get(item.parent_finding_id) if item.parent_finding_id else None, item.part_of) + for item in plan.items + ] + + +def test_plan_nests_planned_sub_findings_in_pre_order() -> None: + root = _finding("Root") + late = _finding("Late child", parent=root, minutes=2) + early = _finding("Early child", parent=root, minutes=1) + grandchild = _finding("Grandchild", parent=early, minutes=3) + second_root = _finding("Second root") + + plan = _plan(root, second_root, late, early, grandchild) + + assert _layout(plan) == [ + ("Root", None, None), + ("Early child", "Root", None), + ("Grandchild", "Early child", None), + ("Late child", "Root", None), + ("Second root", None, None), + ] + + +def test_plan_skips_findings_not_demonstrated_and_plans_their_sub_findings_under_the_destination() -> None: + root = _finding("Root") + skipped = _finding("Not shown", parent=root, demonstrated=False) + child = _finding("Child of skipped", parent=skipped, minutes=1) + + plan = _plan(root, skipped, child) + + assert _layout(plan) == [("Root", None, None), ("Child of skipped", None, "Not shown")] + assert plan.skipped == (FindingPublishSkip(finding_id=skipped.id, title="Not shown", reason="Not demonstrated"),) + + +def test_plan_takes_part_of_from_the_selection_for_a_parent_outside_it() -> None: + parent_id = uuid4() + child = Finding(operation_id=OPERATION_ID, title="Selected child", severity="high", parent_finding_id=parent_id) + + plan = _plan(child, part_of={parent_id: "Unselected parent"}) + + assert _layout(plan) == [("Selected child", None, "Unselected parent")] + + +def test_plan_without_nesting_puts_every_finding_under_the_destination() -> None: + root = _finding("Root") + child = _finding("Child", parent=root) + + plan = _plan(root, child, nest_sub_findings=False) + + assert _layout(plan) == [("Root", None, None), ("Child", None, "Root")] + + +def test_plan_joins_each_item_to_its_report_entry_with_missing_evidence_as_none() -> None: + with_evidence = _finding("With evidence") + without_evidence = _finding("Without evidence") + + plan = _plan(with_evidence, without_evidence, evidence={with_evidence.id: (EVIDENCE,)}) + + assert [(item.entry.finding_id, item.entry.evidence) for item in plan.items] == [ + (with_evidence.id, (EVIDENCE,)), + (without_evidence.id, ()), + ] + + +def test_plan_items_carry_paths_from_the_report() -> None: + root_id = uuid4() + child = Finding(operation_id=OPERATION_ID, title="Step", severity="high", parent_finding_id=root_id) + root = Finding( + id=root_id, + operation_id=OPERATION_ID, + title="Root", + severity="high", + paths=(DecompositionPath(name="Chain", steps=(child.id,)),), + ) + + plan = _plan(root, child) + + assert [(path.name, [step.title for step in path.steps]) for path in plan.items[0].entry.paths] == [ + ("Chain", ["Step"]) + ] + + +def test_plan_records_retired_values_in_stored_order() -> None: + finding = _finding( + "Retired values", field_values={"zeta": "last field", "description": "Current", "alpha": "first field"} + ) + + plan = _plan(finding) + + assert plan.items[0].retired == (("zeta", "last field"), ("alpha", "first field")) + + +def test_plan_digest_is_stable_for_the_same_plan() -> None: + finding = _finding("Finding", finding_id=UUID(int=1)) + + assert _plan(finding).digest(identifier_hash="publisher", destination="12345") == _plan(finding).digest( + identifier_hash="publisher", destination=" 12345 " + ) + + +@pytest.mark.parametrize( + ("nest_sub_findings", "add_skipped", "digest_inputs"), + [ + (True, False, {"identifier_hash": "other publisher", "destination": "12345"}), + (True, False, {"identifier_hash": "publisher", "destination": "54321"}), + (False, False, {"identifier_hash": "publisher", "destination": "12345"}), + (True, True, {"identifier_hash": "publisher", "destination": "12345"}), + ], + ids=["publisher", "destination", "planned pairs", "skipped findings"], +) +def test_plan_digest_changes_with_each_input( + nest_sub_findings: bool, add_skipped: bool, digest_inputs: dict[str, str] +) -> None: + parent = _finding("Parent", finding_id=UUID(int=1)) + child = _finding("Child", parent=parent, finding_id=UUID(int=2)) + baseline_plan = _plan(parent, child) + # A finding that isn't demonstrated changes only the skipped findings, never the planned pairs. + skipped = (_finding("Draft", demonstrated=False, finding_id=UUID(int=3)),) if add_skipped else () + plan = _plan(parent, child, *skipped, nest_sub_findings=nest_sub_findings) + + digest = plan.digest(**digest_inputs) + + if add_skipped: + assert [item.parent_finding_id for item in plan.items] == [ + item.parent_finding_id for item in baseline_plan.items + ] + assert digest != baseline_plan.digest(identifier_hash="publisher", destination="12345") + + +def test_plan_digest_ignores_titles_severities_and_field_values() -> None: + finding = _finding("Finding", finding_id=UUID(int=1)) + edited = finding.model_copy(update={"title": "Renamed", "severity": "low", "field_values": {"description": "New"}}) + + assert _plan(finding).digest(identifier_hash="publisher", destination="12345") == _plan(edited).digest( + identifier_hash="publisher", destination="12345" + ) From 1f34e0576be8a29a49fde3e3b182664d58c5d3bc Mon Sep 17 00:00:00 2001 From: Hannah Westra Date: Fri, 4 Dec 2026 13:05:28 -0500 Subject: [PATCH 04/22] FIX: Report an in-flight create as unknown when a publish is cancelled A cancelled publish logged the item whose create was in flight as not attempted, although its request may have reached the destination. The run now tracks that item and the summary reports it as "in flight 1 (outcome unknown)". Problems are now listed in plan order, as the validation error documents. Tests now fail if the History or other HTML fields go unescaped, another visualstudio.com organization is accepted, a 3xx counts as a known outcome, the project or type comparison becomes case-sensitive, a lone surrogate is allowed in a title, or a request starts with less than a full timeout left. The two real-timeout tests shorten only the hanging request's timeout. The output guide's in-memory publisher is now a runnable cell, and the guide notes that PyRIT's default severity and harm_type fields must be unmapped. Co-Authored-By: Claude Opus 5.5 --- .github/instructions/output.instructions.md | 2 +- doc/code/output/0_output.ipynb | 69 +++++++++++-- doc/code/output/0_output.py | 99 ++++++++++++------- pyrit/output/finding_publisher/base.py | 26 ++++- .../finding_publisher/test_azure_devops.py | 60 ++++++++++- .../output/finding_publisher/test_base.py | 54 ++++++++-- 6 files changed, 257 insertions(+), 53 deletions(-) diff --git a/.github/instructions/output.instructions.md b/.github/instructions/output.instructions.md index e77cc80f7b..5dd44093c1 100644 --- a/.github/instructions/output.instructions.md +++ b/.github/instructions/output.instructions.md @@ -78,4 +78,4 @@ Finding publishers (`pyrit/output/finding_publisher/`) write findings to another - Once the base calls `_create_item_async`, every outcome goes in the result and only cancellation escapes. Raise `FindingPublishCreateError` with `outcome_unknown=False` only when nothing was sent or the response proves nothing was created, and never retry a create that might have succeeded. - Never log tokens, names, emails, titles, field values or the service's message text. -When reviewing: reject a publisher that lets an exception other than cancellation escape after its first create. +When reviewing: reject a subclass that overrides `preview_async`, `publish_async` or the create loop. diff --git a/doc/code/output/0_output.ipynb b/doc/code/output/0_output.ipynb index cef94d7c17..1b47ca67e7 100644 --- a/doc/code/output/0_output.ipynb +++ b/doc/code/output/0_output.ipynb @@ -851,6 +851,9 @@ "publisher.check_fields(fields=fields)\n", "```\n", "\n", + "This example assumes a deployment's configured finding fields. PyRIT's default fields let `severity`\n", + "and `harm_type` take Other text, so with the defaults, list both in `unmapped_keys`.\n", + "\n", "Each work item copies its Area and Iteration from the destination, is assigned to the email of\n", "`requested_by`, and notes the requester, the run ID, and the finding ID in its History. Titles and\n", "`text` values must fit on one line of at most 255 characters as Azure DevOps counts them; the preview\n", @@ -858,11 +861,44 @@ "\n", "To publish somewhere else, subclass `FindingPublisher` and implement `_open_destination_async`, which\n", "reads the destination, and `_create_item_async`, which creates one item. The base class plans the\n", - "items, checks the values, and accounts for every outcome:\n", - "\n", - "```python\n", - "from pyrit.models import ComponentIdentifier, FindingPublishDestination, FindingPublishedItem, FindingPublisherInfo\n", - "from pyrit.output import FindingPublisher\n", + "items, checks the values, and accounts for every outcome. This publisher keeps its items in memory:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "publishing-findings-example", + "metadata": {}, + "outputs": [ + { + "name": "stderr", + "output_type": "stream", + "text": [ + "Finding publish run 47151ee3e69d467b9ffc9b975b84a87c 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", @@ -890,7 +926,28 @@ " 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(operation_name=\"Demo operation\", findings=(finding, step, draft))\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})\")" ] }, { diff --git a/doc/code/output/0_output.py b/doc/code/output/0_output.py index 16ca4253cc..87c238f4b3 100644 --- a/doc/code/output/0_output.py +++ b/doc/code/output/0_output.py @@ -326,6 +326,9 @@ # publisher.check_fields(fields=fields) # ``` # +# This example assumes a deployment's configured finding fields. PyRIT's default fields let `severity` +# and `harm_type` take Other text, so with the defaults, list both in `unmapped_keys`. +# # Each work item copies its Area and Iteration from the destination, is assigned to the email of # `requested_by`, and notes the requester, the run ID, and the finding ID in its History. Titles and # `text` values must fit on one line of at most 255 characters as Azure DevOps counts them; the preview @@ -333,39 +336,69 @@ # # To publish somewhere else, subclass `FindingPublisher` and implement `_open_destination_async`, which # reads the destination, and `_create_item_async`, which creates one item. The base class plans the -# items, checks the values, and accounts for every outcome: -# -# ```python -# from pyrit.models import ComponentIdentifier, FindingPublishDestination, FindingPublishedItem, FindingPublisherInfo -# from pyrit.output import FindingPublisher -# -# -# 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, -# ) -# ``` +# 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_name="Demo operation", findings=(finding, step, draft)) + +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/output/finding_publisher/base.py b/pyrit/output/finding_publisher/base.py index 7ad806ec9a..2fc608a887 100644 --- a/pyrit/output/finding_publisher/base.py +++ b/pyrit/output/finding_publisher/base.py @@ -246,7 +246,12 @@ def _find_problems(self, *, plan: FindingPublishPlan, fields: FindingFields) -> 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))) - return [*problems, *self._check_plan(plan=plan, fields=fields)] + 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 @@ -285,11 +290,13 @@ async def _create_next_async( deadline: float | None, ) -> bool: if _deadline_passed(deadline): - run.stopped_reason = self.STOPPED_FOR_TIME + 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, @@ -300,7 +307,7 @@ async def _create_next_async( deadline=deadline, ) except FindingPublishDeadlineError: - run.stopped_reason = self.STOPPED_FOR_TIME + 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) @@ -330,10 +337,16 @@ class _PublishRun: 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: self.created.append(published) self.external_ids[item.finding.id] = published.external_id + self.in_flight = None + + def stop(self, *, reason: str) -> None: + self.stopped_reason = reason + self.in_flight = None def fail( self, @@ -347,11 +360,12 @@ def fail( 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, ...]: - attempted = len(self.created) + (1 if self.failure is not None else 0) - return self.plan.items[attempted:] + 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( @@ -377,6 +391,8 @@ def summary(self) -> str: 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: diff --git a/tests/unit/output/finding_publisher/test_azure_devops.py b/tests/unit/output/finding_publisher/test_azure_devops.py index ff1a59f2f4..48a27e25e0 100644 --- a/tests/unit/output/finding_publisher/test_azure_devops.py +++ b/tests/unit/output/finding_publisher/test_azure_devops.py @@ -5,6 +5,7 @@ import json import logging from collections.abc import Iterator +from types import SimpleNamespace from typing import Any from unittest.mock import AsyncMock, patch from uuid import uuid4 @@ -63,6 +64,7 @@ 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 = { @@ -70,6 +72,7 @@ "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), } @@ -118,6 +121,23 @@ def _created(work_item_id: int) -> httpx.Response: ) +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"] @@ -357,6 +377,7 @@ async def test_preview_accepts_the_largest_work_item_id(ado: respx.MockRouter) - "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", @@ -392,6 +413,16 @@ async def test_preview_rejects_a_destination_of_another_type(ado: respx.MockRout ) +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."}) @@ -467,6 +498,16 @@ async def test_preview_stops_before_the_token_when_less_than_a_request_timeout_i 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) @@ -487,6 +528,7 @@ async def test_default_token_provider_uses_the_azure_devops_scope_once(destinati (_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( @@ -530,6 +572,7 @@ async def test_publish_sends_one_json_patch_document_per_finding( "risk": "Privacy", "subrisk": "Personal data", "notes": "Not published", + "steps": '1. Send \n2. Read the reply', } ) @@ -547,6 +590,7 @@ async def test_publish_sends_one_json_patch_document_per_finding( "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", @@ -677,6 +721,17 @@ async def test_publish_names_the_requester_in_the_history( 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