@skyhook-io/radar-app 1.21.3 → 1.21.5

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 (42) hide show
  1. package/package.json +1 -1
  2. package/src/App.tsx +3 -0
  3. package/src/api/client.ts +42 -2
  4. package/src/api/radarFeatures.ts +2 -0
  5. package/src/api/vulnerabilities.export.test.ts +44 -0
  6. package/src/api/vulnerabilities.ts +73 -4
  7. package/src/components/applications/ApplicationsView.tsx +38 -8
  8. package/src/components/applications/ArgoSyncDetails.tsx +32 -0
  9. package/src/components/applications/RenderedChanges.test.tsx +179 -0
  10. package/src/components/applications/RenderedChanges.tsx +233 -0
  11. package/src/components/audit/AuditView.tsx +2 -1
  12. package/src/components/audit/VulnerabilitiesView.test.tsx +177 -0
  13. package/src/components/audit/VulnerabilitiesView.tsx +197 -48
  14. package/src/components/diagnose/investigationEvidence/adapters/helm.test.tsx +30 -0
  15. package/src/components/diagnose/investigationEvidence/adapters/helm.ts +21 -1
  16. package/src/components/diagnose/investigationEvidence/bodies/platform.tsx +9 -0
  17. package/src/components/diagnose/investigationEvidence/types.ts +12 -0
  18. package/src/components/helm/HelmReleaseDrawer.test.ts +27 -0
  19. package/src/components/helm/HelmReleaseDrawer.tsx +24 -3
  20. package/src/components/helm/HelmView.tsx +16 -6
  21. package/src/components/helm/ObservedHelmReleaseDrawer.tsx +3 -0
  22. package/src/components/helm/releaseController.test.tsx +26 -0
  23. package/src/components/helm/releaseController.tsx +98 -0
  24. package/src/components/resources/renderers/K3sHelmChartRenderer.tsx +18 -0
  25. package/src/components/traffic/TrafficGraph.export.test.tsx +57 -0
  26. package/src/components/traffic/TrafficGraph.tsx +11 -20
  27. package/src/components/traffic/TrafficView.layoutUnavailable.test.tsx +1 -0
  28. package/src/components/traffic/TrafficView.tsx +17 -2
  29. package/src/components/traffic/traffic-export.test.ts +51 -0
  30. package/src/components/traffic/traffic-export.ts +114 -0
  31. package/src/components/traffic/trafficFilters.ts +16 -0
  32. package/src/components/vulnerabilities/WorkloadVulnerabilitiesSection.test.tsx +30 -1
  33. package/src/components/vulnerabilities/WorkloadVulnerabilitiesSection.tsx +3 -2
  34. package/src/components/vulnerabilities/parts.test.ts +59 -3
  35. package/src/components/vulnerabilities/parts.tsx +199 -5
  36. package/src/components/workload/WorkloadRevisionsButton.test.tsx +34 -0
  37. package/src/components/workload/WorkloadRevisionsButton.tsx +31 -0
  38. package/src/components/workload/WorkloadView.tsx +11 -3
  39. package/src/hooks/useDesktopDownload.test.tsx +57 -0
  40. package/src/hooks/useDesktopDownload.ts +31 -9
  41. package/src/integrations/resourceHosts.test.tsx +1 -1
  42. package/src/integrations/resourceHosts.tsx +2 -0
@@ -13,11 +13,13 @@ import { TrafficSourcePill } from './TrafficSourcePill'
13
13
  import { TrafficGraphTooLarge } from './TrafficGraphTooLarge'
14
14
  import { TrafficGraphUnavailable } from './TrafficGraphUnavailable'
15
15
  import { useQueryClient } from '@tanstack/react-query'
16
- import { useDock } from '../dock'
16
+ import { useDock, useDockReservedHeight } from '../dock'
17
17
  import { AlertBanner, EmptyState, PaneLoader, FreshnessControl } from '@skyhook-io/k8s-ui'
18
18
  import { useConnection } from '../../context/ConnectionContext'
19
+ import { useDesktopBlobDownload } from '../../hooks/useDesktopDownload'
19
20
  import { Tooltip } from '../ui/Tooltip'
20
21
  import { SEVERITY_TEXT } from '@skyhook-io/k8s-ui/utils/badge-colors'
22
+ import { DURATION_DOCK } from '@skyhook-io/k8s-ui/utils/animation'
21
23
  import { matchesStatusRanges, bucketsFromCounts, bucketsFromStatus, isRateBasedSource, keepAvailable, effectiveThreshold, volumeUnit, type VolumeUnit, isExternalKind, groupAddonFlows, mergeFlowVolume, coverageLabel, type GraphFlow, endpointPair, graphEndpoint, graphEndpointId, mergeRawPairs, mergedEdgePort, selectedEdgeMatcher, selectionRawPairs, selectionMatch, graphSize, GRAPH_DRAW_BUDGET, GRAPH_DRAW_CEILING, parseFocus, focusParam, focusId, focusNeighborhood, touchesFocus, endpointSummaries, namespaceSummaries, verdictChoices, type TrafficFocus, warningRetries, warningBannerTitle, emptyWarningHeadline, rateWindowSeconds } from './trafficFilters'
22
24
 
23
25
  // Where a warning about which cluster the traffic belongs to points: how the map
@@ -390,6 +392,7 @@ interface TrafficViewProps {
390
392
 
391
393
  export function TrafficView({ namespaces, onSetNamespaces }: TrafficViewProps) {
392
394
  const { connection } = useConnection()
395
+ const desktopBlobDownload = useDesktopBlobDownload()
393
396
  const [wizardState, setWizardState] = useState<TrafficWizardState>('detecting')
394
397
  const [timeRange, setTimeRange] = useState<string>('5m')
395
398
  const [hideSystem, setHideSystem] = useState(true)
@@ -429,6 +432,7 @@ export function TrafficView({ namespaces, onSetNamespaces }: TrafficViewProps) {
429
432
  const [layoutUnavailable, setLayoutUnavailable] = useState(false)
430
433
  const dock = useDock()
431
434
  const graphPaneRef = useRef<HTMLDivElement>(null)
435
+ const dockInset = useDockReservedHeight()
432
436
 
433
437
  const focusValue = searchParams.get('focus')
434
438
  const focus = useMemo(() => parseFocus(focusValue), [focusValue])
@@ -1330,7 +1334,17 @@ export function TrafficView({ namespaces, onSetNamespaces }: TrafficViewProps) {
1330
1334
  />
1331
1335
 
1332
1336
  {/* Main content area */}
1333
- <div ref={graphPaneRef} className="flex-1 relative min-w-0">
1337
+ {/* The dock spans only this pane (see setLeftOffset), so the pane
1338
+ shrinks above it rather than the app-wide DockSpacer shrinking the
1339
+ filter sidebar too. */}
1340
+ <div
1341
+ ref={graphPaneRef}
1342
+ className="flex-1 relative min-w-0"
1343
+ style={{
1344
+ marginBottom: dockInset,
1345
+ transition: dock.isResizing ? 'none' : `margin-bottom ${DURATION_DOCK}ms cubic-bezier(0.4, 0, 0.2, 1)`,
1346
+ }}
1347
+ >
1334
1348
  {/* Floating controls — overlaid on graph like topology view */}
1335
1349
  {(() => {
1336
1350
  const availableSources = sourcesData?.detected.filter(s => s.status === 'available') || []
@@ -1513,6 +1527,7 @@ export function TrafficView({ namespaces, onSetNamespaces }: TrafficViewProps) {
1513
1527
  focusedId={focusKey}
1514
1528
  onLayoutUnavailable={setLayoutUnavailable}
1515
1529
  windowSeconds={rateWindowSeconds(timeRange)}
1530
+ onDownloadBlob={desktopBlobDownload}
1516
1531
  />
1517
1532
  </>
1518
1533
  )}
@@ -0,0 +1,51 @@
1
+ import { describe, expect, it } from 'vitest'
2
+ import { describeTrafficNode } from './traffic-export'
3
+
4
+ describe('describeTrafficNode', () => {
5
+ it('makes the addon group the only container', () => {
6
+ expect(describeTrafficNode({ id: 'addon-group', type: 'addonGroup', data: {} })).toMatchObject({ shape: 'group', tone: 'addon' })
7
+ const node = describeTrafficNode({ id: 'shop/web', type: 'traffic', data: { kind: 'Pod', label: 'web', namespace: 'shop', namespaceColor: '#1e3a5f' } })
8
+ expect(node).toMatchObject({ shape: 'resource', name: 'web', detail: 'shop', fill: '#1e3a5f' })
9
+ })
10
+
11
+ it('shows a workload by its workload kind', () => {
12
+ expect(describeTrafficNode({ id: 'shop/api', type: 'traffic', data: { kind: 'Workload', workloadKind: 'Deployment', label: 'api' } }))
13
+ .toMatchObject({ kind: 'Deployment', kindLabel: 'Deployment' })
14
+ })
15
+
16
+ it('keeps the category of an external service and no namespace tint', () => {
17
+ const node = describeTrafficNode({ id: 'db.example.com', type: 'traffic', data: { kind: 'External', label: 'db.example.com', serviceCategory: 'database', namespaceColor: '#123456' } })
18
+ expect(node).toMatchObject({ shape: 'resource', kind: 'External', category: 'database' })
19
+ expect(node?.fill).toBeUndefined()
20
+ })
21
+
22
+ it('lists ports with their counts, up to the card limit, or the connection total', () => {
23
+ const ports = [80, 443, 8080, 9090, 9100].map((port, i) => ({ port, connections: i === 1 ? 0 : 1500 }))
24
+ const node = describeTrafficNode({ id: 'shop/api', type: 'traffic', data: { kind: 'Pod', label: 'api', ports, isHotPath: true } })
25
+ expect(node?.rows).toEqual([
26
+ { text: ':80', code: true, hot: true, value: '2K' },
27
+ { text: ':443', code: true, hot: true },
28
+ { text: ':8080', code: true, hot: true, value: '2K' },
29
+ { text: ':9090', code: true, hot: true, value: '2K' },
30
+ { text: '+1 more', muted: true },
31
+ ])
32
+
33
+ const client = describeTrafficNode({ id: 'demo/client', type: 'traffic', data: { kind: 'Pod', label: 'client', ports: [{ port: 0, connections: 5 }], totalConnections: 540, connLabel: 'conn' } })
34
+ expect(client?.rows).toEqual([{ text: '540 conn', hot: false }])
35
+ expect(describeTrafficNode({ id: 'idle', type: 'traffic', data: { kind: 'Pod', label: 'idle' } })?.rows).toBeUndefined()
36
+
37
+ const pod = describeTrafficNode({ id: 'shop/api-7d9', type: 'traffic', data: { kind: 'Pod', label: 'api-7d9', workload: 'api', totalConnections: 3 } })
38
+ expect(pod?.rows).toEqual([{ text: 'api' }, { text: '3 conn', hot: false }])
39
+ })
40
+
41
+ it('washes an external card in its category color', () => {
42
+ expect(describeTrafficNode({ id: 'web', type: 'traffic', data: { kind: 'External', label: 'HTTPS', serviceCategory: 'web' } })?.tint).toEqual({ color: '#3B82F6', opacity: 0.2 })
43
+ expect(describeTrafficNode({ id: 'x', type: 'traffic', data: { kind: 'External', label: 'x' } })?.tint).toEqual({ color: '#EAB308', opacity: 0.1 })
44
+ expect(describeTrafficNode({ id: 'shop/web', type: 'traffic', data: { kind: 'Pod', label: 'web' } })?.tint).toBeUndefined()
45
+ })
46
+
47
+ it('draws both Internet kinds as Internet', () => {
48
+ expect(describeTrafficNode({ id: 'internet', type: 'traffic', data: { kind: 'Internet', label: 'internet' } })?.shape).toBe('internet')
49
+ expect(describeTrafficNode({ id: 'addon-internet', type: 'traffic', data: { kind: 'AddonInternet', label: 'Internet' } })?.shape).toBe('internet')
50
+ })
51
+ })
@@ -0,0 +1,114 @@
1
+ import { CircleQuestionMark, Database, Globe, Puzzle, Server } from 'lucide-react'
2
+ import { getTopologyIcon } from '@skyhook-io/k8s-ui'
3
+ import type { GraphBoxRow, GraphNodeMapper } from '@skyhook-io/k8s-ui/utils/graph-model'
4
+ import { formatVolume, isExternalKind, MAX_VISIBLE_PORTS } from './trafficFilters'
5
+
6
+ // Hex values of the Tailwind 500 shades the traffic nodes use for these categories.
7
+ const CATEGORY_COLORS: Record<string, string> = {
8
+ database: '#8B5CF6',
9
+ cloud: '#06B6D4',
10
+ monitoring: '#84CC16',
11
+ payment: '#10B981',
12
+ auth: '#F59E0B',
13
+ email: '#EC4899',
14
+ messaging: '#A855F7',
15
+ cache: '#F97316',
16
+ infra: '#64748B',
17
+ web: '#3B82F6',
18
+ }
19
+ const HOT = '#F97316'
20
+ const EXTERNAL = '#EAB308'
21
+ const ADDON = '#A855F7'
22
+ const HEALTHY = '#22C55E'
23
+ const ADDON_FILL = '#581C87'
24
+
25
+ function str(value: unknown): string | undefined {
26
+ return typeof value === 'string' && value !== '' ? value : undefined
27
+ }
28
+
29
+ function num(value: unknown): number | undefined {
30
+ return typeof value === 'number' && Number.isFinite(value) ? value : undefined
31
+ }
32
+
33
+ // The card's port rows (":80 230"), or its connection total when it lists no port.
34
+ function trafficRows(data: Record<string, unknown>, hot: boolean): GraphBoxRow[] {
35
+ const rateBased = data.connLabel === 'req/s'
36
+ const ports = (Array.isArray(data.ports) ? data.ports : []).flatMap((p: unknown) => {
37
+ if (typeof p !== 'object' || p === null || !('port' in p)) return []
38
+ const port = num(p.port)
39
+ const connections = ('connections' in p ? num(p.connections) : undefined) ?? 0
40
+ return port ? [{ port, connections }] : []
41
+ })
42
+ if (ports.length > 0) {
43
+ const rows: GraphBoxRow[] = ports.slice(0, MAX_VISIBLE_PORTS).map(({ port, connections }) => ({
44
+ text: `:${port}`,
45
+ code: true,
46
+ hot,
47
+ // No figure for a port with no measured traffic, as on the card.
48
+ ...(connections > 0 ? { value: `${formatVolume(connections, rateBased)}${rateBased ? '/s' : ''}` } : {}),
49
+ }))
50
+ if (ports.length > MAX_VISIBLE_PORTS) rows.push({ text: `+${ports.length - MAX_VISIBLE_PORTS} more`, muted: true })
51
+ return rows
52
+ }
53
+ const total = num(data.totalConnections)
54
+ return total && total > 0 ? [{ text: `${formatVolume(total, rateBased)} ${str(data.connLabel) ?? 'conn'}`, hot }] : []
55
+ }
56
+
57
+ function capitalize(s: string): string {
58
+ return s.charAt(0).toUpperCase() + s.slice(1)
59
+ }
60
+
61
+ /** Live Traffic nodes as export boxes. Namespaces are tints on the nodes; only the addon group is a container. */
62
+ export const describeTrafficNode: GraphNodeMapper = ({ type, data }) => {
63
+ if (type === 'addonGroup') {
64
+ return { shape: 'group', tone: 'addon', kind: 'Addon', name: 'Cluster Addons', icon: Puzzle }
65
+ }
66
+ if (type !== 'traffic') return null
67
+ const kind = str(data.kind) ?? 'Unknown'
68
+ const name = str(data.label) ?? ''
69
+ if (kind === 'Internet' || kind === 'AddonInternet') {
70
+ return { shape: 'internet', kind, name: 'Internet', accent: kind === 'AddonInternet' ? ADDON : '#0EA5E9', icon: Globe }
71
+ }
72
+ const namespace = str(data.namespace)
73
+ const category = str(data.serviceCategory)
74
+ const isAddonNode = data.isAddonNode === true
75
+ const external = isExternalKind(kind)
76
+ const workloadKind = str(data.workloadKind)
77
+ const shownKind = kind === 'Workload' && workloadKind ? workloadKind : kind
78
+ const namespaceColor = str(data.namespaceColor)
79
+ const fill = isAddonNode ? ADDON_FILL : !external && kind !== 'Addon' ? namespaceColor : undefined
80
+ const accent = data.isHotPath === true
81
+ ? HOT
82
+ : kind === 'Addon' || isAddonNode
83
+ ? ADDON
84
+ : external
85
+ ? (category && CATEGORY_COLORS[category]) || EXTERNAL
86
+ : HEALTHY
87
+ const icon = kind === 'Addon'
88
+ ? Puzzle
89
+ : kind.toLowerCase() === 'unknown'
90
+ ? CircleQuestionMark
91
+ : external
92
+ ? category === 'database' ? Database : Server
93
+ : getTopologyIcon(shownKind)
94
+ const detail = namespace ?? (category ? capitalize(category) : kind === 'Addon' ? 'Monitoring, logging, etc.' : undefined)
95
+ const workload = str(data.workload)
96
+ // The card lists the workload under the namespace when it differs from the endpoint name.
97
+ const rows = [...(workload && workload !== name ? [{ text: workload }] : []), ...trafficRows(data, data.isHotPath === true)]
98
+ // External cards are washed in their category color (yellow without one), as on screen.
99
+ const tint = external ? (category && CATEGORY_COLORS[category] ? { color: CATEGORY_COLORS[category], opacity: 0.2 } : { color: EXTERNAL, opacity: 0.1 }) : undefined
100
+ return {
101
+ shape: 'resource',
102
+ kind: shownKind,
103
+ name,
104
+ kindLabel: shownKind,
105
+ accent,
106
+ icon,
107
+ ...(detail ? { detail } : {}),
108
+ ...(category ? { category } : {}),
109
+ ...(fill ? { fill, textColor: '#FFFFFF' } : {}),
110
+ ...(tint ? { tint } : {}),
111
+ nameFirst: true,
112
+ ...(rows.length > 0 ? { rows } : {}),
113
+ }
114
+ }
@@ -876,3 +876,19 @@ export function emptyWarningHeadline(kind: TrafficWarningKind | undefined): stri
876
876
  default: return 'Unable to fetch traffic data'
877
877
  }
878
878
  }
879
+
880
+ export function formatConnections(count: number): string {
881
+ if (count >= 1_000_000_000) return `${(count / 1_000_000_000).toFixed(1)}B`
882
+ if (count >= 1_000_000) return `${(count / 1_000_000).toFixed(1)}M`
883
+ if (count >= 1_000) return `${(count / 1_000).toFixed(0)}K`
884
+ return count.toString()
885
+ }
886
+
887
+ // A volume in the source's own unit: a rate to two significant places for a
888
+ // rate-based source, a whole count otherwise.
889
+ export function formatVolume(volume: number, isRateBased: boolean): string {
890
+ return isRateBased ? formatRate(volume) : formatConnections(volume)
891
+ }
892
+
893
+ /** Ports a traffic card lists before "+N more". */
894
+ export const MAX_VISIBLE_PORTS = 4
@@ -1,5 +1,8 @@
1
+ // @vitest-environment jsdom
2
+ import { act } from 'react'
3
+ import { createRoot } from 'react-dom/client'
1
4
  import { renderToStaticMarkup } from 'react-dom/server'
2
- import { MemoryRouter } from 'react-router-dom'
5
+ import { MemoryRouter, useLocation } from 'react-router-dom'
3
6
  import { expect, it, vi } from 'vitest'
4
7
  import { useAPIResources } from '../../api/apiResources'
5
8
  import { useVulnerabilities, type VulnerableImage } from '../../api/vulnerabilities'
@@ -52,3 +55,29 @@ it('discloses missing scans alongside reported findings', () => {
52
55
  expect(html).toContain('View unscanned images in this workload')
53
56
  expect(html).not.toContain('Java4Shell')
54
57
  })
58
+
59
+ it('opens the tab on By image, the view its cards show', () => {
60
+ Object.assign(globalThis, { IS_REACT_ACT_ENVIRONMENT: true })
61
+ renderDrawer(true, { images: [image] })
62
+ let search = ''
63
+ function Probe() {
64
+ search = useLocation().search
65
+ return null
66
+ }
67
+ const container = document.createElement('div')
68
+ document.body.appendChild(container)
69
+ const root = createRoot(container)
70
+ act(() => root.render(
71
+ <MemoryRouter initialEntries={['/resources?namespaces=team']}>
72
+ <WorkloadVulnerabilitiesSection kind={workload.kind} namespace={workload.namespace} name={workload.name} />
73
+ <Probe />
74
+ </MemoryRouter>,
75
+ ))
76
+ act(() => Array.from(container.querySelectorAll('button')).find((b) => b.textContent?.includes('api:1'))!.click())
77
+ const params = new URLSearchParams(search)
78
+ expect(params.get('by')).toBe('image')
79
+ expect(params.get('workload')).toBe('Deployment/team/api')
80
+ expect(params.get('namespaces')).toBe('team')
81
+ act(() => root.unmount())
82
+ container.remove()
83
+ })
@@ -31,9 +31,10 @@ export function WorkloadVulnerabilitiesSection({ kind, namespace, name }: Props)
31
31
  const upgrades = fixData?.fixes ?? []
32
32
  const isThis = (w: { kind: string; namespace: string; name: string }) => w.kind === kind && w.namespace === namespace && w.name === name
33
33
  // The link keeps the page's namespace view, as every page link does: the
34
- // picker follows the URL, so a narrower one would change it.
34
+ // picker follows the URL, so a narrower one would change it. It opens By
35
+ // image, the view these cards show, unless it names another.
35
36
  const open = (more: Record<string, string> = {}) => {
36
- const search = new URLSearchParams({ workload: workloadParam({ kind, namespace, name }), ...more })
37
+ const search = new URLSearchParams({ workload: workloadParam({ kind, namespace, name }), by: 'image', ...more })
37
38
  const viewNamespaces = params.get('namespaces')
38
39
  if (viewNamespaces) search.set('namespaces', viewNamespaces)
39
40
  navigate({ pathname: '/checks/vulnerabilities', search: search.toString() })
@@ -1,7 +1,7 @@
1
1
  import { describe, expect, it } from 'vitest'
2
2
  import { ApiError } from '../../api/client'
3
3
  import { hasVulnerabilityReports, isKindUnknown, parseWorkloadParam, vulnerabilitiesPath, workloadParam } from '../../api/vulnerabilities'
4
- import { findingsCertainty, gapSentence, imageParts, workloadSummary } from './parts'
4
+ import { exposedCountTip, exposureGapSentence, exposureLookup, exposureUnknownIn, findingsCertainty, gapSentence, imageParts, routesTip, summaryNames } from './parts'
5
5
 
6
6
  describe('vulnerabilities helpers', () => {
7
7
  it('builds the request from filters', () => {
@@ -9,6 +9,8 @@ describe('vulnerabilities helpers', () => {
9
9
  .toBe('/vulnerabilities?view=cve&namespaces=shop%2Cprod&severity=critical%2Chigh&fixable=1&q=zlib')
10
10
  expect(vulnerabilitiesPath({ view: 'image', workload: { kind: 'Deployment', namespace: 'shop', name: 'web' } }))
11
11
  .toBe('/vulnerabilities?view=image&workloadKind=Deployment&workloadNamespace=shop&workloadName=web')
12
+ expect(vulnerabilitiesPath({ view: 'fix', exposed: true })).toBe('/vulnerabilities?view=fix&exposed=1')
13
+ expect(vulnerabilitiesPath({ view: 'fix', exposed: false })).toBe('/vulnerabilities?view=fix')
12
14
  })
13
15
 
14
16
  it('round-trips the workload filter and rejects anything else', () => {
@@ -65,8 +67,62 @@ describe('vulnerabilities helpers', () => {
65
67
  expect(imageParts('ghcr.io/acme/app:1@sha256:abc').name).toBe('app:1')
66
68
  })
67
69
 
70
+ const w = (name: string, container = 'app', namespace = 'shop') => ({ kind: 'Deployment', group: 'apps', namespace, name, container })
71
+ const route = { via: 'LoadBalancer', namespace: 'kube-system', name: 'traefik' }
72
+
68
73
  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')
74
+ const names = summaryNames([w('a'), w('a', 'sidecar'), w('b'), w('c'), w('d')])
75
+ expect(names.names.map((n) => n.name)).toEqual(['a', 'b'])
76
+ expect(names.rest).toBe(2)
77
+ })
78
+
79
+ it('lists exposed workloads first and marks only them, whatever the container', () => {
80
+ const exposure = exposureLookup([{ kind: 'Deployment', group: 'apps', namespace: 'shop', name: 'c', routes: [route] }])
81
+ const names = summaryNames([w('a'), w('b'), w('c', 'sidecar')], exposure)
82
+ expect(names.names.map((n) => [n.name, n.exposed?.routes])).toEqual([['c', [route]], ['a', undefined]])
83
+ expect(names.rest).toBe(1)
84
+ // Same name in another namespace is another workload.
85
+ expect(summaryNames([w('c', 'app', 'other')], exposure).names[0].exposed).toBeUndefined()
86
+ })
87
+
88
+ it('says how many of a count have a route, listing the first few', () => {
89
+ const exposed = ['a', 'b', 'c', 'd'].map((name) => ({ kind: 'Deployment', group: 'apps', namespace: 'shop', name, routes: [route] }))
90
+ const tip = exposedCountTip(exposed, 5, 9)
91
+ expect(tip.startsWith('5 of 9 workloads are exposed')).toBe(true)
92
+ expect(tip).toContain('a (LoadBalancer kube-system/traefik)')
93
+ expect(tip).not.toContain('d (')
94
+ expect(tip.endsWith('and 2 more')).toBe(true)
95
+ expect(exposedCountTip(exposed.slice(0, 1), 1, 5)).not.toContain('more')
96
+ // A list read names three routes per workload and counts the rest.
97
+ const capped = [{ ...exposed[0], routes: [route, route, route], routesTotal: 200 }]
98
+ expect(exposedCountTip(capped, 1, 5)).toContain('and 197 more)')
99
+ expect(routesTip(capped[0].routes, 200)).toMatch(/and 197 more$/)
100
+ })
101
+
102
+ it('reads a workload namespace as unknown only where an exposure gap covers it', () => {
103
+ const ingress = { count: 1, names: [{ kind: 'Ingress', group: 'networking.k8s.io' }] }
104
+ const listed = { code: 'user_forbidden', kinds: ingress, namespaces: { count: 2, names: ['shop', 'prod'] } }
105
+ expect(exposureUnknownIn(undefined, 'shop')).toBe(false)
106
+ expect(exposureUnknownIn([listed], 'shop')).toBe(true)
107
+ expect(exposureUnknownIn([listed], 'dev')).toBe(false)
108
+ expect(exposureUnknownIn([{ ...listed, namespaces: { extent: 'all' } }], 'dev')).toBe(true)
109
+ expect(exposureUnknownIn([{ ...listed, namespaces: { extent: 'unknown' } }], 'dev')).toBe(true)
110
+ // A capped list names 64 of 65: the 65th may be in it.
111
+ expect(exposureUnknownIn([{ ...listed, namespaces: { count: 65, names: Array.from({ length: 64 }, (_, i) => `ns-${i}`) } }], 'ns-64')).toBe(true)
112
+ })
113
+
114
+ it('names the route kinds and namespaces exposure could not be read in', () => {
115
+ const ingress = { count: 1, names: [{ kind: 'Ingress', group: 'networking.k8s.io' }] }
116
+ expect(exposureGapSentence(undefined)).toBeNull()
117
+ expect(exposureGapSentence([])).toBeNull()
118
+ const two = exposureGapSentence([{ code: 'user_forbidden', kinds: ingress, namespaces: { count: 2, names: ['a', 'b'] } }])
119
+ expect(two).toContain('Ingresses')
120
+ expect(two).toContain('2 namespaces')
121
+ expect(exposureGapSentence([{ code: 'radar_kind_not_collected', kinds: { count: 2, names: [{ kind: 'HTTPRoute' }, { kind: 'GRPCRoute' }] }, namespaces: { extent: 'all' } }]))
122
+ .toContain("couldn't read HTTPRoutes and GRPCRoutes, so")
123
+ const hidden = exposureGapSentence([{ code: 'user_forbidden', kinds: { count: 1, names: [{ kind: 'HTTPRoute' }] }, namespaces: { count: 1, names: ['shop'] } }])
124
+ expect(hidden).not.toContain("Radar couldn't read")
125
+ expect(hidden).toContain('HTTPRoutes')
126
+ expect(hidden).toContain('1 namespace')
71
127
  })
72
128
  })
@@ -1,11 +1,15 @@
1
1
  import { clsx } from 'clsx'
2
+ import { Globe } from 'lucide-react'
3
+ import type { LucideIcon } from 'lucide-react'
2
4
  import { WithTooltip } from '../ui/Tooltip'
3
5
  import { CertaintyGlyph, gapReasonText, VULN_SEVERITY_BADGE, VULN_SEVERITY_BAR, VULN_SEVERITY_TEXT, type Certainty } from '@skyhook-io/k8s-ui'
4
6
  import { SEVERITY_TEXT } from '@skyhook-io/k8s-ui/utils/badge-colors'
5
7
  import type {
8
+ ExposedWorkload,
6
9
  VulnerabilitiesResponse,
7
10
  VulnerabilityCounts,
8
11
  VulnerabilityGap,
12
+ VulnerabilityRoute,
9
13
  VulnerabilitySeverity,
10
14
  VulnerabilityWorkloadRef,
11
15
  } from '../../api/vulnerabilities'
@@ -138,11 +142,181 @@ export function ecosystemLabel(packageType?: string): string | undefined {
138
142
  return ECOSYSTEMS[packageType.toLowerCase()] ?? packageType
139
143
  }
140
144
 
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
145
+ type WorkloadKey = { kind: string; namespace: string; name: string }
146
+
147
+ /** A row's exposed workloads by kind/namespace/name, so any container of one matches. */
148
+ export type ExposureLookup = Map<string, ExposedWorkload>
149
+
150
+ const exposureKey = (w: WorkloadKey) => `${w.kind}/${w.namespace}/${w.name}`
151
+
152
+ export function exposureLookup(exposed: ExposedWorkload[] | undefined): ExposureLookup {
153
+ return new Map((exposed ?? []).filter((w) => w.routes.length > 0).map((w) => [exposureKey(w), w]))
154
+ }
155
+
156
+ export function routesFor(exposure: ExposureLookup | undefined, w: WorkloadKey): ExposedWorkload | undefined {
157
+ return exposure?.get(exposureKey(w))
158
+ }
159
+
160
+ export function routeText(r: VulnerabilityRoute): string {
161
+ return `${r.via} ${r.namespace}/${r.name}`
162
+ }
163
+
164
+ /** "A, B, C and 197 more": the routes listed, and how many the list leaves out. */
165
+ export function routeListText(routes: VulnerabilityRoute[], total = routes.length): string {
166
+ const more = total - routes.length
167
+ return `${routes.map(routeText).join(', ')}${more > 0 ? ` and ${more} more` : ''}`
168
+ }
169
+
170
+ export function routesTip(routes: VulnerabilityRoute[], total = routes.length): string {
171
+ return `Exposed via ${routeListText(routes, total)}`
172
+ }
173
+
174
+ /**
175
+ * The words and mark for exposure, in one place. "Exposed" is the term
176
+ * container security tools use for a workload reachable from outside the
177
+ * cluster (Sysdig: "publicly or ingress exposed"); it doesn't claim the
178
+ * internet, which tools keep for "internet-facing"; the tooltips say it may
179
+ * be internal only. The globe stays as the mark people recognise for exposure.
180
+ */
181
+ export const EXPOSURE = {
182
+ icon: Globe as LucideIcon,
183
+ chip: 'Exposed',
184
+ column: 'Exposed via',
185
+ unknown: 'Exposure unknown',
186
+ chipTip: "Only rows affecting a workload reachable from outside the cluster: a LoadBalancer or NodePort Service, or an Ingress or Gateway API route with an address. It may be internal only; firewalls, security groups and NetworkPolicies aren't checked. Not counted yet: hostNetwork and hostPort Pods, service meshes and custom routers.",
187
+ unknownTip: "Radar couldn't read every route kind that could reach this workload, so it may be exposed.",
188
+ }
189
+
190
+ /** The mark on a workload with a route from outside the cluster; absence gets none. */
191
+ export function ExposedMark({ exposed, tip }: { exposed?: ExposedWorkload; tip?: string }) {
192
+ const text = tip ?? (exposed ? routesTip(exposed.routes, exposed.routesTotal) : undefined)
193
+ const Icon = EXPOSURE.icon
194
+ return (
195
+ <WithTooltip tip={text}>
196
+ <Icon className="h-3 w-3 shrink-0 self-center text-theme-text-secondary" role="img" aria-label={text} />
197
+ </WithTooltip>
198
+ )
199
+ }
200
+
201
+ /**
202
+ * Up to `shown` distinct workload names for a collapsed row, exposed ones
203
+ * first, and how many more names there are.
204
+ */
205
+ export function summaryNames(workloads: VulnerabilityWorkloadRef[], exposure?: ExposureLookup, shown = 2): { names: { name: string; exposed?: ExposedWorkload }[]; rest: number } {
206
+ const byName = new Map<string, ExposedWorkload | undefined>()
207
+ for (const w of workloads) {
208
+ const exposed = routesFor(exposure, w)
209
+ if (!byName.has(w.name) || (exposed && !byName.get(w.name))) byName.set(w.name, exposed)
210
+ }
211
+ const all = [...byName].map(([name, exposed]) => ({ name, exposed }))
212
+ const ordered = [...all.filter((n) => n.exposed), ...all.filter((n) => !n.exposed)]
213
+ return { names: ordered.slice(0, shown), rest: Math.max(0, ordered.length - shown) }
214
+ }
215
+
216
+ /** "checkout, worker +4" for a list of workloads, each named once, exposed ones first with the mark. */
217
+ export function WorkloadSummary({ workloads, exposure, suffix }: { workloads: VulnerabilityWorkloadRef[]; exposure?: ExposureLookup; suffix?: string }) {
218
+ const { names, rest } = summaryNames(workloads, exposure)
219
+ return (
220
+ <span className="flex min-w-0 items-baseline text-theme-text-secondary">
221
+ <span className="truncate">
222
+ {names.map((n, i) => (
223
+ <span key={n.name}>
224
+ {i > 0 && ', '}
225
+ {n.exposed && <span className="mr-1 inline-flex align-[-1px]"><ExposedMark exposed={n.exposed} /></span>}
226
+ {n.name}
227
+ </span>
228
+ ))}
229
+ {rest > 0 && ` +${rest}`}
230
+ {suffix}
231
+ </span>
232
+ </span>
233
+ )
234
+ }
235
+
236
+ /**
237
+ * The tooltip for a count of workloads that lists no names: how many are
238
+ * externally exposed, and the first few with their routes.
239
+ */
240
+ export function exposedCountTip(exposed: ExposedWorkload[], exposedTotal: number, workloads?: number, listed = 3): string {
241
+ const shown = exposed.slice(0, listed).map((w) => `${w.name} (${routeListText(w.routes, w.routesTotal)})`)
242
+ const more = exposedTotal - shown.length
243
+ // By image the row counts containers, which can't be set against workloads.
244
+ const lead = workloads === undefined
245
+ ? `${exposedTotal} ${exposedTotal === 1 ? 'workload running it is' : 'workloads running it are'}`
246
+ : `${exposedTotal} of ${workloads} ${workloads === 1 ? 'workload is' : 'workloads are'}`
247
+ return `${lead} exposed: ${shown.join(', ')}${more > 0 ? ` and ${more} more` : ''}`
248
+ }
249
+
250
+ /**
251
+ * "3 exposed" with the mark, under a row's workload count ("1 exposed
252
+ * workload" where the row counts containers);
253
+ * "Exposure unknown" when none is known exposed but some may be; nothing
254
+ * otherwise.
255
+ */
256
+ export function ExposedCount({ exposed, total, workloads, unknown }: { exposed?: ExposedWorkload[]; total?: number; workloads?: number; unknown?: boolean }) {
257
+ const Icon = EXPOSURE.icon
258
+ if (!total) {
259
+ if (!unknown) return null
260
+ return (
261
+ <WithTooltip tip={EXPOSURE.unknownTip}>
262
+ <span className="whitespace-nowrap text-xs text-theme-text-tertiary">{EXPOSURE.unknown}</span>
263
+ </WithTooltip>
264
+ )
265
+ }
266
+ const tip = exposedCountTip(exposed ?? [], total, workloads)
267
+ // Under a workload count the total is already on screen, so the line
268
+ // says only how many are exposed; the tooltip says "N of M".
269
+ const text = workloads === undefined ? `${total} exposed ${total === 1 ? 'workload' : 'workloads'}` : `${total} exposed`
270
+ return (
271
+ <WithTooltip tip={tip}>
272
+ <span className="inline-flex items-center gap-1 whitespace-nowrap text-xs text-theme-text-secondary" aria-label={tip}>
273
+ <Icon className="h-3 w-3 shrink-0" aria-hidden />
274
+ {text}
275
+ </span>
276
+ </WithTooltip>
277
+ )
278
+ }
279
+
280
+ /** Whether an exposure gap covers this namespace, so its routes are unknown. */
281
+ export function exposureUnknownIn(gaps: VulnerabilityGap[] | undefined, namespace: string): boolean {
282
+ return (gaps ?? []).some((g) => {
283
+ const ns = g.namespaces
284
+ if (!ns) return true
285
+ if (ns.extent !== undefined) return true
286
+ // Past the name cap the set only counts: any namespace may be in it.
287
+ return (ns.names ?? []).includes(namespace) || (ns.names ?? []).length < ns.count
288
+ })
289
+ }
290
+
291
+ const pluralKind = (kind: string) => (/(s|x|ch|sh)$/.test(kind) ? `${kind}es` : `${kind}s`)
292
+
293
+ function listWords(words: string[]): string {
294
+ return words.length <= 1 ? words.join('') : `${words.slice(0, -1).join(', ')} and ${words[words.length - 1]}`
295
+ }
296
+
297
+ /** The sentence for route kinds Radar couldn't read, or null when none. */
298
+ export function exposureGapSentence(gaps: VulnerabilityGap[] | undefined): string | null {
299
+ if (!gaps || gaps.length === 0) return null
300
+ const describe = (list: VulnerabilityGap[]) => listWords([...new Set(list.map((g) => {
301
+ const kinds = g.kinds?.names?.length ? listWords(g.kinds.names.map((k) => pluralKind(k.kind))) : 'routes'
302
+ const ns = g.namespaces
303
+ let where = ''
304
+ if (ns?.extent === 'unknown') where = ' in some namespaces'
305
+ else if (ns && ns.extent === undefined) where = ` in ${ns.count} ${ns.count === 1 ? 'namespace' : 'namespaces'}`
306
+ return `${kinds}${where}`
307
+ }))])
308
+ // user_forbidden: route kinds the caller can't read for these workloads' namespaces.
309
+ const hidden = gaps.filter((g) => g.code === 'user_forbidden')
310
+ const unread = gaps.filter((g) => g.code !== 'user_forbidden')
311
+ const sentences: string[] = []
312
+ if (unread.length) sentences.push(`Radar couldn't read ${describe(unread)}, so some workloads may be exposed without the mark.`)
313
+ if (hidden.length) {
314
+ const kinds = listWords([...new Set(hidden.flatMap((g) => (g.kinds?.names ?? []).map((k) => pluralKind(k.kind))))])
315
+ const namespaces = new Set(hidden.flatMap((g) => g.namespaces?.names ?? []))
316
+ const where = namespaces.size ? `workloads in ${namespaces.size} ${namespaces.size === 1 ? 'namespace' : 'namespaces'}` : 'these workloads'
317
+ sentences.push(`Your access doesn't cover all ${kinds || 'routes'} that could reach ${where}, so those without a route you can see read Exposure unknown.`)
318
+ }
319
+ return sentences.join(' ')
146
320
  }
147
321
 
148
322
  export function distinctNamespaces(workloads: VulnerabilityWorkloadRef[]): number {
@@ -289,3 +463,23 @@ export function FindingTotal({ value, certainty, className }: { value: number; c
289
463
  export function installedLabel(from: string[]): string {
290
464
  return from.length > 2 ? `${from.length} versions` : from.join(', ')
291
465
  }
466
+
467
+ const UNCHECKED_NAMES: Record<string, string> = {
468
+ 'networking.istio.io/VirtualService': 'Istio VirtualServices',
469
+ 'networking.istio.io/Gateway': 'Istio Gateways',
470
+ 'traefik.io/IngressRoute': 'Traefik IngressRoutes',
471
+ 'traefik.containo.us/IngressRoute': 'Traefik IngressRoutes',
472
+ 'traefik.io/IngressRouteTCP': 'Traefik IngressRouteTCPs',
473
+ 'traefik.containo.us/IngressRouteTCP': 'Traefik IngressRouteTCPs',
474
+ 'traefik.io/IngressRouteUDP': 'Traefik IngressRouteUDPs',
475
+ 'traefik.containo.us/IngressRouteUDP': 'Traefik IngressRouteUDPs',
476
+ 'projectcontour.io/HTTPProxy': 'Contour HTTPProxies',
477
+ 'serving.knative.dev/Service': 'Knative Services',
478
+ }
479
+
480
+ /** The sentence for route kinds this cluster serves that Radar doesn't follow, or null. */
481
+ export function uncheckedRoutesSentence(unchecked: { kind: string; group?: string }[] | undefined): string | null {
482
+ if (!unchecked || unchecked.length === 0) return null
483
+ const names = [...new Set(unchecked.map((k) => UNCHECKED_NAMES[`${k.group ?? ''}/${k.kind}`] ?? pluralKind(k.kind)))]
484
+ return `This cluster has ${listWords(names)}, which Radar doesn't follow yet, so workloads they route to aren't marked.`
485
+ }
@@ -0,0 +1,34 @@
1
+ // @vitest-environment jsdom
2
+ import { act } from 'react'
3
+ import { createRoot } from 'react-dom/client'
4
+ import { afterEach, expect, it, vi } from 'vitest'
5
+ import { WorkloadRevisionsButton } from './WorkloadRevisionsButton'
6
+ import { useWorkloadRevisions } from '../../api/client'
7
+
8
+ vi.mock('../../api/client', () => ({ useWorkloadRevisions: vi.fn() }))
9
+ vi.stubGlobal('IS_REACT_ACT_ENVIRONMENT', true)
10
+ vi.stubGlobal('ResizeObserver', class { observe() {} disconnect() {} })
11
+ afterEach(() => { document.body.replaceChildren(); vi.clearAllMocks() })
12
+
13
+ it('reads only the chosen workload, compares retained templates, and has no mutation actions', async () => {
14
+ const data = [
15
+ { number: 8, image: 'worker:v1', isCurrent: true, replicas: 2, readyReplicas: 0, matchesDesired: true, template: 'path: /healthz' },
16
+ { number: 7, image: 'worker:v1', isCurrent: false, replicas: 2, readyReplicas: 2, template: 'path: /ready' },
17
+ ]
18
+ vi.mocked(useWorkloadRevisions).mockReturnValue({ data, isError: false, isLoading: false, error: null } as ReturnType<typeof useWorkloadRevisions>)
19
+ const container = document.createElement('div')
20
+ document.body.append(container)
21
+ const root = createRoot(container)
22
+ await act(() => root.render(<WorkloadRevisionsButton kind="Deployment" group="apps" namespace="prod" name="worker" />))
23
+ expect(useWorkloadRevisions).not.toHaveBeenCalled()
24
+ await act(() => container.querySelector('button')!.click())
25
+ expect(useWorkloadRevisions).toHaveBeenCalledWith('deployments', 'prod', 'worker')
26
+ const dialog = document.querySelector('[role=dialog]')!
27
+ expect(dialog.textContent).toContain('0/2 ready')
28
+ expect(dialog.textContent).toContain('2/2 ready')
29
+ expect(dialog.textContent).not.toContain('Rollback')
30
+ await act(() => Array.from(dialog.querySelectorAll('button')).find(b => b.textContent === 'Diff')!.click())
31
+ expect(dialog.textContent).toContain('/healthz')
32
+ expect(dialog.textContent).toContain('/ready')
33
+ await act(() => root.unmount())
34
+ })