@skyhook-io/radar-app 1.21.3 → 1.21.4

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.
@@ -19,7 +19,7 @@ import type { ELK } from 'elkjs/lib/elk.bundled.js'
19
19
  import type { AggregatedFlow } from '../../types'
20
20
  import { clsx } from 'clsx'
21
21
  import { X, ArrowRight, Globe, Server, Activity, Puzzle, Crosshair } from 'lucide-react'
22
- import { MiddleEllipsis, PaneLoader } from '@skyhook-io/k8s-ui'
22
+ import { GraphExportButton, MiddleEllipsis, PaneLoader } from '@skyhook-io/k8s-ui'
23
23
  import { isClusterAddon, type AddonMode } from './TrafficView'
24
24
  import { SEVERITY_BADGE, SEVERITY_DOT, SEVERITY_TEXT } from '@skyhook-io/k8s-ui/utils/badge-colors'
25
25
  import { getNamespaceColor } from '../../utils/traffic-colors'
@@ -87,6 +87,8 @@ interface TrafficGraphProps {
87
87
  /** Seconds the byte figures cover, so an edge measured only in bytes can be
88
88
  * labelled with its throughput. */
89
89
  windowSeconds: number
90
+ /** Saves an exported image instead of a browser download (desktop app). */
91
+ onDownloadBlob?: (blob: Blob, filename: string) => void
90
92
  }
91
93
 
92
94
  // Phase 2.1: Calculate edge width based on connection count (log scale)
@@ -372,7 +374,8 @@ export function TrafficNode({ data }: { data: TrafficNodeData }) {
372
374
  // Legend component
373
375
  function TrafficLegend() {
374
376
  return (
375
- <div className="absolute bottom-2 left-2 bg-theme-surface border border-theme-border rounded-lg p-2.5 text-xs z-10 shadow-lg max-w-xs">
377
+ // Clears the graph controls, which sit in the same corner.
378
+ <div className="absolute bottom-2 left-14 bg-theme-surface border border-theme-border rounded-lg p-2.5 text-xs z-10 shadow-lg max-w-xs">
376
379
  <div className="font-medium text-theme-text-primary mb-2">Legend</div>
377
380
  <div className="space-y-1.5">
378
381
  <div className="flex items-center gap-2">
@@ -1165,7 +1168,7 @@ function trafficEdgeId(sourceId: string, destId: string, flow: AggregatedFlow):
1165
1168
  return `${sourceId}->${destId}:${flow.port}${flow.directionUnknown ? ':unoriented' : ''}`
1166
1169
  }
1167
1170
 
1168
- export function TrafficGraph({ flows, hotPathThreshold = 0, showNamespaceGroups = false, serviceCategories, addonMode = 'show', trafficSource = '', selection: viewSelection, onSelectionChange, onFocus, focusedId, onLayoutUnavailable, windowSeconds }: TrafficGraphProps) {
1171
+ export function TrafficGraph({ flows, hotPathThreshold = 0, showNamespaceGroups = false, serviceCategories, addonMode = 'show', trafficSource = '', selection: viewSelection, onSelectionChange, onFocus, focusedId, onLayoutUnavailable, windowSeconds, onDownloadBlob }: TrafficGraphProps) {
1169
1172
  // Beyla is rate-based too: its Connections field carries requests per second,
1170
1173
  // not a connection count, so it needs the same label Istio gets.
1171
1174
  const isRateBased = isRateBasedSource(trafficSource)
@@ -1815,7 +1818,9 @@ export function TrafficGraph({ flows, hotPathThreshold = 0, showNamespaceGroups
1815
1818
  nodesConnectable={false}
1816
1819
  >
1817
1820
  <Background />
1818
- <Controls />
1821
+ <Controls>
1822
+ <GraphExportButton defaultFilename="traffic" title="Export traffic" onDownloadBlob={onDownloadBlob} />
1823
+ </Controls>
1819
1824
  <FitViewOnChange shouldFitViewRef={shouldFitViewRef} layoutedNodes={layoutedNodes} />
1820
1825
  </ReactFlow>
1821
1826
 
@@ -9,6 +9,7 @@ import type { UseTrafficRecordsOptions } from '../../api/traffic'
9
9
 
10
10
  Object.assign(globalThis, { IS_REACT_ACT_ENVIRONMENT: true })
11
11
 
12
+ vi.mock('../../hooks/useDesktopDownload', () => ({ useDesktopBlobDownload: () => undefined }))
12
13
  vi.mock('elkjs/lib/elk.bundled.js', () => {
13
14
  throw new Error('Failed to fetch dynamically imported module')
14
15
  })
@@ -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
  )}
@@ -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,57 @@
1
+ // @vitest-environment jsdom
2
+ import { act } from 'react'
3
+ import { createRoot, type Root } from 'react-dom/client'
4
+ import { afterEach, beforeEach, expect, it, vi } from 'vitest'
5
+ import { ToastProvider } from '../components/ui/Toast'
6
+
7
+ const { isDesktopApp, desktopSaveBlob } = vi.hoisted(() => ({ isDesktopApp: vi.fn(), desktopSaveBlob: vi.fn() }))
8
+ vi.mock('../utils/desktop-download', () => ({ isDesktopApp, desktopSaveBlob, desktopSaveFile: vi.fn() }))
9
+ vi.mock('../utils/desktop-open-folder', () => ({ openFile: vi.fn(), openFolder: vi.fn() }))
10
+
11
+ import { useDesktopBlobDownload } from './useDesktopDownload'
12
+
13
+ Object.assign(globalThis, { IS_REACT_ACT_ENVIRONMENT: true })
14
+
15
+ let root: Root
16
+ let element: HTMLDivElement
17
+ type Save = ReturnType<typeof useDesktopBlobDownload>
18
+ const seen = vi.fn<(save: Save) => void>()
19
+ function Probe() {
20
+ seen(useDesktopBlobDownload())
21
+ return null
22
+ }
23
+ const latest = (): Save => seen.mock.calls.at(-1)![0]
24
+
25
+ beforeEach(() => {
26
+ element = document.createElement('div')
27
+ document.body.appendChild(element)
28
+ root = createRoot(element)
29
+ desktopSaveBlob.mockReset()
30
+ seen.mockReset()
31
+ })
32
+ afterEach(async () => {
33
+ await act(async () => root.unmount())
34
+ element.remove()
35
+ })
36
+
37
+ async function renderProbe() {
38
+ await act(async () => root.render(<ToastProvider><Probe /></ToastProvider>))
39
+ }
40
+
41
+ it('leaves the browser download in place outside the desktop app', async () => {
42
+ isDesktopApp.mockResolvedValue(false)
43
+ await renderProbe()
44
+ expect(latest()).toBeUndefined()
45
+ })
46
+
47
+ it('saves the blob through the native dialog in the desktop app', async () => {
48
+ isDesktopApp.mockResolvedValue(true)
49
+ desktopSaveBlob.mockResolvedValue('/tmp/topology.png')
50
+ await renderProbe()
51
+ const blob = new Blob(['img'], { type: 'image/png' })
52
+
53
+ await act(async () => latest()!(blob, 'topology.png'))
54
+
55
+ expect(desktopSaveBlob).toHaveBeenCalledWith(blob, 'topology.png')
56
+ expect(document.body.textContent).toContain('File saved')
57
+ })
@@ -1,15 +1,12 @@
1
1
  import { createElement, useState, useEffect, useCallback } from 'react'
2
2
  import { FolderOpen } from 'lucide-react'
3
3
  import { useToast } from '../components/ui/Toast'
4
- import { isDesktopApp, desktopSaveFile } from '../utils/desktop-download'
4
+ import { isDesktopApp, desktopSaveFile, desktopSaveBlob } from '../utils/desktop-download'
5
5
  import { openFile, openFolder } from '../utils/desktop-open-folder'
6
6
 
7
- /**
8
- * Returns a download override function when running in the desktop app,
9
- * or undefined when running in a browser (so the default blob URL approach is used).
10
- * The returned function shows toast notifications for success/failure and silently handles user cancellation.
11
- */
12
- export function useDesktopDownload(): ((content: string, mime: string, filename: string) => void) | undefined {
7
+ // Tracks whether this is the desktop app and reports a native save's outcome as a toast.
8
+ // User cancellation is silent.
9
+ function useDesktopSave(): { isDesktop: boolean; report: (save: Promise<string>) => void } {
13
10
  const [isDesktop, setIsDesktop] = useState(false)
14
11
  const { showSuccess, showError } = useToast()
15
12
 
@@ -17,8 +14,8 @@ export function useDesktopDownload(): ((content: string, mime: string, filename:
17
14
  isDesktopApp().then(setIsDesktop)
18
15
  }, [])
19
16
 
20
- const download = useCallback((content: string, _mime: string, filename: string) => {
21
- desktopSaveFile(content, filename)
17
+ const report = useCallback((save: Promise<string>) => {
18
+ save
22
19
  .then((path) => showSuccess(
23
20
  'File saved',
24
21
  path,
@@ -36,6 +33,31 @@ export function useDesktopDownload(): ((content: string, mime: string, filename:
36
33
  })
37
34
  }, [showSuccess, showError])
38
35
 
36
+ return { isDesktop, report }
37
+ }
38
+
39
+ /**
40
+ * Returns a download override function when running in the desktop app,
41
+ * or undefined when running in a browser (so the default blob URL approach is used).
42
+ * The returned function shows toast notifications for success/failure and silently handles user cancellation.
43
+ */
44
+ export function useDesktopDownload(): ((content: string, mime: string, filename: string) => void) | undefined {
45
+ const { isDesktop, report } = useDesktopSave()
46
+ const download = useCallback((content: string, _mime: string, filename: string) => {
47
+ report(desktopSaveFile(content, filename))
48
+ }, [report])
49
+
50
+ if (!isDesktop) return undefined
51
+ return download
52
+ }
53
+
54
+ /** Blob variant of useDesktopDownload, for binary files such as exported images. */
55
+ export function useDesktopBlobDownload(): ((blob: Blob, filename: string) => void) | undefined {
56
+ const { isDesktop, report } = useDesktopSave()
57
+ const download = useCallback((blob: Blob, filename: string) => {
58
+ report(desktopSaveBlob(blob, filename))
59
+ }, [report])
60
+
39
61
  if (!isDesktop) return undefined
40
62
  return download
41
63
  }