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
3 changes: 3 additions & 0 deletions .env_example
Original file line number Diff line number Diff line change
Expand Up @@ -341,3 +341,6 @@ AZURE_STORAGE_ACCOUNT_DB_DATA_CONTAINER_URL_PROD="https://xxxxx.blob.core.window
# The below is set as the central memory. Adjust as needed. Recommend overwriting in .env.local.
AZURE_SQL_DB_CONNECTION_STRING = ${AZURE_SQL_DB_CONNECTION_STRING_PROD}
AZURE_STORAGE_ACCOUNT_DB_DATA_CONTAINER_URL=${AZURE_STORAGE_ACCOUNT_DB_DATA_CONTAINER_URL_PROD}

# Optional: seconds before a statement is cancelled on the server (default 300; 0 disables).
# AZURE_SQL_DB_QUERY_TIMEOUT_SECONDS = 300
1 change: 1 addition & 0 deletions doc/code/memory/0_memory.md
Original file line number Diff line number Diff line change
Expand Up @@ -52,3 +52,4 @@ The `MemoryDatabaseType` is a `Literal` with 3 options: IN_MEMORY, SQLITE, AZURE
- To configure AzureSQLMemory without an extra argument list, these keys should be in your `.env` file:
- `AZURE_SQL_DB_CONNECTION_STRING`
- `AZURE_STORAGE_ACCOUNT_DB_DATA_CONTAINER_URL`
- Statements that run longer than `AZURE_SQL_DB_QUERY_TIMEOUT_SECONDS` (default 300; `0` disables the limit) are cancelled on the server and raise an error. Schema migrations are not limited.
17 changes: 16 additions & 1 deletion frontend/src/components/CompatibilityGate.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -134,8 +134,9 @@ it.each([{}, { compatibility_id: null }, { compatibility_id: '1.2.0+gabc' }, { c
'blocks startup without mounting business UI for %p', async (version) => {
adapter.mockImplementation(async (config: InternalAxiosRequestConfig) => response(config, version))
render(application())
const notice = await screen.findByRole('alertdialog')
const notice = await screen.findByRole('alertdialog', { name: 'PyRIT compatibility blocked' })
expect(notice).toHaveAttribute('open')
expect(notice).toHaveTextContent('Deploy the frontend and backend from the same version')
expect(fireEvent(notice, new Event('cancel', { cancelable: true }))).toBe(false)
expect(notice).toHaveAttribute('open')
expect(screen.queryByRole('textbox', { hidden: true })).not.toBeInTheDocument()
Expand Down Expand Up @@ -173,6 +174,20 @@ it('blocks startup after authentication still fails following refresh', async ()
expect(screen.queryByRole('textbox', { hidden: true })).not.toBeInTheDocument()
})

it('reports a timed-out version check as backend unavailable without mismatch guidance', async () => {
adapter.mockImplementation(async (config: InternalAxiosRequestConfig) => {
throw new AxiosError('timeout of 30000ms exceeded', AxiosError.ECONNABORTED, config)
})
render(application())
const notice = await screen.findByRole('alertdialog', { name: 'PyRIT backend unavailable' })
expect(notice).toHaveTextContent('This does not indicate a version mismatch')
expect(notice).not.toHaveTextContent('Deploy the frontend and backend')
expect(screen.getByRole('button', { name: 'Reload page' })).toBeVisible()
expect(screen.queryByRole('textbox', { hidden: true })).not.toBeInTheDocument()
await expect(authApi.getAccess()).rejects.toThrow('compatibility')
expect(adapter).toHaveBeenCalledTimes(1)
})

it('retains admitted UI when the first business request is incompatible', async () => {
const unmount = jest.fn()
adapter.mockImplementation(async (config: InternalAxiosRequestConfig) => {
Expand Down
24 changes: 17 additions & 7 deletions frontend/src/components/CompatibilityGate.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ export function CompatibilityGate({ children }: { children: ReactNode }) {
const [admitted, setAdmitted] = useState(false)
const notice = useRef<HTMLDialogElement>(null)
const { modalAttributes } = useModalAttributes({ trapFocus: true })
const failed = snapshot.status === 'blocked' || snapshot.status === 'unavailable'

useEffect(() => {
let active = true
Expand All @@ -18,15 +19,15 @@ export function CompatibilityGate({ children }: { children: ReactNode }) {
}, [])

useEffect(() => {
if (snapshot.status === 'blocked' && notice.current && !notice.current.open) {
if (failed && notice.current && !notice.current.open) {
notice.current.showModal()
}
}, [snapshot.status])
}, [failed])

return (
<>
{snapshot.status === 'checking' && <div role="status">Checking frontend and backend compatibility...</div>}
{snapshot.status === 'blocked' && (
{failed && (
<dialog
{...modalAttributes}
ref={notice}
Expand All @@ -35,11 +36,20 @@ export function CompatibilityGate({ children }: { children: ReactNode }) {
onCancel={(event) => event.preventDefault()}
style={{ padding: '2rem', maxWidth: 'min(42rem, calc(100vw - 2rem))', overflowWrap: 'anywhere' }}
>
<h1 id="compatibility-notice-title">PyRIT compatibility blocked</h1>
<h1 id="compatibility-notice-title">
{snapshot.status === 'unavailable' ? 'PyRIT backend unavailable' : 'PyRIT compatibility blocked'}
</h1>
Comment on lines +39 to +41
<p>{snapshot.reason}</p>
{snapshot.expected && <p>Backend expected: <code>{snapshot.expected}</code></p>}
{snapshot.actual && <p>Frontend sent: <code>{snapshot.actual}</code></p>}
<p>Deploy the frontend and backend from the same version and full Git commit, then reload this page.</p>
{snapshot.status === 'blocked' && (
<>
{snapshot.expected && <p>Backend expected: <code>{snapshot.expected}</code></p>}
{snapshot.actual && <p>Frontend sent: <code>{snapshot.actual}</code></p>}
<p>Deploy the frontend and backend from the same version and full Git commit, then reload this page.</p>
</>
)}
{snapshot.status === 'unavailable' && (
<p>This does not indicate a version mismatch. Wait a few minutes, then reload this page.</p>
)}
<p>Further business requests are disabled. No failed operation will be replayed automatically.</p>
{admitted && <p>Your existing UI state is retained in this page. Reloading will discard unsaved work.</p>}
<button type="button" onClick={() => window.location.reload()}>Reload page</button>
Expand Down
46 changes: 39 additions & 7 deletions frontend/src/components/History/ScenarioHistory.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -745,6 +745,38 @@ describe('ScenarioHistory', () => {
expect(mockedScenariosApi.listRuns).toHaveBeenCalledTimes(2)
})

it('backs off automatic refreshes while history reads keep failing', async () => {
mockedScenariosApi.listRuns.mockRejectedValue(new Error('history unavailable'))
renderHistory()
expect(await screen.findByText('history unavailable')).toBeInTheDocument()

await advanceAutoRefresh()
await waitFor(() => expect(mockedScenariosApi.listRuns).toHaveBeenCalledTimes(2))
await advanceAutoRefresh()
expect(mockedScenariosApi.listRuns).toHaveBeenCalledTimes(2)
await advanceAutoRefresh()
await waitFor(() => expect(mockedScenariosApi.listRuns).toHaveBeenCalledTimes(3))
})

it('leaves the next read to the backoff when the queue changes after a failed read', async () => {
mockedScenariosApi.listRuns.mockRejectedValue(new Error('history unavailable'))
const history = renderHistory()
expect(await screen.findByText('history unavailable')).toBeInTheDocument()

mockUseScenarioQueue.mockReturnValue({
snapshot: { revision: 1, snapshot_at: '2026-01-01T00:01:00Z', active: null, queued: [] },
loading: false, stale: false, error: null, retry: mockQueueRetry,
})
history.rerender(
<FluentProvider theme={webLightTheme}>
<main>
<ScenarioHistory {...defaultProps} />
</main>
</FluentProvider>,
)
expect(mockedScenariosApi.listRuns).toHaveBeenCalledTimes(1)
})

it('distinguishes unfiltered and filtered empty states', async () => {
const user = userEvent.setup()
const onNavigate = jest.fn()
Expand Down Expand Up @@ -1014,7 +1046,7 @@ describe('ScenarioHistory', () => {
await expectFirstPageOfA()
})

it('keeps navigation loading when a queue update reloads the pending page', async () => {
it('waits for the pending page before reloading it for a queue update', async () => {
const user = userEvent.setup()
mockListRuns()
const history = render(renderWithFilters(FILTERS_A))
Expand All @@ -1031,18 +1063,18 @@ describe('ScenarioHistory', () => {
loading: false, stale: false, error: null, retry: mockQueueRetry,
})
history.rerender(renderWithFilters(FILTERS_A))
await waitFor(() => expect(mockedScenariosApi.listRuns).toHaveBeenCalledTimes(3))
expect(mockedScenariosApi.listRuns).toHaveBeenLastCalledWith(
expect.objectContaining({ cursor: 'a-page-2' }),
)
expect(mockedScenariosApi.listRuns).toHaveBeenCalledTimes(2)
expect(screen.getByText('Loading scanner history...')).toBeInTheDocument()
expect(screen.queryByTestId('scenario-history-row-run-1')).not.toBeInTheDocument()
expect(screen.queryByText('Page 2')).not.toBeInTheDocument()

await act(async () => {
nextPage.resolve({ items: [RUN], pagination: { limit: 25, has_more: false } })
})
expect(screen.getByText('Loading scanner history...')).toBeInTheDocument()
await waitFor(() => expect(mockedScenariosApi.listRuns).toHaveBeenCalledTimes(3))
expect(mockedScenariosApi.listRuns).toHaveBeenLastCalledWith(
expect.objectContaining({ cursor: 'a-page-2' }),
)
expect(screen.getByText('Page 2')).toBeInTheDocument()
await act(async () => {
reloadedPage.resolve({ items: [PAGE_TWO_RUN], pagination: { limit: 25, has_more: false } })
})
Expand Down
23 changes: 16 additions & 7 deletions frontend/src/components/History/ScenarioHistory.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -138,6 +138,7 @@ export default function ScenarioHistory({
const [runs, setRuns] = useState<ScenarioRunListItem[]>([])
const [error, setError] = useState<string | null>(null)
const pending = useRef(false)
const lastReadFailed = useRef(false)
const optionsPending = useRef(false)
const [optionsError, setOptionsError] = useState<string | null>(null)
const [scenarioOptions, setScenarioOptions] = useState<string[]>([])
Expand Down Expand Up @@ -263,6 +264,8 @@ export default function ScenarioHistory({
reference_id: filters.referenceId || undefined,
}).then((response) => {
if (cancelled) return
pending.current = false
lastReadFailed.current = false
setRuns(response.items)
setNow(Date.now())
setHasMore(response.pagination.has_more)
Expand All @@ -271,15 +274,15 @@ export default function ScenarioHistory({
setError(null)
}).catch((requestError: unknown) => {
if (cancelled) return
pending.current = false
lastReadFailed.current = true
if (!quiet) {
setRuns([])
setHasMore(false)
setNextCursor(undefined)
}
setSettledRequestId(requestId)
setError(toApiError(requestError).detail)
}).finally(() => {
if (!cancelled) pending.current = false
})
return () => {
cancelled = true
Expand All @@ -296,13 +299,19 @@ export default function ScenarioHistory({
validReference,
])

// History reads can be slow, so a queue change never starts a second read: it waits for the
// read in flight (this effect runs again once it settles). After a failed read, the
// auto-refresh backoff decides when to read again.
useEffect(() => {
if (queueRevision === undefined) return
const previousRevision = lastQueueRevisionRef.current
if (lastQueueRevisionRef.current === null) {
lastQueueRevisionRef.current = queueRevision
return
}
if (lastQueueRevisionRef.current === queueRevision || pending.current) return
lastQueueRevisionRef.current = queueRevision
if (previousRevision === null || previousRevision === queueRevision) return
reloadCurrentPage()
}, [queueRevision, reloadCurrentPage])
if (!lastReadFailed.current) reloadCurrentPage()
}, [queueRevision, settledRequestId, reloadCurrentPage])

const setFilter = <K extends keyof ScenarioHistoryFilters>(
key: K,
Expand All @@ -326,7 +335,7 @@ export default function ScenarioHistory({
if (!optionsPending.current) setOptionsRevision((revision: number) => revision + 1)
reloadCurrentPage()
}
}, validReference && !displayLoading)
}, validReference && !displayLoading, error !== null)

return (
<div className={styles.root}>
Expand Down
12 changes: 12 additions & 0 deletions frontend/src/components/Home/Home.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -353,6 +353,18 @@ describe('Home', () => {
expect(screen.queryByText('Attack service unavailable')).not.toBeInTheDocument()
})

it('should back off automatic refreshes while a source keeps failing', async () => {
mockScans.mockRejectedValue(new Error('Scan history unavailable'))
render(<TestWrapper><Home {...defaultProps} /></TestWrapper>)
await screen.findByText('Scan history unavailable')
await advanceAutoRefresh()
await waitFor(() => expect(mockScans).toHaveBeenCalledTimes(2))
await advanceAutoRefresh()
expect(mockScans).toHaveBeenCalledTimes(2)
await advanceAutoRefresh()
await waitFor(() => expect(mockScans).toHaveBeenCalledTimes(3))
})

it('should show an identical source error only once', async () => {
mockAttacks.mockRejectedValueOnce(new Error('Recent service unavailable'))
mockScans.mockRejectedValueOnce(new Error('Recent service unavailable'))
Expand Down
3 changes: 2 additions & 1 deletion frontend/src/components/Home/Home.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -163,8 +163,9 @@ export default function Home({
.sort((first: RecentItem, second: RecentItem) => activityTime(second.updatedAt) - activityTime(first.updatedAt))
.slice(0, RECENT_WORK_LIMIT)
const refresh = (): void => { setRevision((value: number) => value + 1) }
const refreshFailed = Boolean(attackResult?.error || scanResult?.error || operationResult?.error)
useAutoRefresh(refresh, ready && attackResult?.key === requestKey
&& scanResult?.key === requestKey && operationResult?.key === requestKey)
&& scanResult?.key === requestKey && operationResult?.key === requestKey, refreshFailed)

return (
<div className={styles.root} data-testid="home-view">
Expand Down
55 changes: 53 additions & 2 deletions frontend/src/hooks/useAutoRefresh.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -5,17 +5,68 @@ import { AUTO_REFRESH_INTERVAL_MS, useAutoRefresh } from './useAutoRefresh'
interface RefreshViewProps {
readonly refresh: () => void | Promise<void>
readonly enabled?: boolean
readonly failing?: boolean
}

function RefreshView({ refresh, enabled = true }: RefreshViewProps) {
useAutoRefresh(refresh, enabled)
function RefreshView({ refresh, enabled = true, failing = false }: RefreshViewProps) {
useAutoRefresh(refresh, enabled, failing)
return <input aria-label="Draft" defaultValue="Keep this" />
}

async function advanceIntervals(count: number): Promise<void> {
await act(async () => { await jest.advanceTimersByTimeAsync(AUTO_REFRESH_INTERVAL_MS * count) })
}

describe('useAutoRefresh', () => {
beforeEach(() => { jest.useFakeTimers() })
afterEach(() => { jest.useRealTimers(); jest.restoreAllMocks() })

it('should double the wait after each failed read and resume the normal interval after a success', async () => {
const refresh = jest.fn()
const rendered = render(<RefreshView refresh={refresh} failing />)
await advanceIntervals(1)
expect(refresh).toHaveBeenCalledTimes(1)
await advanceIntervals(1)
expect(refresh).toHaveBeenCalledTimes(1)
await advanceIntervals(1)
expect(refresh).toHaveBeenCalledTimes(2)
await advanceIntervals(3)
expect(refresh).toHaveBeenCalledTimes(2)
await advanceIntervals(1)
expect(refresh).toHaveBeenCalledTimes(3)
rendered.rerender(<RefreshView refresh={refresh} />)
await advanceIntervals(2)
expect(refresh).toHaveBeenCalledTimes(5)
})

it('should cap the failure backoff at sixteen intervals', async () => {
const refresh = jest.fn()
render(<RefreshView refresh={refresh} failing />)
// Retries after 1, 2, 4, 8, 16, then 16 and 16 more intervals.
await advanceIntervals(62)
expect(refresh).toHaveBeenCalledTimes(6)
await advanceIntervals(1)
expect(refresh).toHaveBeenCalledTimes(7)
})

it('should wait the backoff when a failing view becomes visible again', async () => {
const refresh = jest.fn()
const visibility = jest.spyOn(document, 'visibilityState', 'get').mockReturnValue('visible')
render(<RefreshView refresh={refresh} failing />)
await advanceIntervals(1)
expect(refresh).toHaveBeenCalledTimes(1)
visibility.mockReturnValue('hidden')
await advanceIntervals(1)
visibility.mockReturnValue('visible')
await act(async () => { document.dispatchEvent(new Event('visibilitychange')) })
expect(refresh).toHaveBeenCalledTimes(1)
visibility.mockReturnValue('hidden')
await advanceIntervals(1)
visibility.mockReturnValue('visible')
await act(async () => { document.dispatchEvent(new Event('visibilitychange')) })
expect(refresh).toHaveBeenCalledTimes(2)
})

it('should wait a full minute and keep the view mounted', async () => {
const refresh = jest.fn()
render(<RefreshView refresh={refresh} />)
Expand Down
28 changes: 24 additions & 4 deletions frontend/src/hooks/useAutoRefresh.ts
Original file line number Diff line number Diff line change
@@ -1,30 +1,50 @@
import { useEffect, useEffectEvent, useRef } from 'react'

export const AUTO_REFRESH_INTERVAL_MS = 60_000
/** Longest wait, in refresh intervals, while the view's last read keeps failing. */
const MAX_AUTO_REFRESH_BACKOFF_INTERVALS = 16

/** Revalidates a visible view without owning its data or initial load. */
export function useAutoRefresh(refresh: () => void | Promise<void>, enabled: boolean = true): void {
/**
* Revalidates a visible view without owning its data or initial load.
* While `failing` reports that the view's last read failed, each retry doubles the wait,
* up to MAX_AUTO_REFRESH_BACKOFF_INTERVALS, so an overloaded backend is not polled at full rate.
*/
export function useAutoRefresh(
refresh: () => void | Promise<void>,
enabled: boolean = true,
failing: boolean = false,
): void {
const onRefresh = useEffectEvent(refresh)
const isFailing = useEffectEvent((): boolean => failing)
const running = useRef(false)
const failedRetries = useRef(0)

useEffect(() => {
if (!enabled) return
let lastCheck = performance.now()
let intervalsSinceCheck = 0
const intervalsDue = (): number => (isFailing()
? Math.min(2 ** failedRetries.current, MAX_AUTO_REFRESH_BACKOFF_INTERVALS) : 1)
const check = async (): Promise<void> => {
if (document.visibilityState === 'hidden' || running.current) return
running.current = true
lastCheck = performance.now()
intervalsSinceCheck = 0
failedRetries.current = isFailing() ? failedRetries.current + 1 : 0
try {
await onRefresh()
} finally {
running.current = false
}
}
const onInterval = (): void => { void check() }
const onInterval = (): void => {
intervalsSinceCheck += 1
if (intervalsSinceCheck >= intervalsDue()) void check()
}
let timer = window.setInterval(onInterval, AUTO_REFRESH_INTERVAL_MS)
const onVisibilityChange = (): void => {
if (document.visibilityState === 'hidden'
|| performance.now() - lastCheck < AUTO_REFRESH_INTERVAL_MS) return
|| performance.now() - lastCheck < AUTO_REFRESH_INTERVAL_MS * intervalsDue()) return
window.clearInterval(timer)
timer = window.setInterval(onInterval, AUTO_REFRESH_INTERVAL_MS)
void check()
Expand Down
Loading
Loading