@skyhook-io/radar-app 1.20.3 → 1.21.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (152) hide show
  1. package/package.json +10 -9
  2. package/src/App.tsx +54 -10
  3. package/src/api/client.audit-gating.test.tsx +105 -5
  4. package/src/api/client.auditBadgesSync.test.tsx +118 -0
  5. package/src/api/client.capabilitiesPoll.test.ts +61 -0
  6. package/src/api/client.ts +129 -5
  7. package/src/api/namespaceScopeRetry.test.ts +14 -0
  8. package/src/api/radarFeatures.ts +7 -0
  9. package/src/api/substrateHealth.ts +134 -0
  10. package/src/api/velero.test.ts +60 -0
  11. package/src/api/velero.ts +201 -0
  12. package/src/api/vulnerabilities.ts +255 -0
  13. package/src/components/NamespaceSwitcher.tsx +3 -1
  14. package/src/components/audit/AuditView.tsx +4 -0
  15. package/src/components/audit/ChecksViewTabs.test.tsx +33 -5
  16. package/src/components/audit/ChecksViewTabs.tsx +11 -1
  17. package/src/components/audit/UpgradeReadinessView.test.ts +35 -1
  18. package/src/components/audit/UpgradeReadinessView.tsx +60 -2
  19. package/src/components/audit/VulnerabilitiesView.tsx +907 -0
  20. package/src/components/cnpg/CNPGClusterTabs.tsx +3 -1
  21. package/src/components/cnpg/CNPGDrawerTrail.tsx +5 -26
  22. package/src/components/cnpg/CNPGInvestigationAction.test.tsx +27 -6
  23. package/src/components/cnpg/CNPGView.tsx +43 -117
  24. package/src/components/cnpg/CNPGWorkspace.compatibility.test.tsx +30 -0
  25. package/src/components/cnpg/host.tsx +2 -2
  26. package/src/components/cnpg/routes.ts +3 -1
  27. package/src/components/cnpg/shared.tsx +5 -53
  28. package/src/components/cnpg/useCNPGNavigate.ts +1 -21
  29. package/src/components/cnpg/useCNPGSidebarWorkspace.ts +16 -13
  30. package/src/components/community.tsx +42 -0
  31. package/src/components/diagnose/diagnoseEvidenceTypes.ts +2 -0
  32. package/src/components/diagnose/investigationMetrics.test.ts +20 -0
  33. package/src/components/diagnose/investigationMetrics.ts +2 -1
  34. package/src/components/dock/BottomDock.tsx +1 -0
  35. package/src/components/dock/LogsTab.tsx +3 -0
  36. package/src/components/gitops/GitOpsView.tsx +1 -1
  37. package/src/components/helm/HelmDrawerFrame.tsx +1 -1
  38. package/src/components/helm/HelmView.tsx +20 -16
  39. package/src/components/helm/OwnedResources.tsx +4 -3
  40. package/src/components/home/ClusterHealthCard.tsx +3 -1
  41. package/src/components/home/HomeAgentBlock.tsx +3 -0
  42. package/src/components/home/HomeView.tsx +7 -0
  43. package/src/components/home/MCPSetupDialog.test.tsx +19 -12
  44. package/src/components/home/MCPSetupDialog.tsx +4 -2
  45. package/src/components/home/mcpToolCatalog.ts +15 -2
  46. package/src/components/home/useVulnerabilitiesRow.test.ts +26 -0
  47. package/src/components/home/useVulnerabilitiesRow.ts +50 -0
  48. package/src/components/logs/LogsViewer.tsx +3 -1
  49. package/src/components/logs/MultiPodLogsTab.test.tsx +24 -4
  50. package/src/components/logs/MultiPodLogsTab.tsx +9 -5
  51. package/src/components/nav/PrimaryNavRail.test.tsx +17 -0
  52. package/src/components/nav/PrimaryNavRail.tsx +174 -29
  53. package/src/components/resource/PrometheusChartsGrid.tsx +5 -1
  54. package/src/components/resource/SubstrateHealthCharts.test.tsx +143 -0
  55. package/src/components/resource/SubstrateHealthCharts.tsx +254 -0
  56. package/src/components/resource/SubstrateVerdictLine.test.tsx +131 -0
  57. package/src/components/resource/SubstrateVerdictLine.tsx +180 -0
  58. package/src/components/resources/ResourcesView.tsx +12 -6
  59. package/src/components/resources/renderers/UpgradePlanRenderer.test.tsx +20 -0
  60. package/src/components/resources/renderers/UpgradePlanRenderer.tsx +22 -0
  61. package/src/components/resources/renderers/VeleroBackupRenderer.tsx +16 -36
  62. package/src/components/resources/renderers/VeleroRestoreRenderer.tsx +6 -19
  63. package/src/components/resources/renderers/WorkloadRenderer.tsx +8 -0
  64. package/src/components/rightsizing/RightsizingScanView.tsx +3 -2
  65. package/src/components/shared/LargeClusterNamespacePicker.test.tsx +27 -0
  66. package/src/components/shared/LargeClusterNamespacePicker.tsx +8 -2
  67. package/src/components/timeline/TimelineView.tsx +3 -1
  68. package/src/components/traffic/TrafficConnectionsTable.test.tsx +94 -0
  69. package/src/components/traffic/TrafficConnectionsTable.tsx +21 -5
  70. package/src/components/traffic/TrafficData.test.tsx +37 -0
  71. package/src/components/traffic/TrafficData.tsx +27 -0
  72. package/src/components/traffic/TrafficFlowList.tsx +9 -7
  73. package/src/components/traffic/TrafficGraph.layoutEngine.test.tsx +193 -0
  74. package/src/components/traffic/TrafficGraph.test.tsx +269 -0
  75. package/src/components/traffic/TrafficGraph.tsx +135 -64
  76. package/src/components/traffic/TrafficGraphUnavailable.tsx +57 -0
  77. package/src/components/traffic/TrafficView.layoutUnavailable.test.tsx +211 -0
  78. package/src/components/traffic/TrafficView.tsx +46 -129
  79. package/src/components/traffic/trafficFilters.test.ts +172 -1
  80. package/src/components/traffic/trafficFilters.ts +139 -0
  81. package/src/components/ui/DiagnosticsOverlay.tsx +14 -1
  82. package/src/components/ui/UpdateNotification.manual.test.tsx +5 -2
  83. package/src/components/ui/UpdateNotification.test.tsx +31 -2
  84. package/src/components/ui/UpdateNotification.tsx +34 -17
  85. package/src/components/ui/command-items.ts +24 -1
  86. package/src/components/velero/VeleroBackupNow.test.tsx +165 -0
  87. package/src/components/velero/VeleroBackupNow.tsx +143 -0
  88. package/src/components/velero/VeleroDeleteBackup.test.tsx +364 -0
  89. package/src/components/velero/VeleroDeleteBackup.tsx +306 -0
  90. package/src/components/velero/VeleroDetailPage.tsx +148 -0
  91. package/src/components/velero/VeleroKindLists.test.tsx +48 -0
  92. package/src/components/velero/VeleroKindLists.tsx +43 -0
  93. package/src/components/velero/VeleroLocations.expand.test.tsx +27 -0
  94. package/src/components/velero/VeleroLocations.test.tsx +86 -0
  95. package/src/components/velero/VeleroLocations.tsx +240 -0
  96. package/src/components/velero/VeleroOverview.test.tsx +311 -0
  97. package/src/components/velero/VeleroOverview.tsx +485 -0
  98. package/src/components/velero/VeleroPages.test.tsx +516 -0
  99. package/src/components/velero/VeleroPages.tsx +1056 -0
  100. package/src/components/velero/VeleroRunLists.tsx +309 -0
  101. package/src/components/velero/VeleroRunMessagesHost.test.tsx +25 -0
  102. package/src/components/velero/VeleroRunMessagesHost.tsx +54 -0
  103. package/src/components/velero/VeleroScheduleStatusBadge.test.tsx +28 -0
  104. package/src/components/velero/VeleroScheduleStatusBadge.tsx +21 -0
  105. package/src/components/velero/VeleroSchedules.tsx +255 -0
  106. package/src/components/velero/VeleroView.tsx +59 -0
  107. package/src/components/velero/VeleroWorkspace.gate.test.tsx +97 -0
  108. package/src/components/velero/attention.test.ts +178 -0
  109. package/src/components/velero/attention.ts +281 -0
  110. package/src/components/velero/backupDelete.test.tsx +91 -0
  111. package/src/components/velero/backupDelete.tsx +182 -0
  112. package/src/components/velero/coverage.test.ts +87 -0
  113. package/src/components/velero/coverage.ts +150 -0
  114. package/src/components/velero/host.tsx +86 -0
  115. package/src/components/velero/routes.ts +78 -0
  116. package/src/components/velero/runs.tsx +121 -0
  117. package/src/components/velero/shared.test.ts +84 -0
  118. package/src/components/velero/shared.tsx +423 -0
  119. package/src/components/velero/useVeleroSidebarWorkspace.test.tsx +28 -0
  120. package/src/components/velero/useVeleroSidebarWorkspace.ts +71 -0
  121. package/src/components/velero/velero.fixtures.ts +61 -0
  122. package/src/components/velero/workspaceRoute.ts +21 -0
  123. package/src/components/vulnerabilities/WorkloadVulnerabilitiesSection.tsx +167 -0
  124. package/src/components/vulnerabilities/parts.test.ts +72 -0
  125. package/src/components/vulnerabilities/parts.tsx +291 -0
  126. package/src/components/workload/WorkloadView.tsx +64 -27
  127. package/src/components/workspace/DrawerTrailBack.tsx +32 -0
  128. package/src/components/workspace/WorkspaceFrame.tsx +71 -0
  129. package/src/components/workspace/coverage.ts +61 -0
  130. package/src/components/workspace/layout.test.tsx +29 -1
  131. package/src/components/workspace/layout.tsx +15 -5
  132. package/src/components/workspace/sidebar.ts +9 -0
  133. package/src/components/workspace/useWorkspaceDrawer.ts +63 -0
  134. package/src/components/workspace/useWorkspaceNavigate.ts +21 -0
  135. package/src/desktop/AboutDialog.test.ts +12 -0
  136. package/src/desktop/AboutDialog.tsx +151 -0
  137. package/src/desktop/WindowsTitleBar.tsx +359 -0
  138. package/src/desktop/titleBar.test.ts +61 -0
  139. package/src/desktop/titleBar.ts +45 -0
  140. package/src/index.css +19 -0
  141. package/src/integrations/resourceHost.ts +5 -1
  142. package/src/integrations/resourceHosts.test.tsx +14 -2
  143. package/src/integrations/resourceHosts.tsx +22 -6
  144. package/src/integrations/workspaceRoute.ts +1 -1
  145. package/src/integrations/workspaceRoutes.test.ts +11 -0
  146. package/src/integrations/workspaceRoutes.ts +3 -1
  147. package/src/integrations/workspaceScreens.tsx +2 -0
  148. package/src/main.tsx +8 -0
  149. package/src/utils/desktop-zoom.test.ts +53 -0
  150. package/src/utils/desktop-zoom.ts +30 -0
  151. package/src/utils/staleAssetPrompt.test.tsx +76 -0
  152. package/src/utils/staleAssetPrompt.tsx +32 -0
@@ -0,0 +1,167 @@
1
+ import { Fragment } from 'react'
2
+ import { useNavigate, useSearchParams } from 'react-router-dom'
3
+ import { WithTooltip } from '../ui/Tooltip'
4
+ import { ChevronRight, Shield } from 'lucide-react'
5
+ import { Section } from '@skyhook-io/k8s-ui/components/ui/drawer-components'
6
+ import { formatRelativeAgeTime } from '@skyhook-io/k8s-ui/utils/format'
7
+ import { useAPIResources } from '../../api/apiResources'
8
+ import { useRadarFeature } from '../../api/client'
9
+ import { isRadarFeatureUnsupported } from '../../api/radarFeatures'
10
+ import { hasVulnerabilityReports, isKindUnknown, useVulnerabilities, workloadParam } from '../../api/vulnerabilities'
11
+ import { ClearedCount, FixVersion, ImageName, SeverityCounts, gapSentence } from './parts'
12
+
13
+ interface Props {
14
+ kind: string
15
+ namespace: string
16
+ name: string
17
+ }
18
+
19
+ /**
20
+ * A workload's vulnerabilities, for its drawer: per container image, what
21
+ * the current scan found, and the upgrades that clear the most. Absent where the
22
+ * cluster has no scanner reports or the Radar predates the endpoint.
23
+ */
24
+ export function WorkloadVulnerabilitiesSection({ kind, namespace, name }: Props) {
25
+ const navigate = useNavigate()
26
+ const [params] = useSearchParams()
27
+ const { data: resources } = useAPIResources()
28
+ const { support } = useRadarFeature('vulnerabilities')
29
+ const available = hasVulnerabilityReports(resources) && support !== 'unsupported'
30
+ const workload = { kind, namespace, name }
31
+ const { data, isLoading, error } = useVulnerabilities({ view: 'image', workload }, available && !!namespace && !!name)
32
+ // The upgrades it needs, as By fix works them out, once it has findings.
33
+ const { data: fixData } = useVulnerabilities({ view: 'fix', workload }, available && !!namespace && !!name && (data?.images ?? []).length > 0)
34
+ if (!available) return null
35
+ // An older Radar, or a report kind removed since the page loaded, has
36
+ // nothing to show here; anything else is a failure worth saying.
37
+ if (error && (isRadarFeatureUnsupported(error) || isKindUnknown(error))) return null
38
+ if (error) {
39
+ return (
40
+ <Section title="Vulnerabilities" icon={Shield}>
41
+ <p className="text-xs text-warning-text">Couldn't read vulnerability reports: {error instanceof Error ? error.message : 'request failed'}.</p>
42
+ </Section>
43
+ )
44
+ }
45
+
46
+ const images = data?.images ?? []
47
+ // The tab folds clean images away; a workload's drawer shows every container.
48
+ const clean = data?.clean ?? []
49
+ const unscanned = data?.unscanned ?? []
50
+ const critical = images.reduce((n, img) => n + (img.findingsUnread ? 0 : img.counts.critical), 0)
51
+ const upgrades = fixData?.fixes ?? []
52
+ // The read spans the caller's scope; a gap names this namespace, or might.
53
+ const relevantGaps = (data?.coverage.gaps ?? []).filter((g) => {
54
+ const ns = g.namespaces
55
+ return !ns || ns.extent !== undefined || (ns.names ?? []).length < ns.count || (ns.names ?? []).includes(namespace)
56
+ })
57
+ const isThis = (w: { kind: string; namespace: string; name: string }) => w.kind === kind && w.namespace === namespace && w.name === name
58
+ // The link keeps the page's namespace view, as every page link does: the
59
+ // picker follows the URL, so a narrower one would change it.
60
+ const open = (more: Record<string, string> = {}) => {
61
+ const search = new URLSearchParams({ workload: workloadParam({ kind, namespace, name }), ...more })
62
+ const viewNamespaces = params.get('namespaces')
63
+ if (viewNamespaces) search.set('namespaces', viewNamespaces)
64
+ navigate({ pathname: '/checks/vulnerabilities', search: search.toString() })
65
+ }
66
+
67
+ // Each image box opens the tab narrowed to this workload: one destination,
68
+ // so one obvious thing to click.
69
+ const card = (key: string, children: React.ReactNode) => (
70
+ <WithTooltip key={key} tip="Open in Vulnerabilities">
71
+ <button type="button" onClick={() => open()} className="group flex w-full items-center gap-2 rounded-md border border-theme-border bg-theme-surface px-3 py-2 text-left transition-colors hover:border-theme-text-tertiary hover:bg-theme-hover/50">
72
+ <span className="flex min-w-0 flex-1 flex-col gap-1">{children}</span>
73
+ <ChevronRight className="h-4 w-4 shrink-0 text-theme-text-tertiary transition-transform group-hover:translate-x-0.5" aria-hidden />
74
+ </button>
75
+ </WithTooltip>
76
+ )
77
+ const containerName = (workloads: { kind: string; namespace: string; name: string; container?: string }[]) => (
78
+ <span className="font-medium text-theme-text-primary">{[...new Set(workloads.filter(isThis).map((w) => w.container))].join(', ')}</span>
79
+ )
80
+
81
+ return (
82
+ <Section title={critical > 0 ? `Vulnerabilities · ${critical} critical` : 'Vulnerabilities'} icon={Shield}>
83
+ {isLoading ? (
84
+ <p className="text-sm text-theme-text-tertiary">Reading vulnerability reports…</p>
85
+ ) : (
86
+ <div className="flex flex-col gap-3 text-sm">
87
+ {images.map((img) => card(img.id, (
88
+ <>
89
+ <span className="flex flex-wrap items-baseline gap-x-2">
90
+ {containerName(img.workloads)}
91
+ <ImageName image={img.image} className="text-xs text-theme-text-tertiary" />
92
+ </span>
93
+ <span className="flex flex-wrap items-center gap-x-3">
94
+ {img.findingsUnread ? <span className="text-xs text-warning-text">Findings not read</span> : <SeverityCounts counts={img.counts} />}
95
+ <span className="text-xs text-theme-text-secondary">{img.findingsUnread ? '' : `${img.fixable.critical + img.fixable.high + img.fixable.medium + img.fixable.low + img.fixable.unknown} with a fix · `}scanned {formatRelativeAgeTime(img.scannedAt)}</span>
96
+ </span>
97
+ <SharedWith others={[...new Set(img.workloads.filter((w) => !isThis(w)).map((w) => `${w.namespace}/${w.name}`))]} partial={img.workloads.length < img.workloadsTotal} />
98
+ </>
99
+ )))}
100
+ {unscanned.map((u) => card(u.image, (
101
+ <>
102
+ <span className="flex flex-wrap items-baseline gap-x-2">
103
+ {containerName(u.workloads)}
104
+ <ImageName image={u.image} className="text-xs text-theme-text-tertiary" />
105
+ </span>
106
+ <span className="text-xs text-warning-text">Not scanned</span>
107
+ </>
108
+ )))}
109
+ {clean.map((img) => card(img.id, (
110
+ <>
111
+ <span className="flex flex-wrap items-baseline gap-x-2">
112
+ {containerName(img.workloads)}
113
+ <ImageName image={img.image} className="text-xs text-theme-text-tertiary" />
114
+ </span>
115
+ <span className="text-xs text-theme-text-secondary">No CVEs reported · scanned {formatRelativeAgeTime(img.scannedAt)}</span>
116
+ </>
117
+ )))}
118
+ {images.length === 0 && clean.length === 0 && unscanned.length === 0 && (
119
+ <p className="text-xs text-theme-text-tertiary">
120
+ {gapSentence(relevantGaps, { counts: false }) ?? 'No running containers in this workload.'}
121
+ </p>
122
+ )}
123
+ {upgrades.length > 0 && (
124
+ // One grid so packages, targets and counts line up; Critical and
125
+ // High are what decide which upgrade comes first.
126
+ <div className="grid grid-cols-[minmax(0,max-content)_minmax(0,1fr)_2rem_2.5rem] items-baseline gap-x-3 gap-y-1 text-xs">
127
+ <span className="col-span-2 font-medium text-theme-text-secondary">Upgrade first</span>
128
+ <span className="text-right text-theme-text-tertiary">C</span>
129
+ <span className="text-right text-theme-text-tertiary">H</span>
130
+ {upgrades.slice(0, UPGRADES_SHOWN).map((f) => (
131
+ <Fragment key={`${f.packageType ?? ''}/${f.package}/${f.to ?? (f.fixedVersions ?? []).join('|')}`}>
132
+ <span className="truncate font-mono text-theme-text-primary">{f.package}</span>
133
+ {f.to
134
+ ? <span className="flex min-w-0 items-baseline gap-1 font-mono"><span className="text-theme-text-tertiary">→</span><FixVersion installed={f.from.join(', ')} target={f.to} showInstalled={false} /></span>
135
+ : <span className="truncate font-mono text-theme-text-tertiary">fixed in {(f.fixedVersions ?? []).join(', ')}</span>}
136
+ <ClearedCount count={f.counts.critical} severity="critical" />
137
+ <ClearedCount count={f.counts.high} severity="high" />
138
+ </Fragment>
139
+ ))}
140
+ {upgrades.length > UPGRADES_SHOWN && (
141
+ <button type="button" onClick={() => open({ by: 'fix' })} className="col-span-4 justify-self-start text-accent-text hover:underline">
142
+ {upgrades.length - UPGRADES_SHOWN} more {upgrades.length - UPGRADES_SHOWN === 1 ? 'upgrade' : 'upgrades'} →
143
+ </button>
144
+ )}
145
+ </div>
146
+ )}
147
+ </div>
148
+ )}
149
+ </Section>
150
+ )
151
+ }
152
+
153
+ // Upgrades shown in the drawer; the rest are one click away in By fix.
154
+ const UPGRADES_SHOWN = 3
155
+
156
+ // The same image in other workloads: one rebuild fixes them all.
157
+ // partial: the response lists only some of the image's workloads.
158
+ function SharedWith({ others, partial }: { others: string[]; partial: boolean }) {
159
+ if (others.length === 0) return null
160
+ const shown = others.slice(0, 2).join(', ')
161
+ const rest = others.length - 2
162
+ return (
163
+ <span className="text-xs text-theme-text-tertiary">
164
+ Also runs in {shown}{rest > 0 ? ` and ${rest}${partial ? '+' : ''} more` : partial ? ', maybe more' : ''}
165
+ </span>
166
+ )
167
+ }
@@ -0,0 +1,72 @@
1
+ import { describe, expect, it } from 'vitest'
2
+ import { ApiError } from '../../api/client'
3
+ import { hasVulnerabilityReports, isKindUnknown, parseWorkloadParam, vulnerabilitiesPath, workloadParam } from '../../api/vulnerabilities'
4
+ import { findingsCertainty, gapSentence, imageParts, workloadSummary } from './parts'
5
+
6
+ describe('vulnerabilities helpers', () => {
7
+ it('builds the request from filters', () => {
8
+ expect(vulnerabilitiesPath({ view: 'cve', namespaces: ['shop', 'prod'], severities: ['critical', 'high'], fixableOnly: true, query: ' zlib ' }))
9
+ .toBe('/vulnerabilities?view=cve&namespaces=shop%2Cprod&severity=critical%2Chigh&fixable=1&q=zlib')
10
+ expect(vulnerabilitiesPath({ view: 'image', workload: { kind: 'Deployment', namespace: 'shop', name: 'web' } }))
11
+ .toBe('/vulnerabilities?view=image&workloadKind=Deployment&workloadNamespace=shop&workloadName=web')
12
+ })
13
+
14
+ it('round-trips the workload filter and rejects anything else', () => {
15
+ const w = { kind: 'Deployment', namespace: 'shop', name: 'checkout' }
16
+ expect(parseWorkloadParam(workloadParam(w))).toEqual(w)
17
+ expect(parseWorkloadParam('checkout')).toBeUndefined()
18
+ expect(parseWorkloadParam('Deployment//checkout')).toBeUndefined()
19
+ expect(parseWorkloadParam(null)).toBeUndefined()
20
+ })
21
+
22
+ it('reads a 404 as no scanner only when the handler says the kind is unknown', () => {
23
+ expect(isKindUnknown(new ApiError('no kind', 404, { error_code: 'kind_unknown' }))).toBe(true)
24
+ expect(isKindUnknown(new ApiError('not found', 404))).toBe(false)
25
+ expect(isKindUnknown(new ApiError('boom', 500, { error_code: 'kind_unknown' }))).toBe(false)
26
+ })
27
+
28
+ it('detects the report kind by group and plural, not by kind name alone', () => {
29
+ expect(hasVulnerabilityReports(undefined)).toBe(false)
30
+ expect(hasVulnerabilityReports([{ name: 'vulnerabilityreports', kind: 'VulnerabilityReport', group: 'example.com', version: 'v1', namespaced: true, verbs: [], isCrd: true }])).toBe(false)
31
+ expect(hasVulnerabilityReports([{ name: 'vulnerabilityreports', kind: 'VulnerabilityReport', group: 'aquasecurity.github.io', version: 'v1alpha1', namespaced: true, verbs: [], isCrd: true }])).toBe(true)
32
+ })
33
+
34
+ it('names withheld namespaces and says counts cover the rest', () => {
35
+ expect(gapSentence([])).toBeNull()
36
+ expect(gapSentence([{ code: 'user_forbidden', namespaces: { count: 2, names: ['a', 'b'] } }]))
37
+ .toBe("Your access doesn't include the reports in 2 namespaces (a, b). Counts cover the rest.")
38
+ const unknown = { extent: 'unknown' }
39
+ expect(gapSentence([{ code: 'radar_namespace_not_collected', kinds: { count: 1, names: [{ kind: 'VulnerabilityReport', group: 'aquasecurity.github.io' }] }, namespaces: unknown }]))
40
+ .toBe("Radar doesn't collect reports in some namespaces. Counts cover the rest.")
41
+ expect(gapSentence([{ code: 'user_forbidden', kinds: { count: 1, names: [{ kind: 'Pod' }] }, namespaces: { count: 1, names: ['kube-system'] } }]))
42
+ .toBe("Your access doesn't include some Pods in 1 namespace (kube-system); their scans aren't counted. Counts cover the rest.")
43
+ // Without ReplicaSets only the workload names change; every count holds.
44
+ expect(gapSentence([{ code: 'radar_kind_not_collected', kinds: { count: 1, names: [{ kind: 'ReplicaSet', group: 'apps' }] }, namespaces: unknown }]))
45
+ .toBe("Radar doesn't collect ReplicaSets, so Deployments there are named and counted by their ReplicaSets.")
46
+ // A ReplicaSet the caller may not read withholds its scans.
47
+ expect(gapSentence([{ code: 'user_forbidden', kinds: { count: 1, names: [{ kind: 'ReplicaSet', group: 'apps' }] }, namespaces: { count: 1, names: ['shop'] } }]))
48
+ .toBe("Your access doesn't include some ReplicaSets in 1 namespace (shop); their scans aren't counted. Counts cover the rest.")
49
+ })
50
+
51
+ it('keeps totals exact when only rows are capped or names change', () => {
52
+ const summary = { imagesScanned: 3, imagesUnscanned: 0 } as Parameters<typeof findingsCertainty>[0]['summary']
53
+ const coverage = { complete: false, gaps: [], inactiveReports: 0, rowsOmitted: 40 }
54
+ expect(findingsCertainty({ summary, coverage })).toBe('exact')
55
+ const rs = { code: 'radar_kind_not_collected', kinds: { count: 1, names: [{ kind: 'ReplicaSet' }] } }
56
+ expect(findingsCertainty({ summary, coverage: { ...coverage, gaps: [rs] } })).toBe('exact')
57
+ expect(findingsCertainty({ summary, coverage: { ...coverage, gaps: [{ code: 'user_forbidden' }] } })).toBe('lower_bound')
58
+ expect(findingsCertainty({ summary, coverage: { ...coverage, gaps: [{ ...rs, code: 'user_forbidden' }] } })).toBe('lower_bound')
59
+ })
60
+
61
+ it('leads an image with the part that tells images apart', () => {
62
+ expect(imageParts('us-central1-docker.pkg.dev/online-boutique-ci/microservices-demo/currencyservice:v0.10.7'))
63
+ .toEqual({ name: 'currencyservice:v0.10.7', path: 'us-central1-docker.pkg.dev/online-boutique-ci/microservices-demo' })
64
+ expect(imageParts('redis:alpine')).toEqual({ name: 'redis:alpine', path: '' })
65
+ expect(imageParts('ghcr.io/acme/app:1@sha256:abc').name).toBe('app:1')
66
+ })
67
+
68
+ it('summarizes workloads by distinct name', () => {
69
+ const w = (name: string, container = 'app') => ({ kind: 'Deployment', group: 'apps', namespace: 'shop', name, container })
70
+ expect(workloadSummary([w('a'), w('a', 'sidecar'), w('b'), w('c'), w('d')])).toBe('a, b +2')
71
+ })
72
+ })
@@ -0,0 +1,291 @@
1
+ import { clsx } from 'clsx'
2
+ import { WithTooltip } from '../ui/Tooltip'
3
+ import { CertaintyGlyph, gapReasonText, VULN_SEVERITY_BADGE, VULN_SEVERITY_BAR, VULN_SEVERITY_TEXT, type Certainty } from '@skyhook-io/k8s-ui'
4
+ import { SEVERITY_TEXT } from '@skyhook-io/k8s-ui/utils/badge-colors'
5
+ import type {
6
+ VulnerabilitiesResponse,
7
+ VulnerabilityCounts,
8
+ VulnerabilityGap,
9
+ VulnerabilitySeverity,
10
+ VulnerabilityWorkloadRef,
11
+ } from '../../api/vulnerabilities'
12
+
13
+ export const SEVERITIES: { key: VulnerabilitySeverity; label: string; letter: string }[] = [
14
+ { key: 'critical', label: 'Critical', letter: 'C' },
15
+ { key: 'high', label: 'High', letter: 'H' },
16
+ { key: 'medium', label: 'Medium', letter: 'M' },
17
+ { key: 'low', label: 'Low', letter: 'L' },
18
+ ]
19
+
20
+ const upper = (s: VulnerabilitySeverity) => s.toUpperCase()
21
+
22
+ export function totalFindings(c: VulnerabilityCounts): number {
23
+ return c.critical + c.high + c.medium + c.low + c.unknown
24
+ }
25
+
26
+ /** Stacked bar of findings per severity; letters keep it readable without color. */
27
+ export function SeverityBar({ counts, className }: { counts: VulnerabilityCounts; className?: string }) {
28
+ const total = totalFindings(counts)
29
+ return (
30
+ <div className={clsx('flex min-w-0 flex-col gap-1', className)}>
31
+ <div className="flex h-1.5 overflow-hidden rounded-full bg-theme-elevated" aria-hidden>
32
+ {total > 0 && [...SEVERITIES, { key: 'unknown' as const }].map(({ key }) => (
33
+ counts[key] > 0 ? <span key={key} className={VULN_SEVERITY_BAR[upper(key)]} style={{ width: `${(100 * counts[key]) / total}%` }} /> : null
34
+ ))}
35
+ </div>
36
+ <SeverityCounts counts={counts} />
37
+ </div>
38
+ )
39
+ }
40
+
41
+ /**
42
+ * An image reference split for display: the last path segment with its tag
43
+ * (what tells images apart) and the registry/repository path before it.
44
+ */
45
+ export function imageParts(ref: string): { name: string; path: string } {
46
+ const bare = ref.split('@')[0]
47
+ const slash = bare.lastIndexOf('/')
48
+ return slash < 0 ? { name: bare, path: '' } : { name: bare.slice(slash + 1), path: bare.slice(0, slash) }
49
+ }
50
+
51
+ /** An image's name and tag, with the full reference on hover. */
52
+ export function ImageName({ image, className }: { image: string; className?: string }) {
53
+ const { name } = imageParts(image)
54
+ return (
55
+ <WithTooltip tip={image}>
56
+ <span className={clsx('truncate font-mono', className)}>{name}</span>
57
+ </WithTooltip>
58
+ )
59
+ }
60
+
61
+ export function SeverityCounts({ counts }: { counts: VulnerabilityCounts }) {
62
+ if (totalFindings(counts) === 0) {
63
+ return <span className="text-xs text-theme-text-tertiary">No CVEs reported</span>
64
+ }
65
+ // Zeros are left out: "H 1" reads faster than "C 0 H 1 M 0 L 0".
66
+ return (
67
+ <span className="flex flex-wrap gap-x-2.5 font-mono text-xs tabular-nums">
68
+ {SEVERITIES.filter(({ key }) => counts[key] > 0).map(({ key, letter, label }) => (
69
+ <WithTooltip key={key} tip={`${counts[key]} ${label}`}>
70
+ <span className={VULN_SEVERITY_TEXT[upper(key)]}>{letter}&thinsp;{counts[key]}</span>
71
+ </WithTooltip>
72
+ ))}
73
+ {counts.unknown > 0 && (
74
+ <WithTooltip tip={`${counts.unknown} not yet rated by the scanner`}>
75
+ <span className="text-theme-text-tertiary">? {counts.unknown}</span>
76
+ </WithTooltip>
77
+ )}
78
+ </span>
79
+ )
80
+ }
81
+
82
+ // fromScore: the scanner gave no severity; Radar rated the CVSS score.
83
+ export function SeverityBadge({ severity, fromScore, score }: { severity: VulnerabilitySeverity; fromScore?: boolean; score?: number }) {
84
+ const label = SEVERITIES.find((s) => s.key === severity)?.label ?? 'Unknown'
85
+ const badge = <span className={clsx('badge-sm w-fit justify-self-start border', VULN_SEVERITY_BADGE[upper(severity)])}>{label}</span>
86
+ return fromScore ? <WithTooltip tip={`Trivy gave no severity; rated from its CVSS score${score !== undefined ? ` (${score.toFixed(1)})` : ''}`}>{badge}</WithTooltip> : badge
87
+ }
88
+
89
+ /**
90
+ * An installed version and the one to move to. The scanner lists one fix
91
+ * per maintained branch ("v0.38.0, v0.36.1"); the target is the smallest
92
+ * above the installed version, with the full list on hover. When Radar
93
+ * couldn't pick a target, the scanner's list stands as written, without
94
+ * an arrow or the color of a recommendation.
95
+ */
96
+ export function FixVersion({ installed, fixed, target, showInstalled = true, className }: { installed: string; fixed?: string; target?: string; showInstalled?: boolean; className?: string }) {
97
+ if (!target && fixed) {
98
+ return (
99
+ <WithTooltip tip={`Installed ${installed}. The scanner lists ${fixed} as fixed, but Radar couldn't confirm it's above the installed version.`}>
100
+ <span className={clsx('min-w-0 truncate font-mono text-theme-text-secondary', className)}>
101
+ {showInstalled && <span className="text-theme-text-tertiary">{installed} · </span>}fixed in {fixed}
102
+ </span>
103
+ </WithTooltip>
104
+ )
105
+ }
106
+ const tip = target ? `${installed} → ${target}${fixed && fixed !== target ? ` (fixed releases: ${fixed})` : ''}` : undefined
107
+ return (
108
+ <WithTooltip tip={tip}>
109
+ {/* The installed side gives way first: the target is what to act on. */}
110
+ <span className={clsx('flex min-w-0 items-baseline font-mono', className)}>
111
+ {showInstalled && <span className="min-w-0 shrink-[100] truncate text-theme-text-tertiary">{installed}</span>}
112
+ {showInstalled && <span className="shrink-0 whitespace-pre text-theme-text-tertiary"> → </span>}
113
+ {target ? <span className={clsx('min-w-0 truncate', SEVERITY_TEXT.success)}>{target}</span> : <span className="min-w-0 truncate text-theme-text-tertiary">no fix yet</span>}
114
+ </span>
115
+ </WithTooltip>
116
+ )
117
+ }
118
+
119
+ // Keys are the scanner's package types and, for reports without them, the
120
+ // ecosystem Radar reads from the package URL (deb, pypi, golang, …).
121
+ const ECOSYSTEMS: Record<string, string> = {
122
+ deb: 'OS package (deb)', apk: 'OS package (apk)', rpm: 'OS package (rpm)',
123
+ pypi: 'Python package', gem: 'Ruby gem', cocoapods: 'CocoaPods pod', maven: 'Java library', golang: 'Go module',
124
+ cargo: 'Rust crate', pub: 'Dart package', hex: 'Elixir package', swift: 'Swift package', rustbinary: 'Rust crate, compiled in',
125
+ debian: 'Debian package', ubuntu: 'Ubuntu package', alpine: 'Alpine package', wolfi: 'Wolfi package', chainguard: 'Chainguard package',
126
+ redhat: 'RPM package', centos: 'RPM package', rocky: 'RPM package', alma: 'RPM package', amazon: 'RPM package', oracle: 'RPM package',
127
+ fedora: 'RPM package', suse: 'RPM package', 'cbl-mariner': 'RPM package', azurelinux: 'RPM package', photon: 'RPM package',
128
+ gobinary: 'Go module, compiled in', gomod: 'Go module', npm: 'npm package', 'node-pkg': 'npm package', yarn: 'npm package', pnpm: 'npm package', bun: 'npm package',
129
+ 'python-pkg': 'Python package', pip: 'Python package', pipenv: 'Python package', poetry: 'Python package', uv: 'Python package',
130
+ jar: 'Java library', pom: 'Java library', gradle: 'Java library', sbt: 'Java library',
131
+ gemspec: 'Ruby gem', bundler: 'Ruby gem', 'rust-binary': 'Rust crate, compiled in',
132
+ composer: 'PHP package', nuget: '.NET package', 'dotnet-core': '.NET package',
133
+ }
134
+
135
+ /** The scanner's package type in words ("gobinary" → "Go module, compiled in"). */
136
+ export function ecosystemLabel(packageType?: string): string | undefined {
137
+ if (!packageType) return undefined
138
+ return ECOSYSTEMS[packageType.toLowerCase()] ?? packageType
139
+ }
140
+
141
+ /** "checkout, worker +4" for a list of workloads, each named once. */
142
+ export function workloadSummary(workloads: VulnerabilityWorkloadRef[], shown = 2): string {
143
+ const names = [...new Set(workloads.map((w) => w.name))]
144
+ const head = names.slice(0, shown).join(', ')
145
+ return names.length > shown ? `${head} +${names.length - shown}` : head
146
+ }
147
+
148
+ export function distinctNamespaces(workloads: VulnerabilityWorkloadRef[]): number {
149
+ return new Set(workloads.map((w) => w.namespace)).size
150
+ }
151
+
152
+ type KindName = { kind: string; group?: string }
153
+
154
+ const REPORT_KIND = 'VulnerabilityReport'
155
+
156
+ // What a gap left unread: the reports when it names no kind.
157
+ function gapKinds(gap: VulnerabilityGap): KindName[] {
158
+ return gap.kinds?.names?.length ? gap.kinds.names : [{ kind: REPORT_KIND }]
159
+ }
160
+
161
+ const kindWords = (kinds: KindName[]) => kinds.map((k) => (k.kind === REPORT_KIND ? 'reports' : `${k.kind}s`)).join(', ')
162
+
163
+ // Codes for a kind Radar doesn't hold, rather than one the caller may not read.
164
+ const COLLECTION_CODES = new Set(['radar_kind_not_collected', 'radar_namespace_not_collected', 'kind_sync_pending', 'kind_sync_timed_out'])
165
+
166
+ /**
167
+ * A gap that leaves the finding counts exact: where Radar doesn't hold
168
+ * ReplicaSets, a Deployment's containers are named, and counted, by their
169
+ * ReplicaSets, but their findings are read. A ReplicaSet the caller may not
170
+ * read is withheld.
171
+ */
172
+ function namesOnly(gap: VulnerabilityGap): boolean {
173
+ return COLLECTION_CODES.has(gap.code) && gapKinds(gap).every((k) => k.kind === 'ReplicaSet')
174
+ }
175
+
176
+ /**
177
+ * How many CVEs an upgrade clears at one severity, right-aligned for a
178
+ * column of them; a dash for none. Upgrade lists show Critical and High
179
+ * only: those decide which upgrade comes first.
180
+ */
181
+ export function ClearedCount({ count, severity }: { count: number; severity: 'critical' | 'high' }) {
182
+ return <span className={clsx('text-right font-mono tabular-nums', count > 0 ? VULN_SEVERITY_TEXT[upper(severity)] : 'text-theme-text-tertiary')}>{count > 0 ? count : '–'}</span>
183
+ }
184
+
185
+ /** Why a build of a moved tag stays unscanned, and the ways out: for a tooltip. */
186
+ export const OTHER_BUILD_TIP = "These Pods pulled the tag before it moved. Trivy scans only the build the tag points to now, so this one won't be scanned. Pin the image by digest to keep scans matched, or redeploy so the Pods pull the current build."
187
+
188
+ /** Whether a Deployment may count once per ReplicaSet in the workload totals. */
189
+ export function workloadsByReplicaSet(coverage: VulnerabilitiesResponse['coverage']): boolean {
190
+ return coverage.gaps.some(namesOnly)
191
+ }
192
+
193
+ /** Whether what Radar read covers the scope: unlisted rows don't count. */
194
+ export function readsComplete(coverage: VulnerabilitiesResponse['coverage']): boolean {
195
+ return !coverage.truncated && coverage.gaps.every(namesOnly)
196
+ }
197
+
198
+ function gapWhere(gap: VulnerabilityGap): string {
199
+ const ns = gap.namespaces
200
+ if (!ns) return ''
201
+ // A kind not collected or not loaded at all has no namespaces to name.
202
+ if (ns.extent === 'unknown') return gap.code === 'radar_namespace_not_collected' ? ' in some namespaces' : ''
203
+ const names = ns.names ?? []
204
+ const count = ns.count ?? names.length
205
+ if (count === 0) return ''
206
+ const list = names.length > 0 ? ` (${names.slice(0, 5).join(', ')}${count > 5 ? ', …' : ''})` : ''
207
+ return ` in ${count} ${count === 1 ? 'namespace' : 'namespaces'}${list}`
208
+ }
209
+
210
+ function gapPart(gap: VulnerabilityGap): string {
211
+ if (gap.code === 'user_no_namespace_access') return "You don't have access to any namespace."
212
+ const kinds = gapKinds(gap)
213
+ if (kinds.some((k) => k.kind === 'Namespace')) {
214
+ return "Radar can't list namespaces, so it checked only those that hold reports."
215
+ }
216
+ const words = kindWords(kinds)
217
+ const where = gapWhere(gap)
218
+ let part: string
219
+ switch (gap.code) {
220
+ case 'user_forbidden':
221
+ part = `Your access doesn't include ${kinds[0].kind === REPORT_KIND ? 'the reports' : `some ${words}`}${where}`
222
+ break
223
+ case 'user_permission_check_failed':
224
+ part = `Radar couldn't check your access to ${words}${where}; refresh to check again`
225
+ break
226
+ case 'radar_kind_not_collected':
227
+ case 'radar_namespace_not_collected':
228
+ part = `Radar doesn't collect ${words}${where}`
229
+ break
230
+ case 'kind_sync_pending':
231
+ part = `${capitalize(words)}${where} are still loading`
232
+ break
233
+ case 'kind_sync_timed_out':
234
+ part = `${capitalize(words)}${where} didn't finish loading`
235
+ break
236
+ default:
237
+ part = `Radar couldn't read ${words}${where} (${gapReasonText(gap.code)})`
238
+ }
239
+ const kind = kinds[0].kind
240
+ if (kind === REPORT_KIND) return `${part}.`
241
+ const collection = COLLECTION_CODES.has(gap.code) && kinds.length === 1
242
+ if (collection && kind === 'Pod') return `${part}, so what runs there is unknown and its reports aren't counted.`
243
+ if (namesOnly(gap)) return `${part}, so Deployments there are named and counted by their ReplicaSets.`
244
+ if (collection && kind === 'CronJob') return `${part}, so CronJob scans there aren't counted.`
245
+ // A Job's Pods can't be traced to the CronJob Trivy scanned them through.
246
+ if (collection && kind === 'Job') return `${part}, so scans of Jobs and of the CronJobs they ran there aren't counted.`
247
+ // Objects the caller may not read: their scans are withheld.
248
+ return `${part}; their scans aren't counted.`
249
+ }
250
+
251
+ const capitalize = (s: string) => s.charAt(0).toUpperCase() + s.slice(1)
252
+
253
+ /** The sentence for coverage gaps, or null when none. */
254
+ export function gapSentence(gaps: VulnerabilityGap[], { counts = true } = {}): string | null {
255
+ if (gaps.length === 0) return null
256
+ const parts = [...new Set(gaps.map(gapPart))]
257
+ if (counts && !gaps.every(namesOnly)) parts.push('Counts cover the rest.')
258
+ return parts.join(' ')
259
+ }
260
+
261
+ /**
262
+ * How exactly the finding totals are known. A running image without a
263
+ * report, or reports the caller can't read, make the totals lower bounds;
264
+ * with nothing scanned they are unknown, never zero. Rows the response
265
+ * doesn't list don't: the totals are counted before rows are capped.
266
+ */
267
+ export function findingsCertainty(data: Pick<VulnerabilitiesResponse, 'summary' | 'coverage'>): 'exact' | 'lower_bound' | 'unknown' {
268
+ const partial = data.summary.imagesUnscanned > 0 || !readsComplete(data.coverage)
269
+ if (data.summary.imagesScanned === 0 && partial) return 'unknown'
270
+ return partial ? 'lower_bound' : 'exact'
271
+ }
272
+
273
+ /** A finding total under its certainty: "—" when unknown, "≥ n" when a bound. */
274
+ export function FindingTotal({ value, certainty, className }: { value: number; certainty: Certainty; className?: string }) {
275
+ if (certainty === 'unknown') {
276
+ return <span className={clsx('font-mono text-theme-text-tertiary', className)}>—</span>
277
+ }
278
+ return (
279
+ <span className={clsx('inline-flex items-baseline gap-1.5', className)}>
280
+ {certainty === 'lower_bound' && <CertaintyGlyph certainty="lower_bound" title="At least: some running images have no report, or some reports aren't readable" />}
281
+ <span className="font-mono">{value}</span>
282
+ </span>
283
+ )
284
+ }
285
+
286
+ // The installed side of an upgrade: two versions read fine, more push the
287
+ // version to move to out of the cell, so they collapse to a count (the
288
+ // full list is in the row's tooltip and expanded detail).
289
+ export function installedLabel(from: string[]): string {
290
+ return from.length > 2 ? `${from.length} versions` : from.join(', ')
291
+ }