feat: pre-deploy scan visibility and pinned scanner version (#1378)

* feat: pre-deploy scan visibility and pinned scanner version

Pin managed Trivy installs and add an opt-in pre-deploy scan advisory so a
manual deploy can surface each image's latest scan before it runs.

- Managed Trivy now installs a pinned, known-good version by default for
  reproducible installs. Auto-update still tracks the latest release, and an
  explicit update always pulls the latest.
- Add an opt-in pre-deploy scan advisory: when enabled, deploying a stack from
  the editor first shows each image's latest cached scan severity for review.
  It is visibility only and never blocks; deploy enforcement is unchanged.
- Backend: pre_deploy_scan_advisory setting, PUT
  /security/pre-deploy-scan-advisory, a cache-only GET
  /security/stacks/:name/pre-deploy-summary, and a node-scoped
  getLatestVulnScanByDigestForNode lookup.
- Frontend: advisory toggle on the Security page scanner setup, and a
  PreDeployScanDialog wired into the editor deploy flow that fails open when the
  summary is unavailable.
- Docs: scanner configuration, version pinning, and the advisory.

* fix: harden pre-deploy advisory guard, toggle visibility, and installer busy state

Addresses review findings on the pre-deploy advisory.

- Block a second editor deploy during the async advisory window with a
  synchronous pending ref, cleared on cancel and in the deploy's finally, so a
  double-click can no longer start two deploys.
- Keep the pre-deploy advisory toggle visible to admins whenever the setting is
  on, so it can still be turned off after the scanner becomes unavailable.
- Resolve the managed Trivy version inside the install lock so the busy state and
  serialization cover the latest-version fetch and the managed-install check.
This commit is contained in:
Anso
2026-06-16 00:42:33 -04:00
committed by GitHub
parent 770bead889
commit 7ce045accb
21 changed files with 1093 additions and 23 deletions
@@ -1,5 +1,6 @@
import BashExecModal from '../BashExecModal';
import { PolicyBlockDialog } from '../stack/PolicyBlockDialog';
import { PreDeployScanDialog } from '../stack/PreDeployScanDialog';
import { UpdateReadinessDialog } from '../stack/UpdateReadinessDialog';
import { DeleteStackDialog } from './DeleteStackDialog';
import { UnsavedChangesDialog } from './UnsavedChangesDialog';
@@ -43,6 +44,7 @@ export function ShellOverlays({
stackMonitor, closeStackMonitor,
policyBlock, setPolicyBlock, policyBypassing,
updateReadiness, setUpdateReadiness,
preDeployAdvisory,
stackMisconfigScanId, setStackMisconfigScanId,
diffPreview, setDiffPreview, diffPreviewConfirming, setDiffPreviewConfirming,
} = overlayState;
@@ -98,6 +100,15 @@ export function ShellOverlays({
onProceed={() => updateReadiness?.proceed()}
/>
{/* Pre-deploy scan advisory (visibility only; never blocks) */}
<PreDeployScanDialog
open={preDeployAdvisory !== null}
stackName={preDeployAdvisory?.stackName ?? ''}
images={preDeployAdvisory?.images ?? []}
onCancel={() => preDeployAdvisory?.cancel()}
onDeploy={() => preDeployAdvisory?.proceed()}
/>
{/* Pre-deploy policy block */}
<PolicyBlockDialog
open={policyBlock !== null}
@@ -0,0 +1,67 @@
/**
* fetchPreDeployAdvisory is the pre-deploy gate's data fetch. It returns the
* image list only when the advisory is enabled and the backend answers cleanly;
* every other case returns null ("deploy normally"). Failing open is the whole
* point: the advisory is visibility and must never block a deploy when the
* summary is unavailable (older node, timeout, network error).
*/
import { describe, it, expect, vi, beforeEach } from 'vitest';
vi.mock('@/lib/api', () => ({
apiFetch: vi.fn(),
withDeploySession: (_id: string, o: object) => o,
}));
vi.mock('@/components/ui/toast-store', () => ({
toast: { error: vi.fn(), success: vi.fn(), info: vi.fn(), warning: vi.fn(), loading: vi.fn(() => 'id'), dismiss: vi.fn() },
}));
import { apiFetch } from '@/lib/api';
import { fetchPreDeployAdvisory } from '../useStackActions';
const mockedFetch = vi.mocked(apiFetch);
function response(ok: boolean, body: unknown): Response {
return { ok, json: async () => body } as unknown as Response;
}
beforeEach(() => mockedFetch.mockReset());
describe('fetchPreDeployAdvisory', () => {
it('returns the image list when the advisory is enabled, bound to the captured node', async () => {
mockedFetch.mockResolvedValue(response(true, { enabled: true, images: [{ imageRef: 'nginx:1.14', scan: null }] }));
const result = await fetchPreDeployAdvisory('web', 7);
expect(result).toEqual([{ imageRef: 'nginx:1.14', scan: null }]);
expect(mockedFetch).toHaveBeenCalledWith(
'/security/stacks/web/pre-deploy-summary',
expect.objectContaining({ nodeId: 7 }),
);
});
it('returns null when the advisory is disabled', async () => {
mockedFetch.mockResolvedValue(response(true, { enabled: false }));
expect(await fetchPreDeployAdvisory('web', 1)).toBeNull();
});
it('fails open on a non-ok response (older node without the route)', async () => {
mockedFetch.mockResolvedValue(response(false, {}));
expect(await fetchPreDeployAdvisory('web', null)).toBeNull();
});
it('fails open when the response cannot be read (timeout / abort / network)', async () => {
// A read failure inside the request exercises the same fail-open catch a
// network rejection would, without leaving a stray rejected promise that the
// test runner would flag as unhandled.
mockedFetch.mockResolvedValue({
ok: true,
json: async () => {
throw new Error('aborted');
},
} as unknown as Response);
expect(await fetchPreDeployAdvisory('web', 1)).toBeNull();
});
it('fails open on a malformed body', async () => {
mockedFetch.mockResolvedValue(response(true, { enabled: true, images: 'not-an-array' }));
expect(await fetchPreDeployAdvisory('web', 1)).toBeNull();
});
});
@@ -2,6 +2,7 @@ import { useState, useCallback, useEffect } from 'react';
import { SENCHO_OPEN_LOGS_EVENT } from '@/lib/events';
import type { SenchoOpenLogsDetail } from '@/lib/events';
import type { PolicyBlockPayload, PolicyBlockableAction } from '../../stack/PolicyBlockDialog';
import type { PreDeployScanImage } from '@/types/security';
import type { Node } from '@/context/NodeContext';
type DiffPreview = {
@@ -96,6 +97,17 @@ export function useOverlayState() {
proceed: () => void;
} | null>(null);
// Pre-deploy scan advisory dialog. `proceed` runs the actual deploy when the
// user confirms; opened by useStackActions.deployStack when the advisory
// setting is on. Callback continuation (like updateReadiness), so cancel /
// close / unmount simply discards it with no pending action to leak.
const [preDeployAdvisory, setPreDeployAdvisory] = useState<{
stackName: string;
images: PreDeployScanImage[];
proceed: () => void;
cancel: () => void;
} | null>(null);
const [stackMisconfigScanId, setStackMisconfigScanId] = useState<number | null>(null);
const [diffPreview, setDiffPreview] = useState<DiffPreview | null>(null);
@@ -112,6 +124,7 @@ export function useOverlayState() {
stackMonitor, openAlertSheet, openAutoHeal, closeStackMonitor,
policyBlock, setPolicyBlock, policyBypassing, setPolicyBypassing,
updateReadiness, setUpdateReadiness,
preDeployAdvisory, setPreDeployAdvisory,
stackMisconfigScanId, setStackMisconfigScanId,
diffPreview, setDiffPreview, diffPreviewConfirming, setDiffPreviewConfirming,
} as const;
@@ -86,6 +86,8 @@ function makeOverlay(over: Partial<OverlayState> = {}): OverlayState {
setPolicyBypassing: vi.fn(),
updateReadiness: null,
setUpdateReadiness: vi.fn(),
preDeployAdvisory: null,
setPreDeployAdvisory: vi.fn(),
setDiffPreview: vi.fn(),
...over,
} as unknown as OverlayState;
@@ -253,6 +255,9 @@ describe('useStackActions policy-block dialog wiring', () => {
});
it('opens the dialog with action "deploy" when an editor deploy is blocked', async () => {
// deployStack first fetches the pre-deploy advisory summary; keep it off so
// the flow reaches the deploy POST that returns the policy block.
vi.mocked(apiFetch).mockResolvedValueOnce(new Response(JSON.stringify({ enabled: false }), { status: 200 }));
vi.mocked(apiFetch).mockResolvedValueOnce(new Response(JSON.stringify(policyPayload), { status: 409 }));
const { result, overlayState } = setup();
await result.current.deployStack(mouseEvent);
@@ -309,6 +314,158 @@ describe('useStackActions policy-block dialog wiring', () => {
});
});
describe('useStackActions pre-deploy advisory', () => {
const mouseEvent = { preventDefault: vi.fn(), stopPropagation: vi.fn() } as unknown as React.MouseEvent;
beforeEach(() => {
vi.mocked(apiFetch).mockReset();
lastRunWithLogParams = null;
});
it('opens the advisory before deploying and defers the deploy until the user proceeds', async () => {
const setPreDeployAdvisory = vi.fn();
vi.mocked(apiFetch).mockImplementation(async (url: string) => {
if (String(url).includes('/pre-deploy-summary')) {
return new Response(JSON.stringify({ enabled: true, images: [{ imageRef: 'nginx:1.14', scan: null }] }), { status: 200 });
}
return new Response(null, { status: 200 });
});
const { result } = setup({ overlay: { setPreDeployAdvisory } });
await result.current.deployStack(mouseEvent);
// The advisory opened and the deploy has NOT started (no progress log, no POST).
expect(setPreDeployAdvisory).toHaveBeenCalledWith(
expect.objectContaining({ stackName: 'web', images: [{ imageRef: 'nginx:1.14', scan: null }] }),
);
expect(lastRunWithLogParams).toBeNull();
expect(vi.mocked(apiFetch).mock.calls.filter(c => String(c[0]).includes('/deploy'))).toHaveLength(0);
// Proceeding runs the actual deploy.
const arg = setPreDeployAdvisory.mock.calls[0][0] as { proceed: () => void };
arg.proceed();
await vi.waitFor(() => expect(lastRunWithLogParams).not.toBeNull());
});
it('deploys directly, with no advisory, when the summary is disabled', async () => {
const setPreDeployAdvisory = vi.fn();
vi.mocked(apiFetch).mockResolvedValue(new Response(JSON.stringify({ enabled: false }), { status: 200 }));
const { result } = setup({ overlay: { setPreDeployAdvisory } });
await result.current.deployStack(mouseEvent);
expect(setPreDeployAdvisory).not.toHaveBeenCalled();
expect(lastRunWithLogParams).not.toBeNull();
});
it('deploys directly when the advisory is enabled but no images are returned', async () => {
const setPreDeployAdvisory = vi.fn();
vi.mocked(apiFetch).mockImplementation(async (url: string) => {
if (String(url).includes('/pre-deploy-summary')) {
return new Response(JSON.stringify({ enabled: true, images: [] }), { status: 200 });
}
return new Response(null, { status: 200 });
});
const { result } = setup({ overlay: { setPreDeployAdvisory } });
await result.current.deployStack(mouseEvent);
expect(setPreDeployAdvisory).not.toHaveBeenCalled();
expect(lastRunWithLogParams).not.toBeNull();
});
it('binds the advisory fetch and the deferred deploy to the captured node', async () => {
const setPreDeployAdvisory = vi.fn();
vi.mocked(apiFetch).mockImplementation(async (url: string) => {
if (String(url).includes('/pre-deploy-summary')) {
return new Response(JSON.stringify({ enabled: true, images: [{ imageRef: 'nginx:1.14', scan: null }] }), { status: 200 });
}
return new Response(null, { status: 200 });
});
const { result } = setup({
overlay: { setPreDeployAdvisory },
activeNode: { id: 42, type: 'local' } as Parameters<typeof useStackActions>[0]['activeNode'],
});
await result.current.deployStack(mouseEvent);
expect(apiFetch).toHaveBeenCalledWith(
expect.stringContaining('/pre-deploy-summary'),
expect.objectContaining({ nodeId: 42 }),
);
const arg = (setPreDeployAdvisory.mock.calls[0][0]) as { proceed: () => void };
arg.proceed();
await vi.waitFor(() => expect(lastRunWithLogParams?.nodeId).toBe(42));
});
it('runs the deploy at most once even if proceed fires twice', async () => {
const setPreDeployAdvisory = vi.fn();
vi.mocked(apiFetch).mockImplementation(async (url: string) => {
if (String(url).includes('/pre-deploy-summary')) {
return new Response(JSON.stringify({ enabled: true, images: [{ imageRef: 'nginx:1.14', scan: null }] }), { status: 200 });
}
return new Response(null, { status: 200 });
});
const { result } = setup({ overlay: { setPreDeployAdvisory } });
await result.current.deployStack(mouseEvent);
const arg = (setPreDeployAdvisory.mock.calls[0][0]) as { proceed: () => void };
arg.proceed();
await vi.waitFor(() => expect(lastRunWithLogParams).not.toBeNull());
lastRunWithLogParams = null;
arg.proceed();
await Promise.resolve();
expect(lastRunWithLogParams).toBeNull();
});
it('blocks a second deploy click while the advisory fetch is still pending', async () => {
const setPreDeployAdvisory = vi.fn();
const summaryGate: { release: () => void } = { release: () => {} };
vi.mocked(apiFetch).mockImplementation((url: string) => {
if (String(url).includes('/pre-deploy-summary')) {
return new Promise<Response>((resolve) => {
summaryGate.release = () => resolve(new Response(JSON.stringify({ enabled: false }), { status: 200 }));
});
}
return Promise.resolve(new Response(null, { status: 200 }));
});
const { result } = setup({ overlay: { setPreDeployAdvisory } });
const first = result.current.deployStack(mouseEvent);
const second = result.current.deployStack(mouseEvent); // double-click while the summary is in flight
summaryGate.release();
await Promise.all([first, second]);
await vi.waitFor(() => expect(lastRunWithLogParams).not.toBeNull());
// The second click is blocked before it ever issues a request, so exactly
// one summary fetch and one deploy occur.
const summaryCalls = vi.mocked(apiFetch).mock.calls.filter(c => String(c[0]).includes('/pre-deploy-summary'));
expect(summaryCalls).toHaveLength(1);
});
it('clears the pending guard on cancel so a later deploy is allowed', async () => {
const setPreDeployAdvisory = vi.fn();
vi.mocked(apiFetch).mockImplementation(async (url: string) => {
if (String(url).includes('/pre-deploy-summary')) {
return new Response(JSON.stringify({ enabled: true, images: [{ imageRef: 'nginx:1.14', scan: null }] }), { status: 200 });
}
return new Response(null, { status: 200 });
});
const { result } = setup({ overlay: { setPreDeployAdvisory } });
await result.current.deployStack(mouseEvent);
const arg = (setPreDeployAdvisory.mock.calls[0][0]) as { cancel: () => void };
arg.cancel(); // dismiss the advisory; the guard must release
await result.current.deployStack(mouseEvent); // a fresh deploy must not be blocked
// Calls: open, null (cancel), open again. The third proves the guard cleared
// and the later deploy opened a fresh advisory rather than being blocked.
expect(setPreDeployAdvisory).toHaveBeenCalledTimes(3);
expect(setPreDeployAdvisory.mock.calls[2][0]).toMatchObject({ stackName: 'web' });
});
});
describe('useStackActions.bypassPolicyAndRetry', () => {
const payload = {
error: 'blocked',
@@ -11,6 +11,7 @@ import type { RunWithLogParams } from '@/context/DeployFeedbackContext';
import type { StackAction, RecoverableAction, FailureClassification } from '../EditorView';
import type { NotificationItem } from '../../dashboard/types';
import type { PolicyBlockPayload, PolicyBlockableAction } from '../../stack/PolicyBlockDialog';
import type { PreDeployScanImage } from '@/types/security';
interface RunResult {
ok: boolean;
@@ -118,6 +119,38 @@ interface UseStackActionsOptions {
const isRecord = (value: unknown): value is Record<string, unknown> =>
typeof value === 'object' && value !== null;
const PRE_DEPLOY_SUMMARY_TIMEOUT_MS = 5000;
/**
* Fetch the pre-deploy scan advisory for a manual deploy. Returns the image
* list when the advisory is enabled and the backend answers in time, or null to
* mean "no advisory, deploy normally" for every other case (setting off,
* timeout, an older node without the route, or any error). Failing open is
* deliberate: the advisory is visibility, it must never block a deploy. Bound to
* the captured node so it targets the same node the deploy will hit.
*/
export async function fetchPreDeployAdvisory(
stackName: string,
opNodeId: number | null,
): Promise<PreDeployScanImage[] | null> {
const controller = new AbortController();
const timer = setTimeout(() => controller.abort(), PRE_DEPLOY_SUMMARY_TIMEOUT_MS);
try {
const res = await apiFetch(
`/security/stacks/${encodeURIComponent(stackName)}/pre-deploy-summary`,
{ nodeId: opNodeId, signal: controller.signal },
);
if (!res.ok) return null;
const data: unknown = await res.json();
if (!isRecord(data) || data.enabled !== true || !Array.isArray(data.images)) return null;
return data.images as PreDeployScanImage[];
} catch {
return null;
} finally {
clearTimeout(timer);
}
}
const parseStackOpInProgress = (rawBody: string): StackOpInProgressInfo | null => {
try {
const parsed: unknown = JSON.parse(rawBody);
@@ -202,6 +235,9 @@ export function useStackActions(options: UseStackActionsOptions) {
const pendingStackLoadRef = useRef<string | null>(null);
const pendingLogsRef = useRef<{ stackName: string; containerName: string } | null>(null);
const checkUpdatesIntervalRef = useRef<ReturnType<typeof setInterval> | null>(null);
// True from a deploy click through the async pre-deploy advisory phase until
// the deploy starts or is cancelled, so a double-click cannot start two deploys.
const deployPendingRef = useRef(false);
// Aborts the most recent loadFile sequence (compose GET, envs GET, env content
// GET, containers GET, backup GET). A node switch, an unmount, or a second
// loadFile call before the first finishes all cancel the in-flight fetches so
@@ -723,22 +759,63 @@ export function useStackActions(options: UseStackActionsOptions) {
const deployStack = async (e?: React.MouseEvent) => {
e?.preventDefault();
e?.stopPropagation();
if (!stackListState.selectedFile || stackListState.isStackBusy(stackListState.selectedFile))
// deployPendingRef blocks a second deploy from the moment of the click
// through the async advisory phase, before setStackAction marks the stack
// busy. Without it, a double-click during the advisory fetch window could
// launch two deploys. Cleared on cancel and in the deploy's finally.
if (
!stackListState.selectedFile ||
stackListState.isStackBusy(stackListState.selectedFile) ||
deployPendingRef.current
)
return;
const stackFile = stackListState.selectedFile;
const stackName = stackFile.replace(/\.(yml|yaml)$/, '');
stackListState.setStackAction(stackFile, 'deploy');
// Snapshot the node once so the request stays bound to it even if the active
// node changes while the operation is in flight.
// Snapshot the node once so the advisory fetch and the deploy stay bound to
// it even if the active node changes while the advisory dialog is open.
const opNodeId = activeNode?.id ?? null;
try {
await runWithLog({ stackName, action: 'deploy', nodeId: opNodeId }, (started, ds) =>
runDeploy(stackName, stackFile, false, started, ds, opNodeId),
);
} finally {
stackListState.clearStackAction(stackFile);
stackListState.refreshStacks(true);
deployPendingRef.current = true;
// The actual deploy, pulled out so the optional pre-deploy advisory can gate
// it without duplicating the action lifecycle. The stack action is set here
// (not before the advisory) so cancelling the advisory leaves no stuck state.
const runDeployFlow = async () => {
stackListState.setStackAction(stackFile, 'deploy');
try {
await runWithLog({ stackName, action: 'deploy', nodeId: opNodeId }, (started, ds) =>
runDeploy(stackName, stackFile, false, started, ds, opNodeId),
);
} finally {
stackListState.clearStackAction(stackFile);
stackListState.refreshStacks(true);
deployPendingRef.current = false;
}
};
// Advisory runs before the deploy log opens (fails open: a null result means
// setting off / timeout / older node / error, so the deploy proceeds).
const advisoryImages = await fetchPreDeployAdvisory(stackName, opNodeId);
if (advisoryImages && advisoryImages.length > 0) {
let settled = false;
overlayState.setPreDeployAdvisory({
stackName,
images: advisoryImages,
proceed: () => {
if (settled) return;
settled = true;
overlayState.setPreDeployAdvisory(null);
void runDeployFlow();
},
cancel: () => {
if (settled) return;
settled = true;
overlayState.setPreDeployAdvisory(null);
deployPendingRef.current = false;
},
});
return;
}
await runDeployFlow();
};
const handleSaveAndDeploy = async (e: React.MouseEvent) => {