@skyhook-io/radar-app 1.21.2 → 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.
Files changed (103) hide show
  1. package/README.md +11 -0
  2. package/package.json +2 -2
  3. package/src/App.tsx +53 -28
  4. package/src/api/actions.test.ts +11 -0
  5. package/src/api/actions.ts +5 -0
  6. package/src/api/apiResources.navigation.test.tsx +58 -0
  7. package/src/api/apiResources.ts +22 -16
  8. package/src/api/client.diagnostics.test.ts +52 -0
  9. package/src/api/client.triggerCronJob.test.tsx +49 -0
  10. package/src/api/client.ts +140 -120
  11. package/src/api/connectionBinding.test.tsx +82 -0
  12. package/src/api/connectionBinding.ts +52 -0
  13. package/src/api/contextSwitch.test.ts +11 -0
  14. package/src/api/contextSwitch.ts +58 -0
  15. package/src/api/radarFeatures.ts +6 -0
  16. package/src/api/vulnerabilities.export.test.ts +44 -0
  17. package/src/api/vulnerabilities.ts +73 -4
  18. package/src/components/ConnectionErrorView.tsx +13 -0
  19. package/src/components/ContextSwitchActions.tsx +43 -0
  20. package/src/components/ContextSwitcher.tsx +13 -6
  21. package/src/components/SwitchAwareConnectionError.tsx +2 -2
  22. package/src/components/audit/VulnerabilitiesView.test.tsx +177 -0
  23. package/src/components/audit/VulnerabilitiesView.tsx +197 -48
  24. package/src/components/cost/ApplicationCostTab.test.ts +16 -0
  25. package/src/components/cost/ApplicationCostTab.tsx +41 -9
  26. package/src/components/cost/CostTrendChart.tsx +25 -2
  27. package/src/components/cost/CostTrendWithheld.render.test.tsx +105 -0
  28. package/src/components/cost/CostView.tsx +10 -2
  29. package/src/components/cost/CostViewTabs.test.tsx +18 -0
  30. package/src/components/cost/CostViewTabs.tsx +14 -22
  31. package/src/components/cost/WorkloadCostTab.test.ts +15 -0
  32. package/src/components/cost/WorkloadCostTab.tsx +42 -8
  33. package/src/components/cost/source.test.ts +16 -1
  34. package/src/components/cost/source.ts +34 -0
  35. package/src/components/diagnose/investigationEvidence/adapters/diagnose.test.ts +35 -0
  36. package/src/components/diagnose/investigationEvidence/adapters/diagnose.ts +16 -1
  37. package/src/components/dock/NodeTerminalTab.test.tsx +4 -2
  38. package/src/components/dock/NodeTerminalTab.tsx +8 -8
  39. package/src/components/dock/TerminalTab.test.tsx +12 -1
  40. package/src/components/dock/TerminalTab.tsx +6 -3
  41. package/src/components/home/CostCard.test.tsx +49 -0
  42. package/src/components/home/CostCard.tsx +98 -63
  43. package/src/components/home/mcpToolCatalog.ts +1 -0
  44. package/src/components/resource/DatadogRightsizingPanel.test.tsx +118 -0
  45. package/src/components/resource/DatadogRightsizingPanel.tsx +68 -0
  46. package/src/components/resource/DatadogWorkloadCharts.tsx +149 -0
  47. package/src/components/resource/HPACharts.render.test.tsx +42 -0
  48. package/src/components/resource/HPACharts.tsx +34 -1
  49. package/src/components/resource/PrometheusChartsGrid.render.test.tsx +126 -3
  50. package/src/components/resource/PrometheusChartsGrid.tsx +58 -25
  51. package/src/components/resource/RestartChart.render.test.tsx +72 -0
  52. package/src/components/resource/RestartChart.tsx +31 -3
  53. package/src/components/resource/RightsizingPanel.access.test.tsx +24 -0
  54. package/src/components/resource/RightsizingStrip.render.test.tsx +44 -0
  55. package/src/components/resource/RightsizingStrip.test.ts +1 -188
  56. package/src/components/resource/RightsizingStrip.tsx +27 -300
  57. package/src/components/resource/WorkloadMetricsSection.render.test.tsx +22 -0
  58. package/src/components/resource/WorkloadMetricsSection.tsx +14 -4
  59. package/src/components/resource/nameMatchedScope.ts +39 -0
  60. package/src/components/resources/pod-file-upload.ts +3 -0
  61. package/src/components/resources/renderers/CAPIClusterRenderer.tsx +5 -2
  62. package/src/components/resources/renderers/LonghornVolumeRenderer.test.tsx +104 -0
  63. package/src/components/resources/renderers/LonghornVolumeRenderer.tsx +31 -0
  64. package/src/components/rightsizing/RightsizingScanLink.tsx +22 -0
  65. package/src/components/rightsizing/RightsizingScanView.tsx +65 -528
  66. package/src/components/rightsizing/model.test.ts +20 -9
  67. package/src/components/rightsizing/model.ts +17 -176
  68. package/src/components/rightsizing/notices.test.tsx +30 -29
  69. package/src/components/traffic/TrafficGraph.export.test.tsx +57 -0
  70. package/src/components/traffic/TrafficGraph.tsx +9 -4
  71. package/src/components/traffic/TrafficView.layoutUnavailable.test.tsx +1 -0
  72. package/src/components/traffic/TrafficView.tsx +17 -2
  73. package/src/components/ui/DiagnosticsOverlay.test.ts +3 -2
  74. package/src/components/ui/DiagnosticsOverlay.tsx +23 -13
  75. package/src/components/ui/command-items.ts +3 -4
  76. package/src/components/useContextSwitchFlow.test.tsx +9 -0
  77. package/src/components/useContextSwitchFlow.tsx +43 -5
  78. package/src/components/vulnerabilities/WorkloadVulnerabilitiesSection.test.tsx +30 -1
  79. package/src/components/vulnerabilities/WorkloadVulnerabilitiesSection.tsx +3 -2
  80. package/src/components/vulnerabilities/parts.test.ts +59 -3
  81. package/src/components/vulnerabilities/parts.tsx +199 -5
  82. package/src/components/workload/WorkloadRightsizingSource.test.tsx +83 -0
  83. package/src/components/workload/WorkloadView.test.ts +22 -1
  84. package/src/components/workload/WorkloadView.tsx +57 -16
  85. package/src/context/ConnectionContext.test.ts +1 -0
  86. package/src/context/ConnectionContext.tsx +58 -15
  87. package/src/context/ConnectionProvider.connectionId.test.tsx +92 -0
  88. package/src/context/ConnectionProvider.retry.test.tsx +174 -1
  89. package/src/context/ContextSwitchContext.tsx +15 -1
  90. package/src/context/NavCustomization.tsx +6 -3
  91. package/src/hooks/useDesktopDownload.test.tsx +57 -0
  92. package/src/hooks/useDesktopDownload.ts +31 -9
  93. package/src/hooks/useEventSource.test.tsx +85 -0
  94. package/src/hooks/useEventSource.ts +43 -16
  95. package/src/hooks/useResetViewsOnContextChange.test.tsx +34 -0
  96. package/src/hooks/useResetViewsOnContextChange.ts +27 -0
  97. package/src/index.ts +3 -0
  98. package/src/integrations/resourceHosts.test.tsx +1 -1
  99. package/src/integrations/resourceHosts.tsx +2 -0
  100. package/src/utils/navigation.ts +1 -15
  101. package/src/utils/page-links.ts +6 -0
  102. package/src/components/rightsizing/presentation.test.ts +0 -150
  103. package/src/components/rightsizing/presentation.ts +0 -109
@@ -19,6 +19,7 @@ import {
19
19
  Megaphone,
20
20
  } from "lucide-react";
21
21
  import { SlackIcon } from "../community";
22
+ import type { ContextInfo } from "../../types";
22
23
  import { useNamespaces, useContexts } from "../../api/client";
23
24
  import { CORE_RESOURCES, useAPIResources } from "../../api/apiResources";
24
25
  import { getResourceIcon } from "../../utils/resource-icons";
@@ -126,7 +127,7 @@ export function bestScore(item: CommandItem, query: string): number {
126
127
  export interface CommandItemCallbacks {
127
128
  onNavigateView: (view: MainView) => void;
128
129
  onNavigateKind: (kind: string, group: string) => void;
129
- onSwitchContext: (name: string) => void;
130
+ onSwitchContext: (context: ContextInfo) => void;
130
131
  onSetNamespaces: (ns: string[]) => void;
131
132
  onToggleTheme: () => void;
132
133
  onShowDiagnostics?: () => void;
@@ -238,9 +239,7 @@ export function useCommandItems(cb: CommandItemCallbacks): CommandItem[] {
238
239
  sublabel: sub || undefined,
239
240
  category: "Clusters",
240
241
  icon: Server,
241
- action: () => {
242
- if (!ctx.isCurrent) cb.onSwitchContext(ctx.name);
243
- },
242
+ action: () => cb.onSwitchContext(ctx),
244
243
  searchTerms: [ctx.name, account || ""].filter(Boolean),
245
244
  });
246
245
  }
@@ -5,6 +5,7 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
5
5
  import type { ContextInfo } from '../types'
6
6
 
7
7
  const mocks = vi.hoisted(() => ({
8
+ connection: { errorType: undefined as string | undefined },
8
9
  mutateAsync: vi.fn(),
9
10
  setFailedSwitch: vi.fn(),
10
11
  startSwitch: vi.fn(),
@@ -14,6 +15,7 @@ vi.mock('../api/client', () => ({
14
15
  fetchSessionCounts: async () => ({ portForwards: 0 }),
15
16
  SwitchContextError: class extends Error {},
16
17
  }))
18
+ vi.mock('../context/ConnectionContext', () => ({ useConnection: () => ({ connection: mocks.connection }) }))
17
19
  vi.mock('../context/ContextSwitchContext', () => ({
18
20
  useContextSwitch: () => ({
19
21
  startSwitch: mocks.startSwitch,
@@ -39,6 +41,7 @@ function Probe() {
39
41
 
40
42
  beforeEach(() => {
41
43
  vi.clearAllMocks()
44
+ mocks.connection.errorType = undefined
42
45
  root = createRoot(document.createElement('div'))
43
46
  act(() => root.render(<Probe />))
44
47
  })
@@ -54,6 +57,12 @@ describe('useContextSwitchFlow', () => {
54
57
  expect(mocks.mutateAsync).not.toHaveBeenCalled()
55
58
  })
56
59
 
60
+ it('selecting the stopped target starts a fresh tracked switch', async () => {
61
+ mocks.connection.errorType = 'switch-stopped'
62
+ await act(() => flow().requestSwitch(ctx('current', true)))
63
+ expect(mocks.mutateAsync).toHaveBeenCalledWith({ name: 'current' })
64
+ })
65
+
57
66
  it('picking another cluster still switches', async () => {
58
67
  await act(() => flow().requestSwitch(ctx('staging', false)))
59
68
  expect(mocks.mutateAsync).toHaveBeenCalledWith({ name: 'staging' })
@@ -1,7 +1,9 @@
1
- import { useState, type ReactNode } from 'react'
1
+ import { useLayoutEffect, useState, type ReactNode } from 'react'
2
2
  import { AlertTriangle } from 'lucide-react'
3
3
  import { pluralize } from '@skyhook-io/k8s-ui'
4
4
  import { useSwitchContext, fetchSessionCounts, SwitchContextError, type SessionCounts } from '../api/client'
5
+ import { finishSwitch, followSwitch, followingSwitch, switchInProgress, useTrackedContextSwitch } from '../api/contextSwitch'
6
+ import { useConnection } from '../context/ConnectionContext'
5
7
  import { useContextSwitch } from '../context/ContextSwitchContext'
6
8
  import { useToast } from './ui/Toast'
7
9
  import { Tooltip } from './ui/Tooltip'
@@ -30,8 +32,9 @@ interface PendingSwitch {
30
32
  // toast when the switch fails. `openAfter` is opened once the new context is
31
33
  // live. Callers render `confirmDialog`.
32
34
  export function useContextSwitchFlow() {
35
+ const { connection } = useConnection()
33
36
  const switchContext = useSwitchContext()
34
- const { startSwitch, endSwitch, setOpenAfterSwitch, setFailedSwitch } = useContextSwitch()
37
+ const { isSwitching, startSwitch, endSwitch, setOpenAfterSwitch, setFailedSwitch } = useContextSwitch()
35
38
  const { showError } = useToast()
36
39
  const { tabs } = useDock()
37
40
  const [pending, setPending] = useState<PendingSwitch | null>(null)
@@ -65,9 +68,9 @@ export function useContextSwitchFlow() {
65
68
  }
66
69
 
67
70
  const requestSwitch = async (context: ContextInfo, openAfter?: SelectedResource) => {
68
- if (switchContext.isPending) return
71
+ if (isSwitching || switchContext.isPending) return
69
72
  // Picking the cluster you're still on dismisses a refused switch's screen.
70
- if (context.isCurrent) {
73
+ if (context.isCurrent && connection.errorType !== 'switch-stopped') {
71
74
  setFailedSwitch(null)
72
75
  return
73
76
  }
@@ -157,7 +160,7 @@ export function useContextSwitchFlow() {
157
160
 
158
161
  return {
159
162
  requestSwitch,
160
- isPending: switchContext.isPending,
163
+ isPending: !!isSwitching || switchContext.isPending,
161
164
  error: switchContext.isError ? switchContext.error : null,
162
165
  // The picker's inline line is for failures that don't get the full screen.
163
166
  errorText: switchContext.isError && switchContext.error && !refusedBeforeLeaving(switchContext.error)
@@ -170,3 +173,38 @@ export function useContextSwitchFlow() {
170
173
  function shortNameHides(context: ContextInfo) {
171
174
  return parseContextForSwitcher(context).clusterName !== context.name
172
175
  }
176
+
177
+ export function useContextSwitchOutcome(applyContextChange: (context: string, id: string) => void) {
178
+ const { contextSwitch: polledSwitch, connection } = useConnection()
179
+ const contextSwitch = useTrackedContextSwitch(polledSwitch)
180
+ const { endSwitch, setOpenAfterSwitch, setFailedSwitch } = useContextSwitch()
181
+ const { showError } = useToast()
182
+
183
+ useLayoutEffect(() => {
184
+ if (!contextSwitch) return
185
+ if (switchInProgress(contextSwitch)) {
186
+ if (followingSwitch() !== contextSwitch.id) followSwitch(contextSwitch.id)
187
+ // The accepted POST can arrive before the first connection poll. Keep
188
+ // local progress until an observed operation takes over the overlay.
189
+ endSwitch()
190
+ return
191
+ }
192
+ if (followingSwitch() !== contextSwitch.id) return
193
+ if (contextSwitch.phase === 'failed' && connection.state === 'connecting') return
194
+ finishSwitch(contextSwitch.id)
195
+ endSwitch()
196
+ if (contextSwitch.phase === 'succeeded' && connection.context === contextSwitch.target) {
197
+ applyContextChange(contextSwitch.target, contextSwitch.id)
198
+ } else {
199
+ setOpenAfterSwitch(null)
200
+ if (contextSwitch.phase === 'failed' && (connection.state === 'connected' || connection.context !== contextSwitch.target)) {
201
+ const reason = contextSwitch.error || 'Cluster switch failed'
202
+ if (contextSwitch.errorType) {
203
+ setFailedSwitch({ context: contextSwitch.target, error: reason, errorType: contextSwitch.errorType })
204
+ } else {
205
+ showError('Failed to switch context', reason)
206
+ }
207
+ }
208
+ }
209
+ }, [contextSwitch, connection.state, connection.context, applyContextChange, endSwitch, setOpenAfterSwitch, setFailedSwitch, showError])
210
+ }
@@ -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,83 @@
1
+ import { renderToStaticMarkup } from 'react-dom/server'
2
+ import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
3
+ import { MemoryRouter } from 'react-router-dom'
4
+ import { expect, it, vi } from 'vitest'
5
+ import { ApiError } from '../../api/client'
6
+ import { getApiBase } from '../../api/config'
7
+ import { NavCustomizationProvider } from '../../context/NavCustomization'
8
+ import { WorkloadCostRightsizing } from '../resource/DatadogWorkloadCharts'
9
+ import { MetricsTabContent } from './WorkloadView'
10
+
11
+ vi.mock('../resource/PrometheusChartsGrid', () => ({
12
+ PrometheusChartsGrid: ({ showRightsizing = true, workloadTotals }: { showRightsizing?: boolean; workloadTotals?: React.ReactNode }) =>
13
+ <div>Prom charts{workloadTotals}{showRightsizing && <p>Prom recommendation</p>}</div>,
14
+ }))
15
+ vi.mock('../resource/RightsizingStrip', () => ({
16
+ RightsizingPanel: () => <p>Prom recommendation</p>,
17
+ RightsizingStrip: () => <p>Prom recommendation</p>,
18
+ }))
19
+ vi.mock('../resource/DatadogRightsizingPanel', () => ({
20
+ DatadogRightsizingPanel: () => <p>DD recommendation</p>,
21
+ }))
22
+ vi.mock('../resource/RestartChart', () => ({ RestartEventLane: () => null }))
23
+
24
+ function render(status: object | Error, required = true) {
25
+ const client = new QueryClient({ defaultOptions: { queries: { retryOnMount: false } } })
26
+ const queryKey = ['datadog-metrics-status', getApiBase()]
27
+ if (status instanceof Error) {
28
+ const query = client.getQueryCache().build(client, { queryKey })
29
+ query.setState({ status: 'error', error: status })
30
+ } else {
31
+ client.setQueryData(queryKey, status)
32
+ }
33
+ const workload = { kind: 'Deployment', namespace: 'shop', name: 'api' }
34
+ function view(children: React.ReactNode) {
35
+ return renderToStaticMarkup(
36
+ <MemoryRouter><NavCustomizationProvider value={{ embedded: true, rightsizingProviderStatus: required }}>
37
+ <QueryClientProvider client={client}>{children}</QueryClientProvider>
38
+ </NavCustomizationProvider></MemoryRouter>,
39
+ )
40
+ }
41
+ const metrics = view(<MetricsTabContent {...workload} resource={{}} expanded />)
42
+ const drawer = view(<MetricsTabContent {...workload} resource={{}} expanded={false} />)
43
+ const cost = view(<WorkloadCostRightsizing {...workload} />)
44
+ client.clear()
45
+ return { cost, metrics, drawer }
46
+ }
47
+
48
+ it.each([
49
+ [{ configured: false, rightsizingProvider: 'datadog' }, 'no usable rightsizing connection'],
50
+ [{ configured: false }, 'could not determine the rightsizing source'],
51
+ [new ApiError('Cluster missing', 404), 'could not determine the rightsizing source'],
52
+ [new ApiError('Gateway down', 503), 'could not determine the rightsizing source'],
53
+ ])('keeps Prom charts available and withholds sizing when its selection is unresolved', (status, reason) => {
54
+ const { cost, metrics, drawer } = render(status)
55
+ expect(metrics).toContain('Prom charts')
56
+ for (const panel of [metrics, drawer, cost]) {
57
+ expect(panel).toContain(reason)
58
+ expect(panel).not.toContain('Prom recommendation')
59
+ expect(panel).not.toContain('DD recommendation')
60
+ }
61
+ })
62
+
63
+ it.each([
64
+ [{ configured: false, rightsizingProvider: 'prometheus' }, 'Prom charts', 'Prom recommendation'],
65
+ [{ configured: true, rightsizingProvider: 'prometheus' }, 'Datadog', 'Prom recommendation'],
66
+ [{ configured: false, rightsizingProvider: 'datadog', rightsizing: true }, 'Prom charts', 'DD recommendation'],
67
+ [{ configured: true, rightsizingProvider: 'datadog', rightsizing: true }, 'Datadog', 'DD recommendation'],
68
+ ])('resolves charts independently of the single selected sizing provider', (status, charts, expected) => {
69
+ const { cost, metrics, drawer } = render(status)
70
+ expect(metrics).toContain(charts)
71
+ for (const panel of [metrics, drawer, cost]) {
72
+ expect(panel.match(/(?:DD|Prom) recommendation/g)).toEqual([expected])
73
+ }
74
+ })
75
+
76
+ it('keeps Prometheus sizing for chart-only Hubs and recognizes a missing status route', () => {
77
+ const absentRoute = new ApiError('Not found', 404, {}, { unknownRoute: true })
78
+ expect(render(absentRoute, false).cost).toContain('Prom recommendation')
79
+ expect(render(absentRoute).cost).not.toContain('Prom recommendation')
80
+ expect(render(new ApiError('Cluster unavailable', 404), false).cost).not.toContain('Prom recommendation')
81
+ expect(render({ configured: true }, false).cost).toContain('Prom recommendation')
82
+ expect(render({ configured: false }, false).cost).toContain('Prom recommendation')
83
+ })
@@ -2,7 +2,7 @@ import { describe, expect, it } from 'vitest'
2
2
 
3
3
  import { gitOpsOwnerFromRelationships } from '@skyhook-io/k8s-ui'
4
4
  import type { Relationships } from '../../types'
5
- import { collectServingRefs, memberOverviewParams, supportsBatchExecution } from './WorkloadView'
5
+ import { collectServingRefs, isPrometheusMetricsAvailable, memberOverviewParams, supportsBatchExecution } from './WorkloadView'
6
6
  import { findInheritedGitOpsLookupRef } from '../../hooks/useResolvedGitOpsOwner'
7
7
 
8
8
  describe('findInheritedGitOpsLookupRef', () => {
@@ -93,3 +93,24 @@ describe('memberOverviewParams', () => {
93
93
  expect(next.get('apiGroup')).toBe('jobset.x-k8s.io')
94
94
  })
95
95
  })
96
+
97
+ describe('isPrometheusMetricsAvailable', () => {
98
+ it('offers metrics for a core Node', () => {
99
+ expect(isPrometheusMetricsAvailable('Node', { apiVersion: 'v1', kind: 'Node' }, true)).toBe(true)
100
+ expect(isPrometheusMetricsAvailable('Node', undefined, true)).toBe(true)
101
+ })
102
+
103
+ it('offers no metrics for a Longhorn Node', () => {
104
+ const longhornNode = { apiVersion: 'longhorn.io/v1beta2', kind: 'Node' }
105
+ expect(isPrometheusMetricsAvailable('Node', longhornNode, false)).toBe(false)
106
+ expect(isPrometheusMetricsAvailable('Node', longhornNode, true)).toBe(false)
107
+ expect(isPrometheusMetricsAvailable('Node', undefined, false)).toBe(false)
108
+ })
109
+
110
+ it('keeps the workload rules', () => {
111
+ expect(isPrometheusMetricsAvailable('Deployment', {}, false)).toBe(true)
112
+ expect(isPrometheusMetricsAvailable('Pod', { status: { phase: 'Pending' } }, false)).toBe(false)
113
+ expect(isPrometheusMetricsAvailable('Pod', { status: { phase: 'Running' } }, false)).toBe(true)
114
+ expect(isPrometheusMetricsAvailable('ConfigMap', {}, false)).toBe(false)
115
+ })
116
+ })