mirror of
https://github.com/Studio-Saelix/sencho.git
synced 2026-08-13 04:06:59 +00:00
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:
@@ -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) => {
|
||||
|
||||
@@ -46,7 +46,7 @@ interface TrivyManagerProps {
|
||||
*/
|
||||
export function TrivyManager({ status, updateCheck, refresh, refreshUpdateCheck }: TrivyManagerProps) {
|
||||
const { isAdmin } = useAuth();
|
||||
const [trivyBusy, setTrivyBusy] = useState<null | 'install' | 'update' | 'uninstall' | 'auto-update'>(null);
|
||||
const [trivyBusy, setTrivyBusy] = useState<null | 'install' | 'update' | 'uninstall' | 'auto-update' | 'advisory'>(null);
|
||||
const [uninstallConfirm, setUninstallConfirm] = useState(false);
|
||||
|
||||
const runTrivyOp = async (
|
||||
@@ -99,6 +99,25 @@ export function TrivyManager({ status, updateCheck, refresh, refreshUpdateCheck
|
||||
}
|
||||
};
|
||||
|
||||
const handleAdvisoryToggle = async (enabled: boolean) => {
|
||||
setTrivyBusy('advisory');
|
||||
try {
|
||||
const res = await apiFetch('/security/pre-deploy-scan-advisory', {
|
||||
method: 'PUT',
|
||||
body: JSON.stringify({ enabled }),
|
||||
});
|
||||
if (!res.ok) {
|
||||
const err = await res.json().catch(() => ({}));
|
||||
throw new Error(err?.error || 'Failed to update setting');
|
||||
}
|
||||
await refresh();
|
||||
} catch (err) {
|
||||
toast.error((err as Error)?.message || 'Failed to update setting');
|
||||
} finally {
|
||||
setTrivyBusy(null);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<>
|
||||
<div className="rounded-lg border border-card-border border-t-card-border-top bg-card shadow-card-bevel p-4 space-y-3">
|
||||
@@ -172,6 +191,22 @@ export function TrivyManager({ status, updateCheck, refresh, refreshUpdateCheck
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{(status.available || status.preDeployScanAdvisory) && isAdmin && (
|
||||
<div className="flex items-center justify-between rounded-lg border border-glass-border px-3 py-2.5">
|
||||
<div>
|
||||
<Label className="text-sm">Pre-deploy scan advisory</Label>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
Before a manual deploy, show each image's latest scan results so you can review them first. Advisory only; it never blocks the deploy.
|
||||
</p>
|
||||
</div>
|
||||
<TogglePill
|
||||
checked={status.preDeployScanAdvisory}
|
||||
onChange={handleAdvisoryToggle}
|
||||
disabled={trivyBusy !== null}
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<ConfirmModal
|
||||
|
||||
@@ -34,7 +34,7 @@ function setup({ isPaid }: { isPaid: boolean }) {
|
||||
vi.mocked(AuthContext.useAuth).mockReturnValue({ isAdmin: true } as unknown as ReturnType<typeof AuthContext.useAuth>);
|
||||
vi.mocked(NodeContext.useNodes).mockReturnValue({ activeNode: { type: 'local', id: 1, name: 'local' } } as unknown as ReturnType<typeof NodeContext.useNodes>);
|
||||
vi.mocked(TrivyStatus.useTrivyStatus).mockReturnValue({
|
||||
status: { available: true, version: '1', source: 'managed', autoUpdate: false, honorSuppressionsOnDeploy: false, busy: false },
|
||||
status: { available: true, version: '1', source: 'managed', autoUpdate: false, honorSuppressionsOnDeploy: false, preDeployScanAdvisory: false, busy: false },
|
||||
updateCheck: null,
|
||||
refresh: vi.fn().mockResolvedValue(undefined),
|
||||
refreshUpdateCheck: vi.fn().mockResolvedValue(undefined),
|
||||
|
||||
@@ -0,0 +1,78 @@
|
||||
import {
|
||||
Modal,
|
||||
ModalHeader,
|
||||
ModalBody,
|
||||
ModalFooter,
|
||||
} from '@/components/ui/modal';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { SeverityChip } from '@/components/VulnerabilityScanSheet';
|
||||
import { formatTimeAgo } from '@/lib/relativeTime';
|
||||
import type { PreDeployScanImage } from '@/types/security';
|
||||
|
||||
interface PreDeployScanDialogProps {
|
||||
open: boolean;
|
||||
stackName: string;
|
||||
images: PreDeployScanImage[];
|
||||
onCancel: () => void;
|
||||
onDeploy: () => void;
|
||||
}
|
||||
|
||||
/**
|
||||
* Advisory pre-deploy review. Shows the latest cached scan for each image in a
|
||||
* manual deploy so the operator can review the security posture before
|
||||
* proceeding. Unlike PolicyBlockDialog this never blocks: anyone can deploy or
|
||||
* cancel, and there is no override gate (blocking is the paid deploy-block
|
||||
* policy). Opened opt-in via the pre-deploy scan advisory setting.
|
||||
*/
|
||||
export function PreDeployScanDialog({ open, stackName, images, onCancel, onDeploy }: PreDeployScanDialogProps) {
|
||||
return (
|
||||
<Modal open={open} onOpenChange={(next) => { if (!next) onCancel(); }} size="xl">
|
||||
<ModalHeader
|
||||
kicker={`${stackName.toUpperCase()} · PRE-DEPLOY · SCAN REVIEW`}
|
||||
title="Review scan results before deploying"
|
||||
description="The latest vulnerability scan for each image in this deploy. Advisory only; it does not block the deploy."
|
||||
/>
|
||||
<ModalBody>
|
||||
<div className="border border-glass-border bg-card/60 shadow-card-bevel divide-y divide-glass-border">
|
||||
{images.length === 0 ? (
|
||||
<div className="px-4 py-3 text-sm text-muted-foreground">No images found for this stack.</div>
|
||||
) : (
|
||||
images.map((img) => (
|
||||
<div key={img.imageRef} className="px-4 py-3 flex items-center justify-between gap-4">
|
||||
<div className="min-w-0">
|
||||
<div className="font-mono text-sm truncate">{img.imageRef}</div>
|
||||
<div className="font-mono text-[10px] uppercase tracking-[0.18em] text-stat-subtitle tabular-nums">
|
||||
{img.scan
|
||||
? `${img.scan.criticalCount} critical · ${img.scan.highCount} high · ${img.scan.mediumCount} medium · ${img.scan.lowCount} low · scanned ${formatTimeAgo(img.scan.scannedAt)}`
|
||||
: 'not scanned'}
|
||||
</div>
|
||||
</div>
|
||||
{img.scan?.highestSeverity ? (
|
||||
<SeverityChip severity={img.scan.highestSeverity} />
|
||||
) : null}
|
||||
</div>
|
||||
))
|
||||
)}
|
||||
</div>
|
||||
</ModalBody>
|
||||
<ModalFooter
|
||||
secondary={
|
||||
<Button variant="outline" size="sm" onClick={onCancel}>
|
||||
Cancel
|
||||
</Button>
|
||||
}
|
||||
primary={
|
||||
<Button
|
||||
size="sm"
|
||||
onClick={(e) => {
|
||||
e.preventDefault();
|
||||
onDeploy();
|
||||
}}
|
||||
>
|
||||
Deploy
|
||||
</Button>
|
||||
}
|
||||
/>
|
||||
</Modal>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,49 @@
|
||||
import { describe, it, expect, vi } from 'vitest';
|
||||
import { render, screen, fireEvent } from '@testing-library/react';
|
||||
import { PreDeployScanDialog } from '../PreDeployScanDialog';
|
||||
import type { PreDeployScanImage } from '@/types/security';
|
||||
|
||||
const images: PreDeployScanImage[] = [
|
||||
{
|
||||
imageRef: 'nginx:1.14',
|
||||
scan: {
|
||||
criticalCount: 31,
|
||||
highCount: 82,
|
||||
mediumCount: 1,
|
||||
lowCount: 4,
|
||||
highestSeverity: 'CRITICAL',
|
||||
scannedAt: Date.now() - 3_600_000,
|
||||
},
|
||||
},
|
||||
{ imageRef: 'redis:7', scan: null },
|
||||
];
|
||||
|
||||
describe('PreDeployScanDialog', () => {
|
||||
it('renders each image with its scan counts or a not-scanned note', () => {
|
||||
render(
|
||||
<PreDeployScanDialog open stackName="web" images={images} onCancel={vi.fn()} onDeploy={vi.fn()} />,
|
||||
);
|
||||
expect(screen.getByText('nginx:1.14')).toBeInTheDocument();
|
||||
expect(screen.getByText(/31 critical/)).toBeInTheDocument();
|
||||
expect(screen.getByText('redis:7')).toBeInTheDocument();
|
||||
expect(screen.getByText('not scanned')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('calls onDeploy when Deploy is clicked', () => {
|
||||
const onDeploy = vi.fn();
|
||||
render(
|
||||
<PreDeployScanDialog open stackName="web" images={images} onCancel={vi.fn()} onDeploy={onDeploy} />,
|
||||
);
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Deploy' }));
|
||||
expect(onDeploy).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it('calls onCancel when Cancel is clicked', () => {
|
||||
const onCancel = vi.fn();
|
||||
render(
|
||||
<PreDeployScanDialog open stackName="web" images={images} onCancel={onCancel} onDeploy={vi.fn()} />,
|
||||
);
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Cancel' }));
|
||||
expect(onCancel).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
});
|
||||
Reference in New Issue
Block a user