From 44f698c55a600c82fdfe527afb530a1f4ec0af0e Mon Sep 17 00:00:00 2001 From: Behnam Ousat Date: Wed, 25 Nov 2026 11:30:51 -0800 Subject: [PATCH] FIX: Bound slow scenario-history reads and stop false compatibility dialog Long scenario-history reads kept running after the proxy abandoned the request, piled up on every frontend refresh, exhausted the connection pool, and starved the default executor. The /api/version handshake then timed out and the GUI showed a misleading "deploy matching builds" dialog. - AzureSQLMemory: set a pyodbc query timeout on async-engine connections so the driver cancels long statements server-side and frees the connection. Cancelling the asyncio task does not interrupt the ODBC call. Configurable via query_timeout_seconds / AZURE_SQL_DB_QUERY_TIMEOUT_SECONDS (default 300, 0 disables); schema migrations are not limited. - /api/version: read build info once in the app lifespan instead of on the default executor per request. - useAutoRefresh: optional exponential backoff (up to 16 intervals) while a view's last read failed; used by Scanner History and Home, which both call GET /api/scenarios/runs. - Scanner History: queue changes wait for the in-flight read instead of starting a parallel one, and do not bypass the backoff after a failure. - Compatibility gate: a failed or timed-out version check (now 30 s) shows "PyRIT backend unavailable" instead of build-mismatch guidance. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- .env_example | 3 + doc/code/memory/0_memory.md | 1 + .../src/components/CompatibilityGate.test.tsx | 17 ++- frontend/src/components/CompatibilityGate.tsx | 24 ++-- .../History/ScenarioHistory.test.tsx | 46 ++++++-- .../components/History/ScenarioHistory.tsx | 23 ++-- frontend/src/components/Home/Home.test.tsx | 12 ++ frontend/src/components/Home/Home.tsx | 3 +- frontend/src/hooks/useAutoRefresh.test.tsx | 55 ++++++++- frontend/src/hooks/useAutoRefresh.ts | 28 ++++- frontend/src/services/api.test.ts | 2 +- frontend/src/services/api.ts | 5 +- frontend/src/services/compatibility.test.ts | 9 +- frontend/src/services/compatibility.ts | 12 +- pyrit/backend/main.py | 1 + pyrit/backend/routes/version.py | 50 ++++---- pyrit/memory/azure_sql_memory.py | 49 +++++++- tests/unit/backend/test_api_routes.py | 108 +++++------------- tests/unit/backend/test_main.py | 10 ++ tests/unit/memory/test_azure_sql_memory.py | 63 +++++++++- 20 files changed, 380 insertions(+), 141 deletions(-) diff --git a/.env_example b/.env_example index 36ec6b713d..3fd0ef591e 100644 --- a/.env_example +++ b/.env_example @@ -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 diff --git a/doc/code/memory/0_memory.md b/doc/code/memory/0_memory.md index c542bf9500..1e1b14d51b 100644 --- a/doc/code/memory/0_memory.md +++ b/doc/code/memory/0_memory.md @@ -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. diff --git a/frontend/src/components/CompatibilityGate.test.tsx b/frontend/src/components/CompatibilityGate.test.tsx index d06bf271c1..7ebe8d6cae 100644 --- a/frontend/src/components/CompatibilityGate.test.tsx +++ b/frontend/src/components/CompatibilityGate.test.tsx @@ -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() @@ -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) => { diff --git a/frontend/src/components/CompatibilityGate.tsx b/frontend/src/components/CompatibilityGate.tsx index 06f440539d..1b16ca2a73 100644 --- a/frontend/src/components/CompatibilityGate.tsx +++ b/frontend/src/components/CompatibilityGate.tsx @@ -8,6 +8,7 @@ export function CompatibilityGate({ children }: { children: ReactNode }) { const [admitted, setAdmitted] = useState(false) const notice = useRef(null) const { modalAttributes } = useModalAttributes({ trapFocus: true }) + const failed = snapshot.status === 'blocked' || snapshot.status === 'unavailable' useEffect(() => { let active = true @@ -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' &&
Checking frontend and backend compatibility...
} - {snapshot.status === 'blocked' && ( + {failed && ( event.preventDefault()} style={{ padding: '2rem', maxWidth: 'min(42rem, calc(100vw - 2rem))', overflowWrap: 'anywhere' }} > -

PyRIT compatibility blocked

+

+ {snapshot.status === 'unavailable' ? 'PyRIT backend unavailable' : 'PyRIT compatibility blocked'} +

{snapshot.reason}

- {snapshot.expected &&

Backend expected: {snapshot.expected}

} - {snapshot.actual &&

Frontend sent: {snapshot.actual}

} -

Deploy the frontend and backend from the same version and full Git commit, then reload this page.

+ {snapshot.status === 'blocked' && ( + <> + {snapshot.expected &&

Backend expected: {snapshot.expected}

} + {snapshot.actual &&

Frontend sent: {snapshot.actual}

} +

Deploy the frontend and backend from the same version and full Git commit, then reload this page.

+ + )} + {snapshot.status === 'unavailable' && ( +

This does not indicate a version mismatch. Wait a few minutes, then reload this page.

+ )}

Further business requests are disabled. No failed operation will be replayed automatically.

{admitted &&

Your existing UI state is retained in this page. Reloading will discard unsaved work.

} diff --git a/frontend/src/components/History/ScenarioHistory.test.tsx b/frontend/src/components/History/ScenarioHistory.test.tsx index 1eea7c23a4..1f337a51b9 100644 --- a/frontend/src/components/History/ScenarioHistory.test.tsx +++ b/frontend/src/components/History/ScenarioHistory.test.tsx @@ -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( + +
+ +
+
, + ) + expect(mockedScenariosApi.listRuns).toHaveBeenCalledTimes(1) + }) + it('distinguishes unfiltered and filtered empty states', async () => { const user = userEvent.setup() const onNavigate = jest.fn() @@ -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)) @@ -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 } }) }) diff --git a/frontend/src/components/History/ScenarioHistory.tsx b/frontend/src/components/History/ScenarioHistory.tsx index 02b8d2e34e..59350d6e1f 100644 --- a/frontend/src/components/History/ScenarioHistory.tsx +++ b/frontend/src/components/History/ScenarioHistory.tsx @@ -138,6 +138,7 @@ export default function ScenarioHistory({ const [runs, setRuns] = useState([]) const [error, setError] = useState(null) const pending = useRef(false) + const lastReadFailed = useRef(false) const optionsPending = useRef(false) const [optionsError, setOptionsError] = useState(null) const [scenarioOptions, setScenarioOptions] = useState([]) @@ -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) @@ -271,6 +274,8 @@ export default function ScenarioHistory({ setError(null) }).catch((requestError: unknown) => { if (cancelled) return + pending.current = false + lastReadFailed.current = true if (!quiet) { setRuns([]) setHasMore(false) @@ -278,8 +283,6 @@ export default function ScenarioHistory({ } setSettledRequestId(requestId) setError(toApiError(requestError).detail) - }).finally(() => { - if (!cancelled) pending.current = false }) return () => { cancelled = true @@ -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 = ( key: K, @@ -326,7 +335,7 @@ export default function ScenarioHistory({ if (!optionsPending.current) setOptionsRevision((revision: number) => revision + 1) reloadCurrentPage() } - }, validReference && !displayLoading) + }, validReference && !displayLoading, error !== null) return (
diff --git a/frontend/src/components/Home/Home.test.tsx b/frontend/src/components/Home/Home.test.tsx index 34581bc48a..d347efac85 100644 --- a/frontend/src/components/Home/Home.test.tsx +++ b/frontend/src/components/Home/Home.test.tsx @@ -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() + 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')) diff --git a/frontend/src/components/Home/Home.tsx b/frontend/src/components/Home/Home.tsx index a645952097..436efedb3e 100644 --- a/frontend/src/components/Home/Home.tsx +++ b/frontend/src/components/Home/Home.tsx @@ -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 (
diff --git a/frontend/src/hooks/useAutoRefresh.test.tsx b/frontend/src/hooks/useAutoRefresh.test.tsx index 32003fee9c..e3ec2c730b 100644 --- a/frontend/src/hooks/useAutoRefresh.test.tsx +++ b/frontend/src/hooks/useAutoRefresh.test.tsx @@ -5,17 +5,68 @@ import { AUTO_REFRESH_INTERVAL_MS, useAutoRefresh } from './useAutoRefresh' interface RefreshViewProps { readonly refresh: () => void | Promise 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 } +async function advanceIntervals(count: number): Promise { + 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() + 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() + await advanceIntervals(2) + expect(refresh).toHaveBeenCalledTimes(5) + }) + + it('should cap the failure backoff at sixteen intervals', async () => { + const refresh = jest.fn() + render() + // 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() + 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() diff --git a/frontend/src/hooks/useAutoRefresh.ts b/frontend/src/hooks/useAutoRefresh.ts index ba34d100f4..a2506d69cd 100644 --- a/frontend/src/hooks/useAutoRefresh.ts +++ b/frontend/src/hooks/useAutoRefresh.ts @@ -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, 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, + 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 => { 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() diff --git a/frontend/src/services/api.test.ts b/frontend/src/services/api.test.ts index cbb8cbcaf6..2dc99be4bf 100644 --- a/frontend/src/services/api.test.ts +++ b/frontend/src/services/api.test.ts @@ -641,7 +641,7 @@ describe("api service", () => { const result = await versionApi.getVersion(); - expect(apiClient.get).toHaveBeenCalledWith("/version"); + expect(apiClient.get).toHaveBeenCalledWith("/version", { timeout: 30_000 }); expect(result).toEqual({ version: "0.10.1" }); }); }); diff --git a/frontend/src/services/api.ts b/frontend/src/services/api.ts index 7691fa5208..cf3943819e 100644 --- a/frontend/src/services/api.ts +++ b/frontend/src/services/api.ts @@ -360,9 +360,12 @@ export const healthApi = { }, } +// The version check reads no database, so a slow answer means the backend is unavailable. +const VERSION_CHECK_TIMEOUT_MS = 30_000 + export const versionApi = { getVersion: async () => { - const response = await apiClient.get('/version') + const response = await apiClient.get('/version', { timeout: VERSION_CHECK_TIMEOUT_MS }) return response.data }, } diff --git a/frontend/src/services/compatibility.test.ts b/frontend/src/services/compatibility.test.ts index 75d67e4dff..3583c4226e 100644 --- a/frontend/src/services/compatibility.test.ts +++ b/frontend/src/services/compatibility.test.ts @@ -59,9 +59,12 @@ describe('CompatibilityStore', () => { expect(store.getSnapshot().status).toBe('blocked') }) - it('blocks a failed authenticated handshake', async () => { + it('reports a failed or timed-out handshake as unavailable rather than a build mismatch', async () => { const store = new CompatibilityStore(bundledId) - await store.verify(async () => { throw new Error('401') }) - expect(store.getSnapshot().status).toBe('blocked') + await store.verify(async () => { throw new Error('timeout of 30000ms exceeded') }) + expect(store.getSnapshot()).toMatchObject({ status: 'unavailable', reason: expect.stringMatching(/did not answer/) }) + expect(() => store.assertReady()).toThrow() + store.block('Deployment changed') + expect(store.getSnapshot().status).toBe('unavailable') }) }) diff --git a/frontend/src/services/compatibility.ts b/frontend/src/services/compatibility.ts index e81d295d8c..8ea045584a 100644 --- a/frontend/src/services/compatibility.ts +++ b/frontend/src/services/compatibility.ts @@ -7,6 +7,11 @@ export const COMPATIBILITY_HEADER = 'PyRIT-Compatibility-ID' export type CompatibilitySnapshot = | { status: 'checking' | 'ready' } | { status: 'blocked'; reason: string; expected?: string; actual?: string } + | { status: 'unavailable'; reason: string } + +const BACKEND_UNAVAILABLE_REASON = + 'The backend did not answer the authenticated version check. It may be overloaded, restarting, or unreachable, ' + + 'or your sign-in may have expired.' export class CompatibilityStore { private snapshot: CompatibilitySnapshot = { status: 'checking' } @@ -28,7 +33,7 @@ export class CompatibilityStore { } block(reason: string, expected?: unknown, actual?: unknown): void { - if (this.snapshot.status === 'blocked') return + if (this.snapshot.status === 'blocked' || this.snapshot.status === 'unavailable') return this.publish({ status: 'blocked', reason, @@ -67,7 +72,10 @@ export class CompatibilityStore { this.publish({ status: 'ready' }) } } catch { - this.block('The authenticated backend version check failed. Check your connection and sign-in before reloading.') + // A failed or timed-out check says nothing about build identity, so it must not suggest a mismatch. + if (this.snapshot.status === 'checking') { + this.publish({ status: 'unavailable', reason: BACKEND_UNAVAILABLE_REASON }) + } } } } diff --git a/pyrit/backend/main.py b/pyrit/backend/main.py index b097200d47..b07f8179fb 100644 --- a/pyrit/backend/main.py +++ b/pyrit/backend/main.py @@ -71,6 +71,7 @@ async def lifespan(app: FastAPI) -> AsyncGenerator[None, None]: 3. ``PYRIT_CONFIG_FILE`` local path or Azure Blob URI when set """ app.state.compatibility_id = await asyncio.to_thread(_compatibility.get_compatibility_id) + app.state.build_info = await asyncio.to_thread(version.read_build_info) app.state.authentication_policy = resolve_authentication_policy() if app.state.authentication_policy.enabled and not app.state.authentication_policy.admin_group_id: logger.warning("ENTRA_ADMIN_GROUP_ID is not set; authenticated users cannot access administrator routes.") diff --git a/pyrit/backend/routes/version.py b/pyrit/backend/routes/version.py index e6aae3192a..fe3173eb4e 100644 --- a/pyrit/backend/routes/version.py +++ b/pyrit/backend/routes/version.py @@ -3,7 +3,6 @@ """API routes for version information.""" -import asyncio import logging from pathlib import Path from typing import cast @@ -47,6 +46,25 @@ def _load_build_info(build_info_path: Path) -> BuildInfo: return BuildInfo.model_validate_json(file.read()) +def read_build_info(build_info_path: Path = Path("/app/build_info.json")) -> BuildInfo: + """ + Read Docker build metadata once at startup, so version requests never touch the disk or a thread pool. + + Args: + build_info_path (Path): Path to the build metadata JSON file. Defaults to the Docker image location. + + Returns: + BuildInfo: Parsed build metadata, or an empty ``BuildInfo`` when the file is absent or invalid. + """ + if not build_info_path.exists(): + return BuildInfo() + try: + return _load_build_info(build_info_path) + except Exception as e: + logger.warning(f"Failed to load build info: {e}") + return BuildInfo() + + class VersionResponse(BaseModel): """Version information response model.""" @@ -66,29 +84,15 @@ async def get_version_async(request: Request) -> VersionResponse: """ Get version information for the PyRIT installation. - Returns version from pyrit.__version__ and additional build info - if running in Docker (from /app/build_info.json). + Returns version from pyrit.__version__ and the Docker build info that the app + lifespan read from /app/build_info.json at startup. Returns: VersionResponse: Version information including build metadata. """ version = pyrit.__version__ - display = version - source = None - commit = None - modified = None - - # Try to load build info from Docker - build_info_path = Path("/app/build_info.json") - if await asyncio.to_thread(build_info_path.exists): - try: - build_info = await asyncio.to_thread(_load_build_info, build_info_path) - source = build_info.source - commit = build_info.commit - modified = build_info.modified - display = build_info.display or version - except Exception as e: - logger.warning(f"Failed to load build info: {e}") + # The app lifespan publishes a BuildInfo; it is unset before startup. + build_info = cast("BuildInfo | None", getattr(request.app.state, "build_info", None)) or BuildInfo() # Detect current database backend database_info: str | None = None @@ -110,10 +114,10 @@ async def get_version_async(request: Request) -> VersionResponse: return VersionResponse( version=version, compatibility_id=request.app.state.compatibility_id, - source=source, - commit=commit, - modified=modified, - display=display, + source=build_info.source, + commit=build_info.commit, + modified=build_info.modified, + display=build_info.display or version, database_info=database_info, default_labels=default_labels, default_operation=default_operation, diff --git a/pyrit/memory/azure_sql_memory.py b/pyrit/memory/azure_sql_memory.py index 6a2e310749..9eac9eb1e2 100644 --- a/pyrit/memory/azure_sql_memory.py +++ b/pyrit/memory/azure_sql_memory.py @@ -51,6 +51,7 @@ from pyrit.models import AttackResultRole, ConversationStats if TYPE_CHECKING: + import pyodbc from azure.core.credentials import AccessToken from sqlalchemy.sql import SQLColumnExpression @@ -81,6 +82,9 @@ class AzureSQLMemory(MemoryInterface, metaclass=Singleton): # Optional environment variable for production connection string to prevent accidental schema migrations on prod AZURE_SQL_DB_CONNECTION_STRING_PROD: str = "AZURE_SQL_DB_CONNECTION_STRING_PROD" + AZURE_SQL_DB_QUERY_TIMEOUT_SECONDS: str = "AZURE_SQL_DB_QUERY_TIMEOUT_SECONDS" + DEFAULT_QUERY_TIMEOUT_SECONDS: int = 300 + def __init__( self, *, @@ -90,6 +94,7 @@ def __init__( verbose: bool = False, skip_schema_migration: bool = True, silent: bool = False, + query_timeout_seconds: int | None = None, _defer_initialization: bool = False, ) -> None: """ @@ -106,7 +111,15 @@ def __init__( skip_schema_migration (bool): Whether to skip schema migration. Defaults to True. Set to False to explicitly migrate a non-production database during initialization. silent (bool): If True, suppresses schema migration console output. Defaults to False. + query_timeout_seconds (int | None): Seconds after which the driver cancels a statement on the + server and raises, releasing its connection; 0 disables the limit. Applies to the async engine, + not to schema migrations. If not provided, it falls back to the + 'AZURE_SQL_DB_QUERY_TIMEOUT_SECONDS' environment variable, then to 300. + + Raises: + ValueError: If the query timeout is not a non-negative integer. """ + self._query_timeout_seconds = self._resolve_query_timeout_seconds(query_timeout_seconds) self._connection_string = default_values.get_required_value( env_var_name=self.AZURE_SQL_DB_CONNECTION_STRING, passed_value=connection_string ) @@ -191,7 +204,13 @@ async def connect_async() -> aioodbc.Connection: attrs = dict(params.pop("attrs_before", {})) attrs[self.SQL_COPT_SS_ACCESS_TOKEN] = struct.pack(f" st except ValueError: return None + @classmethod + def _resolve_query_timeout_seconds(cls, passed_value: int | None) -> int: + """ + Resolve the per-statement timeout from the argument, the environment, or the default. + + Args: + passed_value (int | None): An explicitly passed timeout in seconds. + + Returns: + int: The timeout in seconds; 0 disables it. + + Raises: + ValueError: If the resolved value is not a non-negative integer. + """ + value: int | str = ( + passed_value + if passed_value is not None + else default_values.get_non_required_value(env_var_name=cls.AZURE_SQL_DB_QUERY_TIMEOUT_SECONDS) + ) + if value == "": + return cls.DEFAULT_QUERY_TIMEOUT_SECONDS + if not str(value).isdecimal(): + raise ValueError( + f"Azure SQL query timeout must be a non-negative integer number of seconds (0 disables it); " + f"got {value!r} from query_timeout_seconds or {cls.AZURE_SQL_DB_QUERY_TIMEOUT_SECONDS}." + ) + return int(value) + def _init_storage_io(self) -> None: # Handle for Azure Blob Storage when using Azure SQL memory. self.results_storage_io = AzureBlobStorageIO( diff --git a/tests/unit/backend/test_api_routes.py b/tests/unit/backend/test_api_routes.py index cbb808f694..6971b485b6 100644 --- a/tests/unit/backend/test_api_routes.py +++ b/tests/unit/backend/test_api_routes.py @@ -6,8 +6,6 @@ """ import json -import os -import tempfile import uuid from contextlib import nullcontext from datetime import UTC, datetime @@ -2212,58 +2210,32 @@ def test_get_version_exposes_default_operation_proposal(self, client: TestClient @pytest.mark.parametrize("commit", ["abc123", None]) def test_get_version_with_build_info(self, *, client: TestClient, commit: str | None) -> None: - """Test getting version with build info from Docker.""" - build_info: dict[str, str | bool | None] = { - "source": "git" if commit is not None else "pypi", - "commit": commit, - "modified": False, - "display": "1.0.0-test", - } - # Create a temp file to simulate Docker build info - with tempfile.NamedTemporaryFile(mode="w", suffix=".json", delete=False) as f: - json.dump(build_info, f) - temp_path = f.name - - try: - to_thread_mock = AsyncMock(side_effect=lambda func, *args, **kwargs: func(*args, **kwargs)) - with ( - patch("pyrit.backend.routes.version.Path") as mock_path_class, - patch("pyrit.backend.routes.version.asyncio.to_thread", new=to_thread_mock), - ): - mock_path_instance = MagicMock() - mock_path_instance.exists.return_value = True - mock_path_class.return_value = mock_path_instance - - # Mock open to return our temp file content - with patch("builtins.open", create=True) as mock_open: - mock_open.return_value.__enter__.return_value.read.return_value = json.dumps(build_info) + """Build info read at startup is served without using a worker thread.""" + build_info = version_routes.BuildInfo( + source="git" if commit is not None else "pypi", commit=commit, modified=False, display="1.0.0-test" + ) + with ( + patch.object(app.state, "build_info", build_info, create=True), + patch("asyncio.to_thread", side_effect=AssertionError("version must not use the default executor")), + ): + response = client.get("/api/version") - response = client.get("/api/version") + assert response.status_code == status.HTTP_200_OK + data = response.json() + for key, value in build_info.model_dump().items(): + assert data[key] == value - assert response.status_code == status.HTTP_200_OK - data = response.json() - for key, value in build_info.items(): - assert data[key] == value - to_thread_mock.assert_any_await(version_routes._load_build_info, mock_path_instance) - finally: - os.unlink(temp_path) - - def test_get_version_build_info_load_failure(self, client: TestClient) -> None: - """Test getting version when build_info.json exists but fails to load.""" - with patch("pyrit.backend.routes.version.Path") as mock_path_class: - mock_path_instance = MagicMock() - mock_path_instance.exists.return_value = True - mock_path_class.return_value = mock_path_instance - - with patch("builtins.open", side_effect=OSError("permission denied")): - response = client.get("/api/version") + def test_get_version_build_info_absent_display_falls_back(self, client: TestClient) -> None: + """A build-info file without `display` falls back to the package version.""" + with patch.object(app.state, "build_info", version_routes.BuildInfo(source="git"), create=True): + response = client.get("/api/version") assert response.status_code == status.HTTP_200_OK data = response.json() - # Falls back to default values when load fails - assert "version" in data - assert data["source"] is None + assert data["source"] == "git" assert data["commit"] is None + assert data["modified"] is None + assert data["display"] == data["version"] def test_build_info_keys_are_not_required(self) -> None: """Every build-info key may be absent and defaults to None.""" @@ -2271,26 +2243,16 @@ def test_build_info_keys_are_not_required(self) -> None: source=None, commit=None, modified=None, display=None ) - def test_get_version_build_info_absent_display_falls_back(self, client: TestClient) -> None: - """A build-info file without `display` falls back to the package version.""" - to_thread_mock = AsyncMock(side_effect=lambda func, *args, **kwargs: func(*args, **kwargs)) - with ( - patch("pyrit.backend.routes.version.Path") as mock_path_class, - patch("pyrit.backend.routes.version.asyncio.to_thread", new=to_thread_mock), - patch.object(version_routes, "_load_build_info", return_value=version_routes.BuildInfo(source="git")), - ): - mock_path_instance = MagicMock() - mock_path_instance.exists.return_value = True - mock_path_class.return_value = mock_path_instance + def test_read_build_info_absent_file_is_empty(self, tmp_path: Path) -> None: + assert version_routes.read_build_info(tmp_path / "build_info.json") == version_routes.BuildInfo() - response = client.get("/api/version") + @pytest.mark.parametrize("content", [json.dumps({"source": "git", "commit": 123, "display": "abc"}), "{not json"]) + def test_read_build_info_ignores_invalid_file(self, *, tmp_path: Path, content: str) -> None: + """An unreadable build-info file falls back to defaults instead of failing startup.""" + build_info_path = tmp_path / "build_info.json" + build_info_path.write_text(content) - assert response.status_code == status.HTTP_200_OK - data = response.json() - assert data["source"] == "git" - assert data["commit"] is None - assert data["modified"] is None - assert data["display"] == data["version"] + assert version_routes.read_build_info(build_info_path) == version_routes.BuildInfo() def test_load_build_info_reads_known_keys(self, tmp_path: Path) -> None: """Known keys are returned as written and extra keys from the Docker build are dropped.""" @@ -2331,20 +2293,6 @@ def test_load_build_info_rejects_wrong_value_type(self, *, tmp_path: Path, key: with pytest.raises(ValidationError, match=key): version_routes._load_build_info(build_info_path) - def test_get_version_ignores_malformed_build_info(self, *, client: TestClient, tmp_path: Path) -> None: - """A wrongly typed build-info value falls back to defaults instead of failing the response.""" - build_info_path = tmp_path / "build_info.json" - build_info_path.write_text(json.dumps({"source": "git", "commit": 123, "display": "abc"})) - - with patch("pyrit.backend.routes.version.Path", return_value=build_info_path): - response = client.get("/api/version") - - assert response.status_code == status.HTTP_200_OK - data = response.json() - assert data["source"] is None - assert data["commit"] is None - assert data["display"] == data["version"] - class TestScoreRoutes: """Tests for score API routes.""" diff --git a/tests/unit/backend/test_main.py b/tests/unit/backend/test_main.py index fcd97bbcda..e6d83be602 100644 --- a/tests/unit/backend/test_main.py +++ b/tests/unit/backend/test_main.py @@ -29,6 +29,7 @@ from pyrit.backend.authentication_policy import AuthenticationConfigurationError from pyrit.backend.main import SPAStaticFiles, app, lifespan, setup_frontend from pyrit.backend.models import CreateConverterRequest +from pyrit.backend.routes.version import BuildInfo from pyrit.backend.services import ConverterService, ScenarioRunService, get_converter_service from pyrit.backend.services.manual_send_scheduler import get_manual_send_scheduler from pyrit.backend.services.message_send_service import get_message_send_service @@ -217,8 +218,15 @@ def read_stamp() -> str: assert threading.get_ident() != event_loop_thread_id return compatibility_id + build_info = BuildInfo(source="git", commit="abc123") + + def read_build_info() -> BuildInfo: + assert threading.get_ident() != event_loop_thread_id + return build_info + with ( patch("pyrit._compatibility.get_compatibility_id", side_effect=read_stamp) as stamp_reader, + patch("pyrit.backend.routes.version.read_build_info", side_effect=read_build_info) as build_info_reader, patch.object(ConfigurationLoader, "load_with_overrides", return_value=fake_config), patch.object(ConfigurationLoader, "initialize_pyrit_async", new=AsyncMock()) as init_mock, patch("pyrit.backend.main.setup_frontend"), @@ -227,8 +235,10 @@ def read_stamp() -> str: pass stamp_reader.assert_called_once() + build_info_reader.assert_called_once() init_mock.assert_awaited_once_with(raise_on_initializer_error=True) assert app.state.compatibility_id == compatibility_id + assert app.state.build_info == build_info assert app.state.default_labels == {} assert app.state.max_concurrent_scenario_runs == fake_config.max_concurrent_scenario_runs assert app.state.allow_custom_initializers is False diff --git a/tests/unit/memory/test_azure_sql_memory.py b/tests/unit/memory/test_azure_sql_memory.py index 6213abe189..d2f128f4ae 100644 --- a/tests/unit/memory/test_azure_sql_memory.py +++ b/tests/unit/memory/test_azure_sql_memory.py @@ -6,7 +6,7 @@ from collections.abc import AsyncGenerator, MutableSequence, Sequence from datetime import UTC, datetime from typing import TYPE_CHECKING, cast -from unittest.mock import MagicMock, patch +from unittest.mock import AsyncMock, MagicMock, patch import pytest from sqlalchemy import inspect, or_, select, text @@ -1022,6 +1022,67 @@ def decorator(fn): captured_fn(None, None, ["some_connection_string"], {}) +def _construct_memory_with_query_timeout(*, query_timeout_seconds: int | None, env_value: str) -> AzureSQLMemory: + with ( + patch.object(Singleton, "_instances", {}), + patch.object(AzureSQLMemory, "_create_engine"), + patch.object(AzureSQLMemory, "_enable_azure_authorization"), + patch.dict(os.environ, {AzureSQLMemory.AZURE_SQL_DB_QUERY_TIMEOUT_SECONDS: env_value}), + ): + return cast( + "AzureSQLMemory", + AzureSQLMemory( + connection_string="Server=tcp:dev.database.windows.net;", + results_container_url="https://test.blob.core.windows.net/test", + results_sas_token="valid_sas_token", + query_timeout_seconds=query_timeout_seconds, + _defer_initialization=True, + ), + ) + + +@pytest.mark.parametrize( + ("query_timeout_seconds", "env_value", "expected"), + [(None, "", 300), (None, "45", 45), (10, "45", 10), (0, "45", 0)], +) +def test_query_timeout_resolves_argument_then_environment_then_default( + *, query_timeout_seconds: int | None, env_value: str, expected: int +) -> None: + memory = _construct_memory_with_query_timeout(query_timeout_seconds=query_timeout_seconds, env_value=env_value) + assert memory._query_timeout_seconds == expected + + +@pytest.mark.parametrize(("query_timeout_seconds", "env_value"), [(-1, ""), (None, "-5"), (None, "1.5"), (None, "x")]) +def test_query_timeout_rejects_invalid_value(*, query_timeout_seconds: int | None, env_value: str) -> None: + with pytest.raises(ValueError, match="non-negative integer"): + _construct_memory_with_query_timeout(query_timeout_seconds=query_timeout_seconds, env_value=env_value) + + +async def test_async_connections_apply_query_timeout(uninitialized_memory_interface: AzureSQLMemory) -> None: + """The driver must cancel long statements server-side, since cancelling the awaiting task does not.""" + from sqlalchemy.ext.asyncio import create_async_engine + + memory = uninitialized_memory_interface + memory._connection_string = "mssql+pyodbc://@server.database.windows.net/db?driver=ODBC+Driver+18+for+SQL+Server" + memory._verbose = False + memory._async_auth = {} + memory._query_timeout_seconds = 42 + connection = MagicMock() + with ( + patch("aioodbc.connect", new=AsyncMock(return_value=connection)), + patch("pyrit.memory.azure_sql_memory.AsyncAzureAuth") as auth_class, + patch("pyrit.memory.azure_sql_memory.create_async_engine", wraps=create_async_engine) as create_engine_spy, + ): + auth_class.return_value.get_access_token_async = AsyncMock(return_value=MagicMock(token="token")) + engine = memory._create_async_engine() + try: + assert await create_engine_spy.call_args.kwargs["async_creator"]() is connection + finally: + await engine.dispose() + + assert connection._conn.timeout == 42 + + async def test_reset_database_raises_when_engine_none_async() -> None: obj = AzureSQLMemory.__new__(AzureSQLMemory) obj.engine = None