Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 8 additions & 0 deletions doc/gui/0_gui.md
Original file line number Diff line number Diff line change
Expand Up @@ -406,6 +406,14 @@ Select an operation in the labels bar to associate new chats and scans with it.
The operation page brings its findings, linked evidence, and execution history
together.

If another tab saves a finding while you are editing it, your save is rejected
and your draft stays open. Copy the edits you want to keep, cancel the dialog,
refresh the page, and reopen the finding to reconcile them with the latest values.
API clients must send the finding's returned `version` as `expected_version` in
each update request. A successful update returns the next version; a stale
version returns HTTP 409. SDK callers pass it as `expected_version` to
`update_finding_async`.

A finding can be broken into sub-findings, at any depth, to record a
decomposition such as a multi-step attack. Use **Add sub-finding** on a
finding, and expand **Sub-findings** to see them, oldest first in the order
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ jest.mock('@/services/api', () => ({

const OPERATION = { id: 'scan-operation', name: 'Scan operation', created_at: '2026-10-08T12:00:00Z' }
const FINDING: FindingListItem = {
version: 1,
id: 'finding', operation_id: OPERATION.id, title: 'Proof', severity: 'low', field_values: {},
created_at: '2026-10-08T12:00:00Z', evidence_count: 0, rows: [], retired: [],
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ jest.mock('@/services/api', () => ({
jest.mock('@/hooks/useRuntime', () => ({ ...jest.requireActual('@/hooks/useRuntime'), useRuntime: jest.fn() }))

const FINDING: FindingListItem = {
version: 1,
id: 'finding', operation_id: 'saved', title: 'Proof', severity: 'low', field_values: {},
created_at: '2026-10-08T12:00:00Z', evidence_count: 0, rows: [], retired: [],
parent_finding_id: null, demonstrated: true, paths: [], child_count: 0,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ function syntheticFinding(index: number, overrides: Partial<FindingListItem> = {
id: `00000000-0000-4000-8000-${String(index).padStart(12, '0')}`, operation_id: OPERATION.id,
title: `Synthetic finding ${index}`, severity: 'moderate', field_values: {},
created_at: '2026-10-21T12:00:00Z', evidence_count: 0, rows: [], retired: [], parent_finding_id: null,
demonstrated: true, paths: [], child_count: 0, ...overrides,
demonstrated: true, paths: [], child_count: 0, version: 1, ...overrides,
}
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ import FindingPathsDialog from './FindingPathsDialog'
jest.mock('@/services/api', () => ({ operationsApi: { replaceFindingPaths: jest.fn() } }))

const BASE: FindingListItem = {
version: 1,
id: 'parent', operation_id: 'op-1', title: 'Data theft', severity: 'critical', field_values: {},
created_at: '2026-11-06T12:00:00Z', evidence_count: 0, parent_finding_id: null, demonstrated: true,
paths: [], child_count: 2, rows: [], retired: [],
Expand Down
29 changes: 29 additions & 0 deletions frontend/src/components/Operations/OperationDetailPage.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@ jest.mock('@/hooks/useRuntime', () => ({ ...jest.requireActual('@/hooks/useRunti
const SAVED: Operation = { id: 'op-1', name: 'Red team / α%', created_at: '2026-10-06T20:00:00Z' }
const OPERATION: OperationDetail = { ...SAVED, usage: { findings: 0, attacks: 0, scenario_runs: 0 } }
const FINDING: FindingListItem = {
version: 1,
id: 'finding-1', operation_id: 'op-1', title: 'Human assessment',
severity: 'informational', field_values: {}, created_at: '2026-10-06T20:00:00Z', evidence_count: 0,
rows: [], retired: [], parent_finding_id: null, demonstrated: true, paths: [], child_count: 0,
Expand Down Expand Up @@ -387,6 +388,7 @@ it('prefills edit fields and saves only editable values', async () => {
await waitFor(() => { expect(screen.queryByRole('dialog')).not.toBeInTheDocument() })
await waitFor(() => { expect(screen.getByRole('heading', { name: edited.title })).toBeInTheDocument() })
expect(operationsApi.updateFinding).toHaveBeenCalledWith('op-1', FINDING.id, {
expected_version: FINDING.version,
title: edited.title, severity: 'critical', field_values: { description: 'Notes' }, demonstrated: true,
parent_finding_id: null, keep_retired_keys: [], remove_retired_keys: [],
})
Expand All @@ -413,6 +415,7 @@ it('displays and preserves both custom classifications when editing a finding',
await user.click(screen.getByRole('button', { name: 'Save finding' }))
await waitFor(() => expect(screen.queryByRole('dialog')).not.toBeInTheDocument())
expect(operationsApi.updateFinding).toHaveBeenCalledWith('op-1', FINDING.id, {
expected_version: FINDING.version,
title: FINDING.title, severity: 'Team severity', field_values: { harm_type: 'Team harm' }, demonstrated: true,
parent_finding_id: null, keep_retired_keys: [], remove_retired_keys: [],
})
Expand Down Expand Up @@ -452,11 +455,36 @@ it('retains an edited draft on update failure and shows why the backend rejected
expect(within(dialog).getByRole('textbox', { name: 'Title' })).toHaveValue(`${FINDING.title} changed`)
expect(within(dialog).getByRole('textbox', { name: 'Other value for Severity' })).toHaveValue('Critical')
expect(operationsApi.updateFinding).toHaveBeenCalledWith('op-1', FINDING.id, {
expected_version: FINDING.version,
title: `${FINDING.title} changed`, severity: 'Critical', field_values: {}, demonstrated: true,
parent_finding_id: null, keep_retired_keys: [], remove_retired_keys: [],
})
})

it('keeps the draft and original version after a stale finding conflict', async () => {
const user = userEvent.setup()
const detail = 'This finding has changed since you opened it. Your edits have not been saved.'
const opening = { ...FINDING, version: 7, field_values: { description: 'Original description' } }
jest.mocked(operationsApi.listFindings).mockResolvedValue({ ...EMPTY, items: [opening] })
jest.mocked(operationsApi.updateFinding).mockRejectedValue({
isAxiosError: true, response: { status: 409, data: { detail } },
})
renderPage()
await user.click(await screen.findByRole('button', { name: `Edit finding: ${FINDING.title}` }))
const dialog = screen.getByRole('dialog', { name: 'Edit finding' })
await user.type(within(dialog).getByRole('textbox', { name: 'Title' }), ' changed')
await user.click(within(dialog).getByRole('button', { name: 'Save finding' }))
expect(await within(dialog).findByText(detail)).toBeInTheDocument()
expect(within(dialog).getByRole('textbox', { name: 'Title' })).toHaveValue(`${FINDING.title} changed`)
expect(within(dialog).getByRole('textbox', { name: 'Description' })).toHaveValue('Original description')
expect(operationsApi.updateFinding).toHaveBeenCalledTimes(1)
expect(operationsApi.updateFinding).toHaveBeenLastCalledWith('op-1', FINDING.id, expect.objectContaining({ expected_version: 7 }))
await user.click(within(dialog).getByRole('button', { name: 'Save finding' }))
await waitFor(() => expect(operationsApi.updateFinding).toHaveBeenCalledTimes(2))
expect(operationsApi.updateFinding).toHaveBeenLastCalledWith('op-1', FINDING.id, expect.objectContaining({ expected_version: 7 }))
expect(within(dialog).getByRole('textbox', { name: 'Title' })).toHaveValue(`${FINDING.title} changed`)
})

it('shows configured rows and retired values on a finding card', async () => {
const user = userEvent.setup()
const steps = '1. Ask the Contoso assistant to repeat its instructions.\n2. Ask again in French.'
Expand Down Expand Up @@ -519,6 +547,7 @@ it('lists the kept and removed retired values by key, and sends none for a new f
await user.click(within(await findRemovalConfirmation()).getByRole('button', { name: 'Remove' }))
await user.click(await screen.findByRole('button', { name: 'Save finding' }))
await waitFor(() => expect(operationsApi.updateFinding).toHaveBeenCalledWith('op-1', FINDING.id, {
expected_version: FINDING.version,
title: FINDING.title, severity: 'informational', field_values: { harm_type: 'Malware' }, demonstrated: true,
parent_finding_id: null, keep_retired_keys: ['retired_owner'], remove_retired_keys: ['contoso_ticket'],
}))
Expand Down
2 changes: 1 addition & 1 deletion frontend/src/components/Operations/OperationDetailPage.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -131,7 +131,7 @@ function OperationDetailContent({ operationId, onOperationChanged }: { operation
const { editing, parent } = dialog
const saved = editing
? await operationsApi.updateFinding(operationId, editing.id, {
...draft, parent_finding_id: editing.parent_finding_id,
...draft, expected_version: editing.version, parent_finding_id: editing.parent_finding_id,
keep_retired_keys: draft.keep_retired_keys ?? [], remove_retired_keys: draft.remove_retired_keys ?? [],
})
: await operationsApi.createFinding(operationId, {
Expand Down
1 change: 1 addition & 0 deletions frontend/src/components/Scenarios/ScenarioRunPage.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -471,6 +471,7 @@ describe('ScenarioRunPage', () => {

it('shows findings linked to the attack only when there are some', async () => {
const finding: AttackFindingItem = {
version: 1,
id: 'finding-1', operation_id: RUN.operation_id, operation_name: 'Review operation', evidence_id: 'evidence-1',
title: 'Protected instructions disclosed', severity: 'important',
field_values: { description: 'Review the saved response.' }, created_at: RUN.created_at,
Expand Down
2 changes: 1 addition & 1 deletion frontend/src/services/api.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -91,7 +91,7 @@ describe("api service", () => {
});
it("nests finding requests under an encoded operation ID", async () => {
const request = { title: "Assessment", severity: "low", field_values: { description: "Notes" } };
const update = { ...request, keep_retired_keys: ["retired_owner"], remove_retired_keys: ["contoso_ticket"] };
const update = { ...request, expected_version: 3, keep_retired_keys: ["retired_owner"], remove_retired_keys: ["contoso_ticket"] };
(apiClient.post as jest.Mock).mockResolvedValueOnce({ data: { name: "Case" } });
await operationsApi.create({ name: " Case / α% " });
expect(apiClient.post).toHaveBeenCalledWith("/operations", { name: " Case / α% " });
Expand Down
3 changes: 3 additions & 0 deletions frontend/src/types/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2709,6 +2709,8 @@ export interface FindingCreateRequest extends FindingCreate {
* again, and a key in `remove_retired_keys` drops that retired value.
*/
export interface FindingUpdateRequest extends FindingCreate {
/** The `version` read when the edit began; a stale version is rejected with HTTP 409. */
expected_version: number
keep_retired_keys: string[]
remove_retired_keys: string[]
}
Expand Down Expand Up @@ -2776,6 +2778,7 @@ export interface FindingPathsUpdateRequest {

export interface Finding extends FindingCreate {
id: string
version: number
Comment thread
romanlutz marked this conversation as resolved.
Resolved
operation_id: string
created_at: string
parent_finding_id: string | null
Expand Down
6 changes: 5 additions & 1 deletion pyrit/backend/models/operations.py
Original file line number Diff line number Diff line change
Expand Up @@ -172,9 +172,13 @@ class FindingUpdateRequest(_FindingRequestFields):
A finding's new editable values, replacing the saved ones, and the retired values to keep or remove.

An omitted ``parent_finding_id`` makes the finding top-level. A finding moves with its sub-findings, and paths
are replaced separately.
are replaced separately. Supply the version read when the edit began as ``expected_version``; a stale version
returns 409.
"""

expected_version: int = Field(
ge=1, strict=True, description="Version of the finding being edited; stale edits return 409"
)
keep_retired_keys: list[IdentifierStr] = Field(
default_factory=list,
max_length=MAX_ITEMS,
Expand Down
8 changes: 6 additions & 2 deletions pyrit/backend/routes/operations.py
Original file line number Diff line number Diff line change
Expand Up @@ -269,12 +269,16 @@ async def update_operation_finding_async(
even if its field is configured again. Values that haven't changed may use options that no longer exist.
A finding moves with its sub-findings. Its paths are unchanged.

Send the ``version`` returned when reading the finding as ``expected_version``. A successful edit increments
it; a stale edit returns 409 without changing the finding. Read the latest values and reconcile the draft
before retrying.

Returns:
Finding: The updated finding.

Raises:
HTTPException: 409 when the finding would move while its parent's paths use it, or under itself or one of
its sub-findings, and 422 when the values do not fit the active finding fields.
HTTPException: 409 for a stale version, or when the finding would move while its parent's paths use it,
or under itself or one of its sub-findings; 422 when values do not fit the active finding fields.
"""
try:
return await _require_operation_async(
Expand Down
22 changes: 18 additions & 4 deletions pyrit/backend/services/operation_service.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,8 @@
from collections.abc import Sequence
from uuid import UUID, uuid4

from sqlalchemy.orm.exc import StaleDataError

from pyrit.backend.models import ScoreView
from pyrit.backend.models.operations import (
AttackFindingItem,
Expand Down Expand Up @@ -41,6 +43,11 @@
# Keeps every ID list a batch reads within SQL Server's 2100-parameter limit.
_EVIDENCE_BATCH_SIZE = 500

_STALE_FINDING_EDIT = (
"This finding has changed since you opened it. Your edits have not been saved. "
"Copy your changes, then refresh and reopen the finding to review its latest values."
)


class OperationNotFoundError(LookupError):
"""Raised when a request names an operation that does not exist."""
Expand Down Expand Up @@ -199,7 +206,7 @@ async def create_finding_async(self, *, operation_id: UUID, request: FindingCrea
except FindingHierarchyError as exc:
raise FindingConflictError(str(exc)) from exc
# Paths are set after a finding is created, so a retry still matches a finding that has paths by then.
unchanged = {"created_at", "paths"}
unchanged = {"created_at", "paths", "version"}
if saved.model_dump(exclude=unchanged) != finding.model_dump(exclude=unchanged) or (
evidence is not None
and await memory.get_finding_evidence_by_source_async(
Expand Down Expand Up @@ -623,20 +630,22 @@ async def update_finding_async(
A current field left out is cleared. Values of fields that are no longer configured are kept and can't
change; list them in ``remove_retired_keys`` to delete them. A value listed in ``keep_retired_keys`` is
kept even if its field is configured again. Values that haven't changed may use options that no longer
exist.
exist. The request must carry the version read when editing began as ``expected_version``.

Returns:
Finding: The updated finding.

Raises:
FindingNotFoundError: If the finding or its new parent is missing or belongs to another operation.
FindingConflictError: If the finding would move while its parent's paths use it, or under itself or one
of its sub-findings.
of its sub-findings, or the edited version is stale.
FindingValuesError: If ``remove_retired_keys`` lists a key that isn't a retired value of the finding
or that is also sent, or the values do not fit the active finding fields.
"""
await self.get_async(operation_id)
stored = await self._require_finding_async(operation_id=operation_id, finding_id=finding_id)
if stored.version != request.expected_version:
raise FindingConflictError(_STALE_FINDING_EDIT)
replacement = get_active_finding_fields().apply_edit(
stored=stored,
edit=request,
Expand All @@ -647,12 +656,17 @@ async def update_finding_async(
await self._require_parent_async(operation_id=operation_id, parent_id=request.parent_finding_id)
try:
return await CentralMemory.get_memory_instance().update_finding_async(
operation_id=operation_id, finding_id=finding_id, request=replacement
operation_id=operation_id,
finding_id=finding_id,
request=replacement,
expected_version=request.expected_version,
)
except LookupError as exc:
raise FindingNotFoundError(str(exc)) from exc
except FindingHierarchyError as exc:
raise FindingConflictError(str(exc)) from exc
except StaleDataError as exc:
raise FindingConflictError(_STALE_FINDING_EDIT) from exc

async def delete_finding_async(self, *, operation_id: UUID, finding_id: UUID) -> None:
"""
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
# Copyright (c) Microsoft Corporation.
# Licensed under the MIT license.

"""
Add an optimistic concurrency version to finding edits.

Revision ID: 8c2d4e6f0a13
Revises: 5c6cb7e7554e
"""

from collections.abc import Sequence

import sqlalchemy as sa
from alembic import op

revision: str = "8c2d4e6f0a13"
down_revision: str | None = "5c6cb7e7554e"
branch_labels: str | Sequence[str] | None = None
depends_on: str | Sequence[str] | None = None


def upgrade() -> None:
"""Initialize existing and new findings at version one."""
op.add_column("FindingEntries", sa.Column("version", sa.Integer(), nullable=False, server_default="1"))


def downgrade() -> None:
"""Remove finding edit versions."""
with op.batch_alter_table("FindingEntries") as batch_op:
batch_op.drop_column("version", mssql_drop_default=True)
8 changes: 7 additions & 1 deletion pyrit/memory/memory_interface.py
Original file line number Diff line number Diff line change
Expand Up @@ -1421,7 +1421,7 @@ async def add_finding_async(self, *, finding: Finding, evidence: FindingEvidence
raise

async def update_finding_async(
self, *, operation_id: uuid.UUID, finding_id: uuid.UUID, request: FindingCreate
self, *, operation_id: uuid.UUID, finding_id: uuid.UUID, request: FindingCreate, expected_version: int
) -> Finding:
"""
Replace a finding's editable fields, including its parent, without changing identity, creation time, or paths.
Expand All @@ -1433,6 +1433,7 @@ async def update_finding_async(

Raises:
LookupError: If the finding does not belong to the operation.
StaleDataError: If the finding has changed since the caller read it.
FindingHierarchyError: If the finding would move while it is a step of its parent's paths, or under a
parent that is outside the operation, the finding itself, or one of its sub-findings.
"""
Expand All @@ -1442,9 +1443,14 @@ async def update_finding_async(
entry = await self._get_finding_entry_async(
session=session, operation_id=operation_id, finding_id=finding_id
)
if entry.version != expected_version:
raise StaleDataError(
f"Finding {finding_id} is at version {entry.version}, not the expected {expected_version}."
)
if validated.parent_finding_id != entry.parent_finding_id:
await validate_move_async(session, entry=entry, parent_id=validated.parent_finding_id)
entry.set_fields(validated)
entry.version += 1
await session.flush()
return entry.get_finding()

Expand Down
3 changes: 3 additions & 0 deletions pyrit/memory/memory_models.py
Original file line number Diff line number Diff line change
Expand Up @@ -483,6 +483,7 @@ class FindingEntry(Base):
CustomUUID, ForeignKey(f"{OperationEntry.__tablename__}.id"), nullable=False
)
title: Mapped[str] = mapped_column(Unicode, nullable=False)
version: Mapped[int] = mapped_column(INTEGER, nullable=False, default=1, server_default="1")
# Binary collation keeps SQL Server from merging severities that differ only in case or accents, as SQLite does.
severity: Mapped[str] = mapped_column(
Unicode().with_variant(Unicode(collation="Latin1_General_100_BIN2"), "mssql"), nullable=False
Expand All @@ -501,6 +502,7 @@ def __init__(self, finding: Finding) -> None:
self.id = validated.id
self.operation_id = validated.operation_id
self.created_at = validated.created_at.astimezone(UTC)
self.version = 1
self.set_fields(validated)
self.set_paths(validated.paths)

Expand Down Expand Up @@ -542,6 +544,7 @@ def get_finding(self) -> Finding:
parent_finding_id=self.parent_finding_id,
demonstrated=self.demonstrated,
paths=self.get_paths(),
version=self.version,
)


Expand Down
1 change: 1 addition & 0 deletions pyrit/models/finding.py
Original file line number Diff line number Diff line change
Expand Up @@ -266,6 +266,7 @@ class Finding(FindingCreate):
operation_id: UUID
id: UUID = Field(default_factory=uuid4)
created_at: AwareDatetime = Field(default_factory=lambda: datetime.now(UTC))
version: int = Field(default=1, ge=1, description="Revision to supply when updating the finding's fields")
paths: tuple[DecompositionPath, ...] = ()

@property
Expand Down
Loading
Loading