Skip to content

Modern Docker Management, Designed for Everyone

20.4 KB
Raw Blame
<script lang="ts">
	import { onMount, type Snippet } from 'svelte';
	import { toast } from 'svelte-sonner';

	import { ArcaneButton } from '#lib/components/arcane-button/index.js';
	import ArcaneTable from '#lib/components/arcane-table/arcane-table.svelte';
	import type { BulkAction, ColumnSpec } from '#lib/components/arcane-table/arcane-table.types.svelte.js';
	import UniversalMobileCard from '#lib/components/arcane-table/cards/universal-mobile-card.svelte';
	import { environmentColumns } from '#lib/components/arcane-table/environment-column.js';
	import RowActionsMenu from '#lib/components/arcane-table/row-actions-menu.svelte';
	import { openConfirmDialog } from '#lib/components/confirm-dialog/index.js';
	// Patching happens on the Patches tab, per image; CVE rows only inspect and ignore.
	import * as DropdownMenu from '#lib/components/ui/dropdown-menu/index.js';
	import { Label } from '#lib/components/ui/label/index.js';
	import { Switch } from '#lib/components/ui/switch/index.js';
	import CveCell from '#lib/components/vulnerability/cve-cell.svelte';
	import FixedCell from '#lib/components/vulnerability/fixed-cell.svelte';
	import MonoCell from '#lib/components/vulnerability/mono-cell.svelte';
	import SeverityBadge from '#lib/components/vulnerability/severity-badge.svelte';
	import { TABLE_PAGE_SIZE_ALL } from '#lib/constants/table-pagination.js';
	import {
		ShieldAlertIcon,
		CodeIcon,
		CheckIcon,
		ImagesIcon,
		EyeOffIcon,
		EyeOnIcon,
		DownloadIcon,
		LayersIcon
	} from '#lib/icons/index.js';
	import { m } from '#lib/paraglide/messages.js';
	import { vulnerabilityService } from '#lib/services/vulnerability-service.js';
	import { environmentStore } from '#lib/stores/environment.store.svelte.js';
	import type { Paginated, SearchPaginationSortRequest } from '#lib/types/shared.js';
	import { handleApiResultWithCallbacks } from '#lib/utils/api.js';
	import { hasPermission } from '#lib/utils/auth.js';
	import { downloadBlob } from '#lib/utils/browser-download.js';
	import { bulkConfirmAndRun, confirmAndRun } from '#lib/utils/bulk-actions.js';
	import {
		ENVIRONMENT_FILTER,
		environmentFilterIds,
		environmentHref,
		environmentName,
		fetchAcrossEnvironments,
		readAcrossEnvironments,
		rowKey,
		settleAcrossEnvironments
	} from '#lib/utils/environments.js';
	import { tryCatch } from '#lib/utils/try-catch.js';
	import {
		getSeverityBadgeVariant,
		getSeverityIconVariant,
		getSeverityLabel,
		mapVulnerabilityPage,
		mapVulnerabilityRequest,
		resolveSeverityFilter,
		toBulkVulnerabilityFilters,
		vulnerabilityEnvironments,
		withVulnerabilityToggles,
		type VulnerabilityRow
	} from '#lib/utils/vulnerability.js';

	let {
		vulnerabilities = $bindable(),
		requestOptions = $bindable(),
		selectedIds = $bindable([]),
		showIgnored = false,
		onToggleIgnored,
		fixAvailable = false,
		onToggleFixAvailable,
		emptyState
	}: {
		vulnerabilities: Paginated<VulnerabilityRow>;
		requestOptions: SearchPaginationSortRequest;
		selectedIds?: string[];
		showIgnored?: boolean;
		onToggleIgnored?: (checked: boolean) => void | Promise<void>;
		fixAvailable?: boolean;
		onToggleFixAvailable?: (checked: boolean) => void | Promise<void>;
		emptyState?: Snippet;
	} = $props();

	let imageNameFilterOptions = $state<string[]>([]);
	let bulkInFlight = $state(false);
	let mounted = true;

	const scope = $derived(environmentStore.shownKey);
	const vulnerabilityManagementEnabled = $derived(vulnerabilityEnvironments().length > 0);
	const manageEnvironments = $derived(
		vulnerabilityEnvironments().filter((env) => hasPermission('vulnerabilities:manage', env.id))
	);
	const canManageVuln = $derived(manageEnvironments.length > 0);

	const matchingCount = $derived(vulnerabilities.pagination?.totalItems ?? vulnerabilities.data.length);

	function handlePageSizeChangeRequest(limit: number, apply: () => void) {
		if (limit !== TABLE_PAGE_SIZE_ALL) {
			apply();
			return;
		}
		const requestedScope = scope;
		openConfirmDialog({
			title: m.vuln_load_all_title(),
			message: m.vuln_load_all_message({ count: matchingCount }),
			confirm: {
				label: m.vuln_load_all_confirm(),
				action: () => {
					if (!mounted || requestedScope !== scope || !vulnerabilityManagementEnabled) return;
					apply();
				}
			}
		});
	}

	async function reloadFromFirstPage(requestedScope: string) {
		if (requestedScope !== scope) return;
		// The rows are already changed on the server; clear before refreshing so a failed reload cannot re-submit them.
		selectedIds = [];
		requestOptions = { ...requestOptions, pagination: { ...(requestOptions.pagination ?? { limit: 20 }), page: 1 } };
		await handleApiResultWithCallbacks({
			result: await tryCatch(refreshVulnerabilityTable(requestOptions)),
			message: m.common_refresh_failed({ resource: m.vuln_title() })
		});
	}

	// Confirmations name one environment, and only count several.
	function confirmEnvironment(environmentIds: string[]): string {
		const unique = [...new Set(environmentIds)];
		if (unique.length === 1) return environmentName(unique[0]!);
		return m.all_environments_count({ count: unique.length });
	}

	function handleBulkSelected(ids: string[]) {
		if (!canManageVuln) return;
		const requestedScope = scope;
		const restore = showIgnored;
		const rows = vulnerabilities.data.filter((row) => ids.includes(rowKey(row)));
		const count = ids.length;
		const environment = confirmEnvironment(rows.map((row) => row.environmentId));
		bulkConfirmAndRun({
			ids,
			title: restore ? m.vuln_bulk_restore_confirm_title({ count }) : m.vuln_bulk_ignore_confirm_title({ count }),
			message: restore
				? m.vuln_bulk_restore_selected_confirm_message({ count, environment })
				: m.vuln_bulk_ignore_selected_confirm_message({ count, environment }),
			confirmLabel: restore ? m.vuln_bulk_restore() : m.common_ignore(),
			run: async (id, environmentId) => {
				const row = rows.find((candidate) => candidate.id === id && candidate.environmentId === environmentId);
				if (!row) return;
				if (restore) {
					if (row.ignoreId) await vulnerabilityService.unignoreVulnerability(row.ignoreId, row.environmentId);
					return;
				}
				await vulnerabilityService.ignoreVulnerability(
					{
						imageId: row.imageId || '',
						vulnerabilityId: row.vulnerabilityId || '',
						pkgName: row.pkgName || '',
						installedVersion: row.installedVersion || ''
					},
					row.environmentId
				);
			},
			messages: {
				success: (n) => (restore ? m.vuln_bulk_restore_success({ count: n }) : m.vuln_bulk_ignore_success({ count: n })),
				partial: (success, total, failed) =>
					restore
						? m.vuln_bulk_restore_partial({ success, total, failed })
						: m.vuln_bulk_ignore_partial({ success, total, failed }),
				failure: () => (restore ? m.vuln_bulk_restore_failed() : m.vuln_bulk_ignore_failed())
			},
			setLoading: (loading) => (bulkInFlight = loading),
			onComplete: async (result) => {
				if (result.success > 0) await reloadFromFirstPage(requestedScope);
			},
			clearSelection: () => (selectedIds = [])
		});
	}

	function handleBulkAllMatching() {
		if (!canManageVuln) return;
		const requestedScope = scope;
		const restore = showIgnored;
		const filters = toBulkVulnerabilityFilters(withVulnerabilityToggles(requestOptions, { showIgnored, fixAvailable }));
		const count = matchingCount;
		const picked = environmentFilterIds(requestOptions.filters?.[ENVIRONMENT_FILTER]);
		const environments = manageEnvironments.filter((env) => picked.length === 0 || picked.includes(env.id));
		const environment = confirmEnvironment(environments.map((env) => env.id));
		confirmAndRun({
			title: restore ? m.vuln_bulk_restore_confirm_title({ count }) : m.vuln_bulk_ignore_confirm_title({ count }),
			message: restore
				? m.vuln_bulk_restore_all_matching_confirm_message({ count, environment })
				: m.vuln_bulk_ignore_all_matching_confirm_message({ count, environment }),
			confirmLabel: restore ? m.vuln_bulk_restore() : m.common_ignore(),
			setLoading: (loading) => (bulkInFlight = loading),
			run: async () => {
				const results = await settleAcrossEnvironments(environments, (id) =>
					restore
						? vulnerabilityService.bulkUnignoreVulnerabilities(filters, id)
						: vulnerabilityService.bulkIgnoreVulnerabilities(filters, id)
				);
				return { affectedCount: results.reduce((total, { value }) => total + value.affectedCount, 0) };
			},
			failureMessage: restore ? m.vuln_bulk_restore_failed() : m.vuln_bulk_ignore_failed(),
			onSuccess: async ({ affectedCount }) => {
				toast.success(
					restore ? m.vuln_bulk_restore_success({ count: affectedCount }) : m.vuln_bulk_ignore_success({ count: affectedCount })
				);
				await reloadFromFirstPage(requestedScope);
			}
		});
	}

	const bulkActions = $derived.by<BulkAction[]>(() => {
		if (!canManageVuln) return [];
		const restore = showIgnored;
		return [
			{
				id: 'bulk-selected',
				label: restore
					? m.vuln_bulk_restore_selected({ count: selectedIds.length })
					: m.vuln_bulk_ignore_selected({ count: selectedIds.length }),
				action: 'base',
				icon: restore ? EyeOnIcon : EyeOffIcon,
				onClick: handleBulkSelected,
				loading: bulkInFlight,
				disabled: bulkInFlight
			},
			{
				id: 'bulk-all-matching',
				label: restore
					? m.vuln_bulk_restore_all_matching({ count: matchingCount })
					: m.vuln_bulk_ignore_all_matching({ count: matchingCount }),
				action: 'base',
				icon: LayersIcon,
				onClick: handleBulkAllMatching,
				loading: bulkInFlight,
				disabled: bulkInFlight || matchingCount === 0
			}
		];
	});

	async function handleUnignoreVulnerability(item: VulnerabilityRow) {
		if (!canManageVuln) return;
		const requestedScope = scope;
		const ignoreId = item.ignoreId;
		if (!ignoreId) return;
		await handleApiResultWithCallbacks({
			result: await tryCatch(vulnerabilityService.unignoreVulnerability(ignoreId, item.environmentId)),
			message: m.vuln_unignore_failed(),
			onSuccess: async () => {
				toast.success(m.vuln_unignore_success());
				if (requestedScope !== scope) return;
				await handleApiResultWithCallbacks({
					result: await tryCatch(refreshVulnerabilityTable(requestOptions)),
					message: m.common_refresh_failed({ resource: m.vuln_title() })
				});
			}
		});
	}

	function deriveImageOptionsFromRows(rows: VulnerabilityRow[]): string[] {
		return [...new Set(rows.map((row) => row.imageName || row.imageId).filter(Boolean) as string[])].sort();
	}

	async function refreshImageNameFilterOptions(options?: SearchPaginationSortRequest): Promise<string[]> {
		if (!vulnerabilityManagementEnabled) return [];
		const requestedScope = scope;
		const severity = resolveSeverityFilter(options);
		const request: SearchPaginationSortRequest = {
			filters: severity ? { severity } : undefined
		};

		const operationResult = await tryCatch(
			(async () => {
				const environments = vulnerabilityEnvironments();
				const optionsResponse =
					environments.length === 0
						? []
						: (
								await readAcrossEnvironments(environments, (scope, config) =>
									vulnerabilityService.getAllVulnerabilityImageOptionsForEnvironment(scope, request, config)
								)
							).value;
				if (vulnerabilityManagementEnabled && requestedScope === scope) imageNameFilterOptions = optionsResponse;
				return optionsResponse;
			})()
		);
		await handleApiResultWithCallbacks({
			result: operationResult,
			message: m.common_refresh_failed({ resource: m.vuln_image_filter_options() })
		});
		return operationResult.error !== null ? imageNameFilterOptions : operationResult.data;
	}

	// Only the latest request is applied, so a slow response for an earlier filter cannot replace newer rows.
	let latestTableRequest = 0;
	async function refreshVulnerabilityTable(options: SearchPaginationSortRequest) {
		if (!vulnerabilityManagementEnabled) return vulnerabilities;
		const requestedScope = scope;
		const tableRequest = ++latestTableRequest;
		const request = mapVulnerabilityRequest(withVulnerabilityToggles(options, { showIgnored, fixAvailable }));

		const [response, optionsResponse] = await Promise.all([
			fetchAcrossEnvironments(vulnerabilityEnvironments(), request, (id, request, config) =>
				vulnerabilityService.getAllVulnerabilitiesForEnvironment(id, request, config)
			),
			refreshImageNameFilterOptions(request)
		]);
		if (!vulnerabilityManagementEnabled || requestedScope !== scope || tableRequest !== latestTableRequest)
			return vulnerabilities;
		const mapped = mapVulnerabilityPage(response, request);
		vulnerabilities = mapped;
		// Row ids are page-position keys, so replacing the rows invalidates the selection.
		selectedIds = [];

		if (optionsResponse.length === 0) {
			imageNameFilterOptions = deriveImageOptionsFromRows(mapped.data ?? []);
		}

		return mapped;
	}

	async function handleExportCsv() {
		if (!vulnerabilityManagementEnabled) return;
		const requestedScope = scope;
		const request = mapVulnerabilityRequest(
			withVulnerabilityToggles({ ...requestOptions, pagination: undefined }, { showIgnored, fixAvailable })
		);
		// The table's environment filter is applied here; the export API never receives it.
		const picked = environmentFilterIds(requestOptions.filters?.[ENVIRONMENT_FILTER]);
		const environments = vulnerabilityEnvironments().filter((env) => picked.length === 0 || picked.includes(env.id));
		const operationResult = await tryCatch(
			settleAcrossEnvironments(environments, (id) => vulnerabilityService.exportVulnerabilitiesForEnvironment(id, request))
		);
		if (!mounted || requestedScope !== scope) return;
		if (operationResult.error !== null) {
			console.error('Failed to export vulnerabilities:', operationResult.error);
			toast.error(m.vuln_export_failed());
			return;
		}
		for (const { value } of operationResult.data) downloadBlob(value.blob, value.filename);
	}

	async function handleIgnoreVulnerability(item: VulnerabilityRow) {
		if (!canManageVuln) return;
		const requestedScope = scope;
		const payload = {
			imageId: item.imageId || '',
			vulnerabilityId: item.vulnerabilityId || '',
			pkgName: item.pkgName || '',
			installedVersion: item.installedVersion || ''
		};
		await handleApiResultWithCallbacks({
			result: await tryCatch(vulnerabilityService.ignoreVulnerability(payload, item.environmentId)),
			message: m.vuln_ignore_failed(),
			onSuccess: async () => {
				toast.success(m.vuln_ignore_success({ cve: item.vulnerabilityId }));
				if (requestedScope !== scope) return;
				await handleApiResultWithCallbacks({
					result: await tryCatch(refreshVulnerabilityTable(requestOptions)),
					message: m.common_refresh_failed({ resource: m.vuln_title() })
				});
			}
		});
	}

	const columns = $derived([
		...environmentColumns<VulnerabilityRow>(),
		{ accessorKey: 'vulnerabilityId', title: 'CVE', cell: CveCol },
		{ accessorKey: 'pkgName', title: m.vuln_package(), cell: PackageCell },
		{ id: 'vulnSeverity', accessorKey: 'severity', title: m.events_col_severity(), sortable: true, cell: SeverityCell },
		{ accessorKey: 'installedVersion', title: m.vuln_installed_version(), cell: InstalledCell },
		{ accessorKey: 'fixedVersion', title: m.vuln_fixed_version(), cell: FixedCol },
		{ accessorKey: 'imageName', title: m.common_image(), sortable: true, cell: ImageCell }
	] satisfies ColumnSpec<VulnerabilityRow>[]);

	onMount(() => {
		void refreshImageNameFilterOptions(requestOptions);
		return () => {
			mounted = false;
		};
	});

	const mobileFields = [
		{ id: 'vulnerabilityId', label: 'CVE', defaultVisible: true },
		{ id: 'pkgName', label: m.vuln_package(), defaultVisible: true },
		{ id: 'vulnSeverity', label: m.events_col_severity(), defaultVisible: true },
		{ id: 'imageName', label: m.common_image(), defaultVisible: true },
		{ id: 'installedVersion', label: m.vuln_installed_version(), defaultVisible: false },
		{ id: 'fixedVersion', label: m.vuln_fixed_version(), defaultVisible: false }
	];
</script>

{#snippet CveCol({ item }: { item: VulnerabilityRow })}
	<div class="flex items-center gap-2">
		<CveCell vulnerabilityId={item.vulnerabilityId} />
		{#if item.ignored}
			<span class="rounded bg-muted px-1.5 py-0.5 text-xs font-medium text-muted-foreground">{m.vuln_ignored_badge()}</span>
		{/if}
	</div>
{/snippet}

{#snippet PackageCell({ item }: { item: VulnerabilityRow })}
	<MonoCell value={item.pkgName} />
{/snippet}

{#snippet SeverityCell({ item }: { item: VulnerabilityRow })}
	<SeverityBadge severity={item.severity} />
{/snippet}

{#snippet InstalledCell({ item }: { item: VulnerabilityRow })}
	<MonoCell value={item.installedVersion} />
{/snippet}

{#snippet FixedCol({ item }: { item: VulnerabilityRow })}
	<FixedCell fixedVersion={item.fixedVersion} />
{/snippet}

{#snippet ImageCell({ item }: { item: VulnerabilityRow })}
	<a class="truncate text-sm font-medium hover:underline" href={environmentHref(`/images/${item.imageId}`, item.environmentId)}>
		{item.imageName || item.imageId}
	</a>
{/snippet}

{#snippet VulnerabilityMobileCard({
	item,
	mobileFieldVisibility
}: {
	item: VulnerabilityRow;
	mobileFieldVisibility: Record<string, boolean>;
})}
	<UniversalMobileCard
		{item}
		icon={(item) => ({
			component: ShieldAlertIcon,
			variant: getSeverityIconVariant(item.severity)
		})}
		title={(item) => item.vulnerabilityId}
		subtitle={(item) => ((mobileFieldVisibility['pkgName'] ?? true) ? item.pkgName : null)}
		badges={[
			(item) =>
				(mobileFieldVisibility['vulnSeverity'] ?? true)
					? { variant: getSeverityBadgeVariant(item.severity), text: getSeverityLabel(item.severity) }
					: null
		]}
		fields={[
			{
				label: m.common_image(),
				getValue: (item) => item.imageName || item.imageId,
				icon: ImagesIcon,
				iconVariant: 'gray',
				show: mobileFieldVisibility['imageName'] ?? true
			},
			{
				label: m.vuln_installed_version(),
				getValue: (item) => item.installedVersion,
				type: 'mono',
				icon: CodeIcon,
				iconVariant: 'blue',
				show: mobileFieldVisibility['installedVersion'] ?? true
			},
			{
				label: m.vuln_fixed_version(),
				getValue: (item) => item.fixedVersion || m.vuln_no_fix(),
				type: 'mono',
				icon: CheckIcon,
				iconVariant: item.fixedVersion ? 'emerald' : 'gray',
				show: mobileFieldVisibility['fixedVersion'] ?? true
			}
		]}
	/>
{/snippet}

{#snippet rowActions({ item }: { item: VulnerabilityRow })}
	<RowActionsMenu>
		{@const canManageRow = hasPermission('vulnerabilities:manage', item.environmentId)}
		{#if item.ignored}
			<DropdownMenu.Item onclick={() => handleUnignoreVulnerability(item)} disabled={!canManageRow}>
				<EyeOnIcon class="size-4" />
				{m.vuln_unignore()}
			</DropdownMenu.Item>
		{:else}
			<DropdownMenu.Item onclick={() => handleIgnoreVulnerability(item)} disabled={!canManageRow}>
				<EyeOffIcon class="size-4" />
				{m.vuln_ignore()}
			</DropdownMenu.Item>
		{/if}
	</RowActionsMenu>
{/snippet}

{#snippet VulnerabilityToolbarActions()}
	<div class="flex w-full flex-wrap items-center justify-end gap-2 md:w-auto">
		<div
			class="flex min-h-9 w-full items-center gap-2 rounded-md border border-border/60 bg-muted/30 px-2.5 py-1.5 md:w-auto md:border-0 md:bg-transparent md:px-1 md:py-0"
		>
			<Switch
				id="security-show-ignored"
				checked={showIgnored}
				onCheckedChange={async (checked) => {
					// The view mode decides whether selected rows are ignored or restored, so drop the selection before the rows change.
					selectedIds = [];
					await onToggleIgnored?.(checked === true);
					await refreshVulnerabilityTable(requestOptions);
				}}
			/>
			<Label for="security-show-ignored" variant="muted" class="mb-0 min-w-0">
				{m.vuln_show_ignored()}
			</Label>
		</div>
		<div
			class="flex min-h-9 w-full items-center gap-2 rounded-md border border-border/60 bg-muted/30 px-2.5 py-1.5 md:w-auto md:border-0 md:bg-transparent md:px-1 md:py-0"
		>
			<Switch
				id="security-fix-available"
				checked={fixAvailable}
				onCheckedChange={async (checked) => {
					selectedIds = [];
					await onToggleFixAvailable?.(checked === true);
					await refreshVulnerabilityTable(requestOptions);
				}}
			/>
			<Label for="security-fix-available" variant="muted" class="mb-0 min-w-0">
				{m.security_fixable()}
			</Label>
		</div>
		<ArcaneButton
			action="base"
			size="sm"
			icon={DownloadIcon}
			customLabel={m.vuln_export_csv()}
			loadingLabel={m.vuln_exporting()}
			onClickPromise={handleExportCsv}
			class="h-9 shrink-0"
		/>
	</div>
{/snippet}

<ArcaneTable
	{emptyState}
	items={vulnerabilities}
	bind:requestOptions
	onRefresh={refreshVulnerabilityTable}
	onPageSizeChangeRequest={handlePageSizeChangeRequest}
	{columns}
	mobileCard={VulnerabilityMobileCard}
	{mobileFields}
	persistKey="arcane-security-vuln-table"
	restoreAllPageSize={false}
	selectionDisabled={!canManageVuln}
	bind:selectedIds
	{bulkActions}
	{imageNameFilterOptions}
	customToolbarActions={VulnerabilityToolbarActions}
	rowActions={canManageVuln ? rowActions : undefined}
/>