@skyhook-io/radar-app 1.21.1 → 1.21.3

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 +50 -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 +7 -0
  16. package/src/api/sealedSecrets.test.ts +22 -0
  17. package/src/api/sealedSecrets.ts +37 -0
  18. package/src/api/vulnerabilities.ts +80 -7
  19. package/src/components/ConnectionErrorView.tsx +13 -0
  20. package/src/components/ContextSwitchActions.tsx +43 -0
  21. package/src/components/ContextSwitcher.tsx +13 -6
  22. package/src/components/SwitchAwareConnectionError.tsx +2 -2
  23. package/src/components/audit/Java4ShellPanel.test.tsx +104 -7
  24. package/src/components/audit/Java4ShellPanel.tsx +169 -72
  25. package/src/components/cost/ApplicationCostTab.test.ts +16 -0
  26. package/src/components/cost/ApplicationCostTab.tsx +41 -9
  27. package/src/components/cost/CostTrendChart.tsx +25 -2
  28. package/src/components/cost/CostTrendWithheld.render.test.tsx +105 -0
  29. package/src/components/cost/CostView.tsx +10 -2
  30. package/src/components/cost/CostViewTabs.test.tsx +18 -0
  31. package/src/components/cost/CostViewTabs.tsx +14 -22
  32. package/src/components/cost/WorkloadCostTab.test.ts +15 -0
  33. package/src/components/cost/WorkloadCostTab.tsx +42 -8
  34. package/src/components/cost/source.test.ts +16 -1
  35. package/src/components/cost/source.ts +34 -0
  36. package/src/components/diagnose/investigationEvidence/adapters/diagnose.test.ts +35 -0
  37. package/src/components/diagnose/investigationEvidence/adapters/diagnose.ts +16 -1
  38. package/src/components/dock/NodeTerminalTab.test.tsx +4 -2
  39. package/src/components/dock/NodeTerminalTab.tsx +8 -8
  40. package/src/components/dock/TerminalTab.test.tsx +12 -1
  41. package/src/components/dock/TerminalTab.tsx +6 -3
  42. package/src/components/home/CostCard.test.tsx +49 -0
  43. package/src/components/home/CostCard.tsx +98 -63
  44. package/src/components/home/mcpToolCatalog.ts +1 -0
  45. package/src/components/resource/DatadogRightsizingPanel.test.tsx +118 -0
  46. package/src/components/resource/DatadogRightsizingPanel.tsx +68 -0
  47. package/src/components/resource/DatadogWorkloadCharts.tsx +149 -0
  48. package/src/components/resource/HPACharts.render.test.tsx +42 -0
  49. package/src/components/resource/HPACharts.tsx +34 -1
  50. package/src/components/resource/PrometheusChartsGrid.render.test.tsx +126 -3
  51. package/src/components/resource/PrometheusChartsGrid.tsx +58 -25
  52. package/src/components/resource/RestartChart.render.test.tsx +72 -0
  53. package/src/components/resource/RestartChart.tsx +31 -3
  54. package/src/components/resource/RightsizingPanel.access.test.tsx +24 -0
  55. package/src/components/resource/RightsizingStrip.render.test.tsx +44 -0
  56. package/src/components/resource/RightsizingStrip.test.ts +1 -188
  57. package/src/components/resource/RightsizingStrip.tsx +27 -300
  58. package/src/components/resource/WorkloadMetricsSection.render.test.tsx +22 -0
  59. package/src/components/resource/WorkloadMetricsSection.tsx +14 -4
  60. package/src/components/resource/nameMatchedScope.ts +39 -0
  61. package/src/components/resources/pod-file-upload.ts +3 -0
  62. package/src/components/resources/renderers/CAPIClusterRenderer.tsx +5 -2
  63. package/src/components/resources/renderers/LonghornVolumeRenderer.test.tsx +104 -0
  64. package/src/components/resources/renderers/LonghornVolumeRenderer.tsx +31 -0
  65. package/src/components/resources/renderers/SealedSecretRenderer.test.tsx +41 -0
  66. package/src/components/resources/renderers/SealedSecretRenderer.tsx +14 -0
  67. package/src/components/rightsizing/RightsizingScanLink.tsx +22 -0
  68. package/src/components/rightsizing/RightsizingScanView.tsx +65 -528
  69. package/src/components/rightsizing/model.test.ts +20 -9
  70. package/src/components/rightsizing/model.ts +17 -176
  71. package/src/components/rightsizing/notices.test.tsx +30 -29
  72. package/src/components/traffic/TrafficFlowList.tsx +8 -4
  73. package/src/components/traffic/TrafficGraph.test.tsx +31 -1
  74. package/src/components/traffic/TrafficGraph.tsx +11 -6
  75. package/src/components/traffic/trafficFilters.ts +4 -4
  76. package/src/components/ui/DiagnosticsOverlay.test.ts +3 -2
  77. package/src/components/ui/DiagnosticsOverlay.tsx +23 -13
  78. package/src/components/ui/command-items.ts +3 -4
  79. package/src/components/useContextSwitchFlow.test.tsx +9 -0
  80. package/src/components/useContextSwitchFlow.tsx +43 -5
  81. package/src/components/vulnerabilities/WorkloadVulnerabilitiesSection.test.tsx +54 -0
  82. package/src/components/vulnerabilities/WorkloadVulnerabilitiesSection.tsx +50 -109
  83. package/src/components/whats-new/releaseNotes.ts +1 -1
  84. package/src/components/workload/WorkloadRightsizingSource.test.tsx +83 -0
  85. package/src/components/workload/WorkloadView.test.ts +22 -1
  86. package/src/components/workload/WorkloadView.tsx +57 -16
  87. package/src/context/ConnectionContext.test.ts +1 -0
  88. package/src/context/ConnectionContext.tsx +58 -15
  89. package/src/context/ConnectionProvider.connectionId.test.tsx +92 -0
  90. package/src/context/ConnectionProvider.retry.test.tsx +174 -1
  91. package/src/context/ContextSwitchContext.tsx +15 -1
  92. package/src/context/NavCustomization.tsx +6 -3
  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 +2 -2
  99. package/src/integrations/resourceHosts.tsx +4 -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
@@ -0,0 +1,58 @@
1
+ import { useSyncExternalStore } from 'react'
2
+ import { createTabStorage } from '../utils/tabStorage'
3
+ import { getApiBase } from './config'
4
+
5
+ export interface ContextSwitchOperation {
6
+ id: string
7
+ target: string
8
+ phase: 'preflight' | 'switching' | 'stopping' | 'stopped' | 'succeeded' | 'failed' | 'cancelled'
9
+ startedAt: string
10
+ preflightTimeoutSeconds?: number
11
+ syncTimeoutSeconds: number
12
+ progress: string
13
+ canStop?: boolean
14
+ error?: string
15
+ errorType?: string
16
+ }
17
+
18
+ export function switchInProgress(op?: ContextSwitchOperation) {
19
+ return op?.phase === 'preflight' || op?.phase === 'switching' || op?.phase === 'stopping'
20
+ }
21
+
22
+ // Only present the terminal result in a tab that was following this operation.
23
+ // A later visit also receives the server's last completed operation.
24
+ const tab = createTabStorage()
25
+ const listeners = new Set<() => void>()
26
+ function subscribe(listener: () => void) {
27
+ listeners.add(listener)
28
+ return () => { listeners.delete(listener) }
29
+ }
30
+
31
+ export function followingSwitch() {
32
+ return tab.get('radar:context-switch:' + getApiBase())
33
+ }
34
+ // Operations this tab presented a result for. A late acknowledgement of one
35
+ // (its POST outlived the poll that showed the outcome) must not replay it.
36
+ const finished = new Map<string, Set<string>>()
37
+
38
+ export function followSwitch(id: string) {
39
+ if (switchFinished(id)) return
40
+ tab.set('radar:context-switch:' + getApiBase(), id)
41
+ listeners.forEach(listener => listener())
42
+ }
43
+
44
+ /** Whether this tab already presented the result of this operation. */
45
+ export function switchFinished(id: string) {
46
+ return Boolean(id) && Boolean(finished.get(getApiBase())?.has(id))
47
+ }
48
+
49
+ export function finishSwitch(id: string) {
50
+ const base = getApiBase()
51
+ finished.set(base, (finished.get(base) ?? new Set()).add(id))
52
+ followSwitch('')
53
+ }
54
+
55
+ export function useTrackedContextSwitch(operation?: ContextSwitchOperation) {
56
+ const followedId = useSyncExternalStore(subscribe, followingSwitch, followingSwitch)
57
+ return switchInProgress(operation) || operation?.id === followedId ? operation : undefined
58
+ }
@@ -30,6 +30,8 @@ export interface RadarFeatureSpec {
30
30
  }
31
31
 
32
32
  export const RADAR_FEATURES = {
33
+ datadogRightsizing: { label: 'Datadog-backed rightsizing', flag: 'datadogRightsizing', flagShippedWithEndpoint: true, requireAffirmativeSupport: true },
34
+ datadogAgentPresence: { label: 'Datadog Agent setup hints', flag: 'datadogAgentPresence', flagShippedWithEndpoint: true },
33
35
  resourceReadCoverage: { label: 'Resource read coverage', flag: 'resourceReadCoverage', flagShippedWithEndpoint: true },
34
36
  searchCoverage: { label: 'Search coverage and object filters', flag: 'searchCoverage', flagShippedWithEndpoint: true },
35
37
  applicationEvidence: { label: 'Application evidence collection', flag: 'applicationEvidence', flagShippedWithEndpoint: true },
@@ -48,6 +50,7 @@ export const RADAR_FEATURES = {
48
50
  deploymentPause: { label: 'Deployment rollout pause and resume', flag: 'deploymentPause', flagShippedWithEndpoint: true },
49
51
  substrateHealthMetrics: { label: 'Agent Substrate charts', flag: 'substrateHealthMetrics', flagShippedWithEndpoint: true, requireAffirmativeSupport: true },
50
52
  cnpgWorkspace: { label: 'CloudNativePG views', flag: 'cnpgWorkspace', flagShippedWithEndpoint: true },
53
+ sealedSecretsController: { label: 'Sealed Secrets controller status', flag: 'sealedSecretsController', flagShippedWithEndpoint: true },
51
54
  cnpgProtectionSetup: { label: 'CloudNativePG backup setup', flag: 'cnpgProtectionSetup', flagShippedWithEndpoint: true },
52
55
  veleroWorkspace: { label: 'Velero views', flag: 'veleroWorkspace', flagShippedWithEndpoint: true },
53
56
  veleroBackupNow: { label: 'Back up now', flag: 'veleroBackupNow', flagShippedWithEndpoint: true },
@@ -83,6 +86,10 @@ export const RADAR_FEATURES = {
83
86
  podFileUpload: { label: 'Pod file uploads', flag: 'podFileUpload', flagShippedWithEndpoint: true },
84
87
  vulnerabilities: { label: 'Vulnerability views', flag: 'vulnerabilities', flagShippedWithEndpoint: true },
85
88
  runtimeAdvisoryChecks: { label: 'Java4Shell checks', flag: 'runtimeAdvisoryChecks', flagShippedWithEndpoint: true },
89
+ runtimeAdvisoryProgress: { label: 'Java4Shell scan progress', flag: 'runtimeAdvisoryProgress', flagShippedWithEndpoint: true },
90
+ // Never blocks a control: an older Radar ignores the request body and names
91
+ // the Job itself, so Trigger stays one click without the Job name dialog.
92
+ cronJobTriggerJobName: { label: 'Job names for manual CronJob runs', flag: 'cronJobTriggerJobName', flagShippedWithEndpoint: true },
86
93
  } as const satisfies Record<string, RadarFeatureSpec>
87
94
 
88
95
  export type RadarFeature = keyof typeof RADAR_FEATURES
@@ -0,0 +1,22 @@
1
+ import { expect, it } from 'vitest'
2
+ import { sealedSecretsControllerPath, sealedSecretsQueryKey, sealedSecretsRefetchInterval } from './sealedSecrets'
3
+
4
+ it('polls while the sealing keys are loading and stops once they are read', () => {
5
+ expect(sealedSecretsRefetchInterval({ installed: true, controllerState: 'ok', keysState: 'loading' })).toBe(3000)
6
+ expect(sealedSecretsRefetchInterval({ installed: true, controllerState: 'ok', keysState: 'ok' })).toBe(false)
7
+ expect(sealedSecretsRefetchInterval(undefined)).toBe(false)
8
+ })
9
+
10
+ it('polls while the controller lookup is loading too', () => {
11
+ expect(sealedSecretsRefetchInterval({ installed: true, controllerState: 'loading', keysState: 'unknown' })).toBe(3000)
12
+ })
13
+
14
+ it('asks again once support is confirmed, so an early failure does not stick', () => {
15
+ expect(sealedSecretsQueryKey('unknown', 'team')).not.toEqual(sealedSecretsQueryKey('supported', 'team'))
16
+ })
17
+
18
+ it('keeps one answer per SealedSecret namespace', () => {
19
+ expect(sealedSecretsQueryKey('supported', 'team-x')).not.toEqual(sealedSecretsQueryKey('supported', 'team-y'))
20
+ expect(sealedSecretsControllerPath('team-x')).toBe('/sealedsecrets/controller?sealedSecretNamespace=team-x')
21
+ expect(sealedSecretsControllerPath('')).toBe('/sealedsecrets/controller')
22
+ })
@@ -0,0 +1,37 @@
1
+ import { useQuery } from '@tanstack/react-query'
2
+ import type { SealedSecretsController } from '@skyhook-io/k8s-ui/components/resources/renderers/SealedSecretRenderer'
3
+ import { fetchJSON, useRadarFeature } from './client'
4
+ import { shouldRetryRadarQuery, type RadarFeatureSupport } from './radarFeatures'
5
+
6
+ // Re-ask while Radar's Secret cache is still syncing, so the keys appear on
7
+ // their own instead of waiting out the stale time.
8
+ export function sealedSecretsRefetchInterval(data: SealedSecretsController | undefined): number | false {
9
+ return data?.keysState === 'loading' || data?.controllerState === 'loading' ? 3000 : false
10
+ }
11
+
12
+ // Support is part of the key, so an answer fetched before capabilities
13
+ // loaded is asked again once support is confirmed. The namespace is too: the
14
+ // controller is the one serving the SealedSecret's namespace.
15
+ export function sealedSecretsQueryKey(support: RadarFeatureSupport, namespace: string) {
16
+ return ['sealedsecrets', 'controller', namespace, support] as const
17
+ }
18
+
19
+ export function sealedSecretsControllerPath(namespace: string) {
20
+ return namespace ? `/sealedsecrets/controller?sealedSecretNamespace=${encodeURIComponent(namespace)}` : '/sealedsecrets/controller'
21
+ }
22
+
23
+ // The sealed-secrets controller serving `namespace`, its sealing keys (names
24
+ // and dates only) and the SealedSecret totals the caller can list. Disabled
25
+ // on an older Radar.
26
+ export function useSealedSecretsController(namespace: string) {
27
+ const { support, guard } = useRadarFeature('sealedSecretsController')
28
+ const query = useQuery({
29
+ queryKey: sealedSecretsQueryKey(support, namespace),
30
+ queryFn: ({ signal }) => guard(() => fetchJSON<SealedSecretsController>(sealedSecretsControllerPath(namespace), signal)),
31
+ enabled: support !== 'unsupported',
32
+ refetchInterval: (q) => sealedSecretsRefetchInterval(q.state.data),
33
+ staleTime: 30_000,
34
+ retry: shouldRetryRadarQuery,
35
+ })
36
+ return { ...query, support }
37
+ }
@@ -1,10 +1,11 @@
1
- import { useQuery } from '@tanstack/react-query'
1
+ import { useQuery, useQueryClient } from '@tanstack/react-query'
2
2
  import type { ReadGap } from '@skyhook-io/k8s-ui/types/read-coverage'
3
3
  import type { ResourceReadCoverage } from '@skyhook-io/k8s-ui/types/resource-coverage'
4
4
  import type { APIResource } from '../types'
5
- import { ApiError, fetchJSON, useRadarFeature } from './client'
5
+ import { ApiError, apiFetch, fetchJSON, useRadarFeature } from './client'
6
6
  import { readActionFor } from '@skyhook-io/k8s-ui/utils/read-actions'
7
- import { getApiBase } from './config'
7
+ import { apiUrl, getApiBase } from './config'
8
+ import { httpStatusMessage, readErrorResponse } from './httpErrors'
8
9
  import { shouldRetryRadarQuery } from './radarFeatures'
9
10
 
10
11
  // Mirrors internal/vulnerabilities/types.go.
@@ -184,6 +185,7 @@ export interface Java4ShellFinding {
184
185
  pods: number
185
186
  vbmiPods: number
186
187
  unknownCPUPods: number
188
+ noVBMIByInstanceType?: Record<string, number>
187
189
  mitigationDeclaredPods: number
188
190
  }
189
191
 
@@ -206,12 +208,18 @@ export interface Java4ShellResult {
206
208
  unassessed: Record<string, number>
207
209
  unassessedRows: Java4ShellUnassessed[]
208
210
  unassessedGroups: number
211
+ authRequiredRegistries?: string[]
212
+ rateLimitedRegistries?: string[]
213
+ unaffectedByMajor?: Record<string, number>
209
214
  coverage: ResourceReadCoverage
210
215
  workload?: VulnerabilityWorkloadRef
211
216
  }
212
217
 
213
218
  export function useJava4ShellCheck(namespaces: string[], context: string, workload?: VulnerabilityWorkloadRef) {
214
219
  const { guard } = useRadarFeature('runtimeAdvisoryChecks')
220
+ const { guard: guardProgress, support: progressSupport } = useRadarFeature('runtimeAdvisoryProgress')
221
+ const client = useQueryClient()
222
+ const base = getApiBase()
215
223
  const query = new URLSearchParams()
216
224
  if (workload) {
217
225
  query.set('workloadKind', workload.kind)
@@ -221,13 +229,78 @@ export function useJava4ShellCheck(namespaces: string[], context: string, worklo
221
229
  } else if (namespaces.length > 0) {
222
230
  query.set('namespaces', [...namespaces].sort().join(','))
223
231
  }
224
- const path = '/vulnerabilities/java4shell' + (query.size ? `?${query}` : '')
225
- return useQuery({
226
- queryKey: ['java4shell', getApiBase(), context, path],
227
- queryFn: ({ signal }) => guard(() => fetchJSON<Java4ShellResult>(path, { signal, cache: 'no-store' })),
232
+ const suffix = query.size ? `?${query}` : ''
233
+ const path = '/vulnerabilities/java4shell' + suffix
234
+ const queryKey = ['java4shell', base, context, path]
235
+ const progressKey = [...queryKey, 'progress']
236
+ const activeKey = ['java4shell-active', base]
237
+ const { data: progress } = useQuery<Java4ShellProgress | null>({ queryKey: progressKey, enabled: false })
238
+ const { data: activeScan } = useQuery<AbortController | null>({ queryKey: activeKey, enabled: false, gcTime: 6 * 60 * 1000 })
239
+ const check = useQuery({
240
+ queryKey,
241
+ queryFn: async (request) => {
242
+ if (progressSupport !== 'supported') {
243
+ return guard(() => fetchJSON<Java4ShellResult>(path, { signal: request.signal, cache: 'no-store' }))
244
+ }
245
+ if (client.getQueryData(activeKey)) throw new Error('A Java4Shell check is already running.')
246
+ const scan = new AbortController()
247
+ client.setQueryData(activeKey, scan)
248
+ client.setQueryData(progressKey, null)
249
+ // The streaming request can finish while the user visits another Radar view.
250
+ try {
251
+ return await guardProgress(() => streamJava4Shell(apiUrl('/vulnerabilities/java4shell/stream' + suffix, base), update => {
252
+ client.setQueryData(progressKey, update)
253
+ }, scan.signal))
254
+ } finally {
255
+ if (client.getQueryData(activeKey) === scan) client.setQueryData(activeKey, null)
256
+ }
257
+ },
228
258
  enabled: false,
229
259
  retry: false,
230
260
  })
261
+ const cancel = activeScan ? () => activeScan.abort(new DOMException('Java4Shell check canceled.', 'AbortError')) : undefined
262
+ return { ...check, progress, cancel }
263
+ }
264
+
265
+ interface Java4ShellProgress {
266
+ done: number
267
+ total: number
268
+ }
269
+
270
+ type Java4ShellStreamMessage =
271
+ | { type: 'progress'; progress: Java4ShellProgress }
272
+ | { type: 'result'; report: Java4ShellResult }
273
+ | { type: 'error'; error: string }
274
+
275
+ export async function streamJava4Shell(url: string, onProgress: (progress: Java4ShellProgress) => void, signal?: AbortSignal): Promise<Java4ShellResult> {
276
+ const response = await apiFetch(url, { cache: 'no-store', signal })
277
+ if (!response.ok) {
278
+ const { body, unknownRoute } = await readErrorResponse(response)
279
+ throw new ApiError(body.error || httpStatusMessage(response.status, response.statusText), response.status, body, { unknownRoute })
280
+ }
281
+ if (!response.body) throw new Error('Radar did not return a Java4Shell scan.')
282
+
283
+ const reader = response.body.getReader()
284
+ const decoder = new TextDecoder()
285
+ let pending = ''
286
+ try {
287
+ for (;;) {
288
+ const { done, value } = await reader.read()
289
+ if (done) break
290
+ pending += decoder.decode(value, { stream: true })
291
+ let index: number
292
+ while ((index = pending.indexOf('\n')) >= 0) {
293
+ const message = JSON.parse(pending.slice(0, index)) as Java4ShellStreamMessage
294
+ pending = pending.slice(index + 1)
295
+ if (message.type === 'result') return message.report
296
+ if (message.type === 'error') throw new Error(message.error)
297
+ if (message.type === 'progress') onProgress(message.progress)
298
+ }
299
+ }
300
+ throw new Error('The Java4Shell scan ended before Radar returned a result. Run the check again.')
301
+ } finally {
302
+ await reader.cancel().catch(() => {})
303
+ }
231
304
  }
232
305
 
233
306
  // What an answer is about, apart from its filters: the workload and the
@@ -403,6 +403,19 @@ export function ConnectionErrorView({ connection, onRetry, isRetrying, back, var
403
403
  openLocalTerminal({ initialCommand: command, title: 'Auth' })
404
404
  }
405
405
 
406
+ if (connection.errorType === 'switch-stopped') {
407
+ return (
408
+ <div className="flex-1 flex flex-col items-center justify-center gap-3 px-8 text-center">
409
+ <h2 className="text-xl font-semibold text-theme-text-primary">Cluster switch stopped</h2>
410
+ <p className="text-sm text-theme-text-secondary">The previous connection was closed. Choose a cluster to reconnect.</p>
411
+ <div className="flex flex-wrap items-center justify-center gap-3">
412
+ <ContextSwitcher triggerName="Choose a cluster" />
413
+ {back && <button type="button" className="btn-secondary px-3 py-1.5" disabled={back.disabled} onClick={back.onBack}>Reconnect to {back.label}</button>}
414
+ </div>
415
+ </div>
416
+ )
417
+ }
418
+
406
419
  // A startup setting kept Radar from connecting, and the error names the
407
420
  // setting to change. Settings are read at startup, so retrying or switching
408
421
  // context can't clear it: only the message, no recovery actions.
@@ -0,0 +1,43 @@
1
+ import { useEffect, useState } from 'react'
2
+ import { useMutation, useQueryClient } from '@tanstack/react-query'
3
+ import { formatDuration } from '@skyhook-io/k8s-ui/components/resources/resource-utils'
4
+ import { apiFetch } from '../api/client'
5
+ import { apiUrl } from '../api/config'
6
+ import type { ContextSwitchOperation } from '../api/contextSwitch'
7
+ import { readErrorBody } from '../api/httpErrors'
8
+
9
+ export function ContextSwitchActions({ operation, syncing, onDismiss }: { operation: ContextSwitchOperation; syncing: boolean; onDismiss: () => void }) {
10
+ const queryClient = useQueryClient()
11
+ const [now, setNow] = useState(Date.now)
12
+ useEffect(() => {
13
+ const timer = window.setInterval(() => setNow(Date.now()), 1000)
14
+ return () => window.clearInterval(timer)
15
+ }, [])
16
+ const cancel = useMutation({
17
+ mutationFn: async (action: 'cancelSwitch' | 'stopSwitch') => {
18
+ const path = `/contexts/${encodeURIComponent(operation.target)}?${action}=${encodeURIComponent(operation.id)}`
19
+ const response = await apiFetch(apiUrl(path), { method: 'POST' })
20
+ if (!response.ok) throw new Error((await readErrorBody(response)).error || (action === 'cancelSwitch' ? 'Could not cancel the switch' : 'Could not stop the switch'))
21
+ },
22
+ onSettled: () => queryClient.invalidateQueries({ queryKey: ['connection-status'] }),
23
+ })
24
+
25
+ let stageLimit = ''
26
+ if (operation.phase === 'preflight' && operation.preflightTimeoutSeconds !== undefined) {
27
+ stageLimit = `Connectivity check limit ${formatDuration(operation.preflightTimeoutSeconds * 1000, true)}`
28
+ } else if (operation.phase === 'switching' && syncing) {
29
+ stageLimit = `Initial workload sync limit ${formatDuration(operation.syncTimeoutSeconds * 1000, true)}`
30
+ }
31
+
32
+ return <span className="mt-2 block text-sm font-normal">
33
+ <span aria-live="off" className="block text-xs text-theme-text-tertiary">Elapsed {formatDuration(Math.max(0, now - Date.parse(operation.startedAt)), true)}{stageLimit && ` · ${stageLimit}`}</span>
34
+ {operation.phase === 'preflight'
35
+ ? <button type="button" disabled={cancel.isPending} className="btn-secondary mt-3 px-3 py-1.5" onClick={() => cancel.mutate('cancelSwitch')}>Cancel switch</button>
36
+ : <>
37
+ {operation.canStop && <span className="mt-2 block text-theme-text-secondary">The previous connection is closed. Stop to choose a cluster.</span>}
38
+ {operation.canStop && <button type="button" disabled={cancel.isPending} className="btn-secondary mt-3 px-3 py-1.5" onClick={() => cancel.mutate('stopSwitch')}>Stop switch</button>}
39
+ <button type="button" className="ml-2 mt-3 px-3 py-1.5 text-theme-text-secondary" onClick={onDismiss}>Hide progress</button>
40
+ </>}
41
+ {cancel.error && ((cancel.variables === 'cancelSwitch' && operation.phase === 'preflight') || (cancel.variables === 'stopSwitch' && operation.canStop)) && <span role="alert" className="block">{cancel.error.message}</span>}
42
+ </span>
43
+ }
@@ -30,11 +30,12 @@ export const ContextSwitcher = forwardRef<ContextSwitcherHandle, ContextSwitcher
30
30
  const { data: contexts, isLoading: contextsLoading } = useContexts()
31
31
  const { data: clusterInfo } = useClusterInfo()
32
32
  const { data: capabilities } = useCapabilities()
33
- const switchFlow = useContextSwitchFlow()
34
- const { failedSwitch } = useContextSwitch()
33
+ const { failedSwitch, dismissed, setDismissed, targetContext } = useContextSwitch()
35
34
  // A settings error (Desktop's namespace list over the limit) blocks every
36
35
  // switch until restart, so offering the list would only lead to a refusal.
37
- const { connection } = useConnection()
36
+ const { connection, contextSwitch } = useConnection()
37
+ const stopped = connection.errorType === 'switch-stopped'
38
+ const switchFlow = useContextSwitchFlow()
38
39
  const settingsBlocked = connection.errorType === 'settings'
39
40
 
40
41
  // Parse contexts and decide whether to render group headers (multi-account only).
@@ -115,18 +116,24 @@ export const ContextSwitcher = forwardRef<ContextSwitcherHandle, ContextSwitcher
115
116
  }
116
117
 
117
118
  const currentCtx = contexts?.find(c => c.isCurrent)
118
- const currentId = currentCtx?.name
119
+ const currentId = stopped ? connection.context : currentCtx?.name
119
120
  // Keep the trigger name parseable and render any collision qualifier as a
120
121
  // separate suffix so cloud-provider metadata remains intact.
121
122
  // Fall back to clusterInfo.context for the very-early window before
122
123
  // /api/contexts has resolved.
123
124
  const currentParsed = currentId ? parsedById.get(currentId) : undefined
124
- const currentRaw = triggerName || currentParsed?.raw || clusterInfo?.context || currentCtx?.name || 'Unknown'
125
+ const currentRaw = triggerName || currentParsed?.raw || currentId || clusterInfo?.context || 'Unknown'
125
126
  const currentNameQualifier = triggerName
126
127
  ? undefined
127
128
  : visibleContextQualifier(currentParsed?.nameQualifier, currentCtx?.source, hasMultipleSources)
128
129
  const currentSourceLabel = triggerName ? undefined : hasMultipleSources ? currentCtx?.source || undefined : undefined
129
130
 
131
+ if (dismissed && targetContext) {
132
+ return <button type="button" className="text-sm text-accent-text" onClick={() => setDismissed(false)}>
133
+ {contextSwitch?.phase === 'stopping' ? 'Stopping switch to' : 'Switching to'} {targetContext.clusterName}…
134
+ </button>
135
+ }
136
+
130
137
  return (
131
138
  <>
132
139
  <ClusterSwitcher
@@ -143,7 +150,7 @@ export const ContextSwitcher = forwardRef<ContextSwitcherHandle, ContextSwitcher
143
150
  loading={switchFlow.isPending}
144
151
  disabled={settingsBlocked || contextsLoading || !capabilities || capabilities.configManagement === 'operator'}
145
152
  searchable={items.length > 1}
146
- currentSelectable={!!failedSwitch}
153
+ currentSelectable={!!failedSwitch || stopped}
147
154
  showGroupHeaders={hasMultipleAccounts}
148
155
  errorSlot={
149
156
  switchFlow.errorText ? (
@@ -14,7 +14,7 @@ function clusterLabel(contexts: ContextInfo[] | undefined, name: string): string
14
14
 
15
15
  // A switch Radar refused before leaving the current cluster: the connection
16
16
  // error screen for the cluster that didn't answer, with its fix steps. The
17
- // current cluster is still connected underneath, so Back only closes this.
17
+ // previous connection is still selected, so Back only closes this.
18
18
  export function FailedSwitchView({ currentContext }: { currentContext: string }) {
19
19
  const { failedSwitch, setFailedSwitch } = useContextSwitch()
20
20
  const { data: contexts } = useContexts()
@@ -41,7 +41,7 @@ export function FailedSwitchView({ currentContext }: { currentContext: string })
41
41
  void requestSwitch(target).finally(() => setStarting(false))
42
42
  }}
43
43
  isRetrying={busy}
44
- back={{ label: clusterLabel(contexts, currentContext), onBack: () => setFailedSwitch(null), disabled: busy }}
44
+ back={{ label: currentContext ? clusterLabel(contexts, currentContext) : 'connection status', onBack: () => setFailedSwitch(null), disabled: busy }}
45
45
  variant="switch"
46
46
  />
47
47
  {confirmDialog}
@@ -1,19 +1,21 @@
1
1
  import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
2
2
  import { renderToStaticMarkup } from 'react-dom/server'
3
- import { expect, it } from 'vitest'
3
+ import { expect, it, vi } from 'vitest'
4
4
  import { getApiBase } from '../../api/config'
5
- import type { Java4ShellResult } from '../../api/vulnerabilities'
5
+ import { streamJava4Shell, type Java4ShellResult } from '../../api/vulnerabilities'
6
6
  import { Java4ShellPanel } from './Java4ShellPanel'
7
7
 
8
- it('shows the Java home count before opening details and counts other failures once', () => {
8
+ it('shows Java home and check limit counts before opening details and counts other failures once', () => {
9
9
  const result: Java4ShellResult = {
10
10
  findings: [],
11
- containers: 6,
11
+ containers: 18,
12
12
  matches: 0,
13
13
  findingGroups: 0,
14
- unassessed: { java_home_declared: 3, auth_required: 2, no_java_declaration: 1 },
14
+ unassessed: { java_home_declared: 3, auth_required: 2, platform_unknown: 2, no_java_declaration: 1, not_checked: 4, docker_hub_limit: 1, rate_limited: 2 },
15
15
  unassessedRows: [],
16
- unassessedGroups: 3,
16
+ unassessedGroups: 5,
17
+ rateLimitedRegistries: ['public.ecr.aws'],
18
+ unaffectedByMajor: { '8': 3 },
17
19
  coverage: { status: 'complete', scope: { type: 'all_namespaces' }, read: { type: 'all_namespaces' }, gaps: [] },
18
20
  }
19
21
  const client = new QueryClient({ defaultOptions: { queries: { enabled: false } } })
@@ -25,7 +27,102 @@ it('shows the Java home count before opening details and counts other failures o
25
27
  )
26
28
 
27
29
  expect(html).toContain('Images for 3 containers set <code>JAVA_HOME</code>. Verify the installed Java version.')
28
- expect(html).toContain('Java version unassessed in 2 containers.')
30
+ expect(html).toContain('Scan limit reached for 4 containers.')
31
+ expect(html).toContain('Radar&#x27;s Docker Hub lookup cap reached for 1 container.')
32
+ expect(html).toContain('14 with assessment gaps')
33
+ expect(html).toContain('Check scope</span> · All namespaces')
34
+ expect(html).toContain('Could not check · next steps')
35
+ expect(html).toContain('Retry to reuse cached public image metadata.')
36
+ expect(html).toContain('Registry throttling affected 2 containers · public.ecr.aws')
37
+ expect(html).toContain('Radar pauses calls to throttled registries for five minutes.')
38
+ expect(html).toContain('verify the installed version in workloads that use Java')
39
+ expect(html).toContain('Declared Java 8 outside affected versions · 3 containers')
40
+ expect(html).toContain('Registry authentication required for 2 containers.')
41
+ expect(html).toContain('Image platform unknown · 2 containers')
42
+ expect(html).toContain('<p role="status" class="sr-only">Java4Shell check finished.</p>')
29
43
  expect(html).toContain('aria-expanded="false"')
30
44
  expect(html).not.toContain('aria-label="Unassessed containers by workload"')
31
45
  })
46
+
47
+ it('explains how to follow up when one workload hits the Docker Hub cap', () => {
48
+ const workload = { kind: 'Deployment', group: 'apps', namespace: 'payments', name: 'api' }
49
+ const coverage: Java4ShellResult['coverage'] = { status: 'complete', scope: { type: 'namespaces' }, gaps: [] }
50
+ const client = new QueryClient({ defaultOptions: { queries: { enabled: false } } })
51
+ client.setQueryData([
52
+ 'java4shell', getApiBase(), 'fixture',
53
+ '/vulnerabilities/java4shell?workloadKind=Deployment&workloadGroup=apps&workloadNamespace=payments&workloadName=api',
54
+ ], {
55
+ findings: [], containers: 1, matches: 0, findingGroups: 0, unassessed: { docker_hub_limit: 1 },
56
+ unassessedRows: [{ workload, container: 'app', image: 'docker.io/library/fixture', pods: 1, reason: 'docker_hub_limit' }],
57
+ unassessedGroups: 1, coverage, workload,
58
+ } satisfies Java4ShellResult)
59
+ const html = renderToStaticMarkup(
60
+ <QueryClientProvider client={client}>
61
+ <Java4ShellPanel context="fixture" connected workload={workload} />
62
+ </QueryClientProvider>,
63
+ )
64
+
65
+ expect(html).toContain('Check scope</span> · payments/api')
66
+ expect(html).toContain('Retry to reuse any image metadata Radar cached. If the cap is reached again, verify Java in the skipped containers.')
67
+ expect(html).toContain('Show skipped images')
68
+ })
69
+
70
+ it('shows instance-type inference alongside unknown CPU and non-x86 placement', () => {
71
+ const result: Java4ShellResult = {
72
+ findings: [{
73
+ workload: { kind: 'Deployment', group: 'apps', namespace: 'team', name: 'api' },
74
+ container: 'app',
75
+ image: 'example.com/team/api',
76
+ digest: 'sha256:fixture',
77
+ version: 'jdk-21.0.8+9',
78
+ pods: 4,
79
+ vbmiPods: 0,
80
+ unknownCPUPods: 1,
81
+ noVBMIByInstanceType: { 'm6a.large': 2 },
82
+ mitigationDeclaredPods: 0,
83
+ }],
84
+ containers: 4,
85
+ matches: 4,
86
+ findingGroups: 1,
87
+ unassessed: {},
88
+ unassessedRows: [],
89
+ unassessedGroups: 0,
90
+ coverage: { status: 'complete', scope: { type: 'all_namespaces' }, read: { type: 'all_namespaces' }, gaps: [] },
91
+ }
92
+ const client = new QueryClient({ defaultOptions: { queries: { enabled: false } } })
93
+ client.setQueryData(['java4shell', getApiBase(), 'fixture', '/vulnerabilities/java4shell'], result)
94
+ const html = renderToStaticMarkup(
95
+ <QueryClientProvider client={client}>
96
+ <Java4ShellPanel context="fixture" connected onNavigateToResource={() => {}} />
97
+ </QueryClientProvider>,
98
+ )
99
+ expect(html).toContain('2 Pods on m6a.large · VBMI absent (inferred from instance type)')
100
+ expect(html).toContain('CPU capability unknown for 1 Pod')
101
+ expect(html).toContain('1 Pod on non-x86 nodes at check time')
102
+ })
103
+
104
+ it('delivers progress and only returns a result after the terminal record', async () => {
105
+ const update = { done: 1, total: 3 }
106
+ const report = { containers: 3, matches: 0, unaffectedByMajor: { '8': 3 } }
107
+ const progressLine = JSON.stringify({ type: 'progress', progress: update }) + '\n'
108
+ const resultLine = JSON.stringify({ type: 'result', report }) + '\n'
109
+ const encoder = new TextEncoder()
110
+ const fetch = vi.fn()
111
+ const response = (...chunks: string[]) => new Response(new ReadableStream({
112
+ start(stream) {
113
+ for (const chunk of chunks) stream.enqueue(encoder.encode(chunk))
114
+ stream.close()
115
+ },
116
+ }))
117
+ fetch.mockResolvedValueOnce(response(progressLine.slice(0, 6), progressLine.slice(6) + resultLine))
118
+ fetch.mockResolvedValueOnce(response(progressLine))
119
+ vi.stubGlobal('fetch', fetch)
120
+ try {
121
+ const onProgress = vi.fn()
122
+ await expect(streamJava4Shell('/api/vulnerabilities/java4shell/stream', onProgress)).resolves.toEqual(report)
123
+ expect(onProgress).toHaveBeenCalledExactlyOnceWith(update)
124
+ await expect(streamJava4Shell('/api/vulnerabilities/java4shell/stream', vi.fn())).rejects.toThrow('ended before Radar returned a result')
125
+ } finally {
126
+ vi.unstubAllGlobals()
127
+ }
128
+ })