@skyhook-io/radar-app 1.20.3 → 1.21.1

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 (167) hide show
  1. package/package.json +10 -9
  2. package/src/App.tsx +67 -15
  3. package/src/api/client.audit-gating.test.tsx +105 -5
  4. package/src/api/client.auditBadgesSync.test.tsx +118 -0
  5. package/src/api/client.capabilitiesPoll.test.ts +61 -0
  6. package/src/api/client.ts +129 -5
  7. package/src/api/namespaceScopeRetry.test.ts +14 -0
  8. package/src/api/radarFeatures.ts +11 -0
  9. package/src/api/substrateHealth.ts +134 -0
  10. package/src/api/velero.test.ts +60 -0
  11. package/src/api/velero.ts +377 -0
  12. package/src/api/vulnerabilities.ts +313 -0
  13. package/src/components/NamespaceSwitcher.tsx +3 -1
  14. package/src/components/audit/AuditView.tsx +4 -0
  15. package/src/components/audit/ChecksViewTabs.test.tsx +35 -5
  16. package/src/components/audit/ChecksViewTabs.tsx +12 -1
  17. package/src/components/audit/Java4ShellPanel.test.tsx +31 -0
  18. package/src/components/audit/Java4ShellPanel.tsx +313 -0
  19. package/src/components/audit/UpgradeReadinessView.test.ts +35 -1
  20. package/src/components/audit/UpgradeReadinessView.tsx +60 -2
  21. package/src/components/audit/VulnerabilitiesView.tsx +944 -0
  22. package/src/components/cnpg/CNPGClusterTabs.tsx +3 -1
  23. package/src/components/cnpg/CNPGDrawerTrail.tsx +5 -26
  24. package/src/components/cnpg/CNPGInvestigationAction.test.tsx +27 -6
  25. package/src/components/cnpg/CNPGView.tsx +43 -117
  26. package/src/components/cnpg/CNPGWorkspace.compatibility.test.tsx +30 -0
  27. package/src/components/cnpg/host.tsx +2 -2
  28. package/src/components/cnpg/routes.ts +3 -1
  29. package/src/components/cnpg/shared.tsx +5 -53
  30. package/src/components/cnpg/useCNPGNavigate.ts +1 -21
  31. package/src/components/cnpg/useCNPGSidebarWorkspace.ts +16 -13
  32. package/src/components/community.tsx +42 -0
  33. package/src/components/diagnose/diagnoseEvidenceTypes.ts +2 -0
  34. package/src/components/diagnose/investigationMetrics.test.ts +20 -0
  35. package/src/components/diagnose/investigationMetrics.ts +2 -1
  36. package/src/components/dock/BottomDock.tsx +1 -0
  37. package/src/components/dock/LogsTab.tsx +3 -0
  38. package/src/components/gitops/FluxOperatorCard.test.tsx +37 -0
  39. package/src/components/gitops/FluxOperatorCard.tsx +27 -0
  40. package/src/components/gitops/GitOpsView.rowsSummary.test.tsx +59 -0
  41. package/src/components/gitops/GitOpsView.tsx +8 -5
  42. package/src/components/gitops/gitopsRowEvents.test.ts +48 -0
  43. package/src/components/gitops/gitopsRowEvents.ts +31 -0
  44. package/src/components/helm/HelmDrawerFrame.tsx +1 -1
  45. package/src/components/helm/HelmView.tsx +20 -16
  46. package/src/components/helm/OwnedResources.tsx +4 -3
  47. package/src/components/home/ClusterHealthCard.tsx +3 -1
  48. package/src/components/home/HomeAgentBlock.tsx +3 -0
  49. package/src/components/home/HomeView.tsx +7 -0
  50. package/src/components/home/MCPSetupDialog.test.tsx +19 -12
  51. package/src/components/home/MCPSetupDialog.tsx +4 -2
  52. package/src/components/home/mcpToolCatalog.ts +15 -2
  53. package/src/components/home/useVulnerabilitiesRow.test.ts +26 -0
  54. package/src/components/home/useVulnerabilitiesRow.ts +50 -0
  55. package/src/components/logs/LogsViewer.tsx +3 -1
  56. package/src/components/logs/MultiPodLogsTab.test.tsx +24 -4
  57. package/src/components/logs/MultiPodLogsTab.tsx +9 -5
  58. package/src/components/nav/PrimaryNavRail.test.tsx +17 -0
  59. package/src/components/nav/PrimaryNavRail.tsx +174 -29
  60. package/src/components/resource/PrometheusChartsGrid.tsx +5 -1
  61. package/src/components/resource/SubstrateHealthCharts.test.tsx +143 -0
  62. package/src/components/resource/SubstrateHealthCharts.tsx +254 -0
  63. package/src/components/resource/SubstrateVerdictLine.test.tsx +131 -0
  64. package/src/components/resource/SubstrateVerdictLine.tsx +180 -0
  65. package/src/components/resources/ResourcesView.tsx +12 -6
  66. package/src/components/resources/renderers/UpgradePlanRenderer.test.tsx +20 -0
  67. package/src/components/resources/renderers/UpgradePlanRenderer.tsx +22 -0
  68. package/src/components/resources/renderers/VeleroBackupRenderer.tsx +16 -36
  69. package/src/components/resources/renderers/VeleroRestoreRenderer.tsx +6 -19
  70. package/src/components/resources/renderers/WorkloadRenderer.tsx +8 -0
  71. package/src/components/rightsizing/RightsizingScanView.tsx +3 -2
  72. package/src/components/shared/LargeClusterNamespacePicker.test.tsx +27 -0
  73. package/src/components/shared/LargeClusterNamespacePicker.tsx +8 -2
  74. package/src/components/timeline/TimelineView.tsx +3 -1
  75. package/src/components/traffic/TrafficConnectionsTable.test.tsx +94 -0
  76. package/src/components/traffic/TrafficConnectionsTable.tsx +21 -5
  77. package/src/components/traffic/TrafficData.test.tsx +37 -0
  78. package/src/components/traffic/TrafficData.tsx +27 -0
  79. package/src/components/traffic/TrafficFlowList.tsx +9 -7
  80. package/src/components/traffic/TrafficGraph.layoutEngine.test.tsx +193 -0
  81. package/src/components/traffic/TrafficGraph.test.tsx +269 -0
  82. package/src/components/traffic/TrafficGraph.tsx +135 -64
  83. package/src/components/traffic/TrafficGraphUnavailable.tsx +57 -0
  84. package/src/components/traffic/TrafficView.layoutUnavailable.test.tsx +211 -0
  85. package/src/components/traffic/TrafficView.tsx +46 -129
  86. package/src/components/traffic/trafficFilters.test.ts +172 -1
  87. package/src/components/traffic/trafficFilters.ts +139 -0
  88. package/src/components/ui/DiagnosticsOverlay.tsx +14 -1
  89. package/src/components/ui/UpdateNotification.manual.test.tsx +5 -2
  90. package/src/components/ui/UpdateNotification.test.tsx +31 -2
  91. package/src/components/ui/UpdateNotification.tsx +34 -17
  92. package/src/components/ui/command-items.ts +24 -1
  93. package/src/components/velero/VeleroBackupNow.test.tsx +165 -0
  94. package/src/components/velero/VeleroBackupNow.tsx +143 -0
  95. package/src/components/velero/VeleroDeleteBackup.test.tsx +364 -0
  96. package/src/components/velero/VeleroDeleteBackup.tsx +306 -0
  97. package/src/components/velero/VeleroDetailPage.tsx +158 -0
  98. package/src/components/velero/VeleroKindLists.test.tsx +48 -0
  99. package/src/components/velero/VeleroKindLists.tsx +43 -0
  100. package/src/components/velero/VeleroLocations.expand.test.tsx +27 -0
  101. package/src/components/velero/VeleroLocations.test.tsx +86 -0
  102. package/src/components/velero/VeleroLocations.tsx +240 -0
  103. package/src/components/velero/VeleroOverview.test.tsx +311 -0
  104. package/src/components/velero/VeleroOverview.tsx +485 -0
  105. package/src/components/velero/VeleroPages.test.tsx +516 -0
  106. package/src/components/velero/VeleroPages.tsx +1056 -0
  107. package/src/components/velero/VeleroRunArtifacts.test.tsx +241 -0
  108. package/src/components/velero/VeleroRunArtifacts.tsx +112 -0
  109. package/src/components/velero/VeleroRunLists.tsx +309 -0
  110. package/src/components/velero/VeleroRunMessagesHost.test.tsx +25 -0
  111. package/src/components/velero/VeleroRunMessagesHost.tsx +54 -0
  112. package/src/components/velero/VeleroRunVolumes.test.tsx +247 -0
  113. package/src/components/velero/VeleroRunVolumes.tsx +122 -0
  114. package/src/components/velero/VeleroSchedulePause.test.tsx +211 -0
  115. package/src/components/velero/VeleroSchedulePause.tsx +191 -0
  116. package/src/components/velero/VeleroScheduleStatusBadge.test.tsx +28 -0
  117. package/src/components/velero/VeleroScheduleStatusBadge.tsx +21 -0
  118. package/src/components/velero/VeleroSchedules.tsx +255 -0
  119. package/src/components/velero/VeleroView.tsx +59 -0
  120. package/src/components/velero/VeleroWorkspace.gate.test.tsx +97 -0
  121. package/src/components/velero/attention.test.ts +178 -0
  122. package/src/components/velero/attention.ts +281 -0
  123. package/src/components/velero/backupDelete.test.tsx +91 -0
  124. package/src/components/velero/backupDelete.tsx +182 -0
  125. package/src/components/velero/coverage.test.ts +87 -0
  126. package/src/components/velero/coverage.ts +150 -0
  127. package/src/components/velero/host.tsx +92 -0
  128. package/src/components/velero/routes.ts +78 -0
  129. package/src/components/velero/runs.tsx +121 -0
  130. package/src/components/velero/shared.test.ts +84 -0
  131. package/src/components/velero/shared.tsx +423 -0
  132. package/src/components/velero/useVeleroSidebarWorkspace.test.tsx +28 -0
  133. package/src/components/velero/useVeleroSidebarWorkspace.ts +71 -0
  134. package/src/components/velero/velero.fixtures.ts +61 -0
  135. package/src/components/velero/workspaceRoute.ts +21 -0
  136. package/src/components/vulnerabilities/WorkloadVulnerabilitiesSection.tsx +179 -0
  137. package/src/components/vulnerabilities/parts.test.ts +72 -0
  138. package/src/components/vulnerabilities/parts.tsx +291 -0
  139. package/src/components/whats-new/WhatsNewDialog.test.tsx +6 -4
  140. package/src/components/whats-new/releaseNotes.ts +67 -1
  141. package/src/components/workload/WorkloadView.tsx +64 -27
  142. package/src/components/workspace/DrawerTrailBack.tsx +32 -0
  143. package/src/components/workspace/WorkspaceFrame.tsx +71 -0
  144. package/src/components/workspace/coverage.ts +61 -0
  145. package/src/components/workspace/layout.test.tsx +29 -1
  146. package/src/components/workspace/layout.tsx +15 -5
  147. package/src/components/workspace/sidebar.ts +9 -0
  148. package/src/components/workspace/useWorkspaceDrawer.ts +63 -0
  149. package/src/components/workspace/useWorkspaceNavigate.ts +21 -0
  150. package/src/desktop/AboutDialog.test.ts +12 -0
  151. package/src/desktop/AboutDialog.tsx +151 -0
  152. package/src/desktop/WindowsTitleBar.tsx +359 -0
  153. package/src/desktop/titleBar.test.ts +61 -0
  154. package/src/desktop/titleBar.ts +45 -0
  155. package/src/index.css +19 -0
  156. package/src/integrations/resourceHost.ts +5 -1
  157. package/src/integrations/resourceHosts.test.tsx +14 -2
  158. package/src/integrations/resourceHosts.tsx +22 -6
  159. package/src/integrations/workspaceRoute.ts +1 -1
  160. package/src/integrations/workspaceRoutes.test.ts +11 -0
  161. package/src/integrations/workspaceRoutes.ts +3 -1
  162. package/src/integrations/workspaceScreens.tsx +2 -0
  163. package/src/main.tsx +8 -0
  164. package/src/utils/desktop-zoom.test.ts +53 -0
  165. package/src/utils/desktop-zoom.ts +30 -0
  166. package/src/utils/staleAssetPrompt.test.tsx +76 -0
  167. package/src/utils/staleAssetPrompt.tsx +32 -0
@@ -0,0 +1,377 @@
1
+ import { useMutation, useQuery, useQueryClient, type UseQueryResult } from '@tanstack/react-query'
2
+ import type { VeleroScheduleActivityResponse, VeleroWorkspaceResponse } from '@skyhook-io/k8s-ui'
3
+ import { apiFetch, fetchJSON, useRadarFeature } from './client'
4
+ import { readErrorBody } from './httpErrors'
5
+ import { getApiBase } from './config'
6
+ import { shouldRetryRadarQuery } from './radarFeatures'
7
+
8
+ // /api/velero/workspace
9
+ //
10
+ // Every Velero installation the caller can read, with per-kind coverage. The
11
+ // server ignores the namespace picker, so nothing view-scoped is sent. The API
12
+ // base is in the key because Radar Hub points one query client at many
13
+ // clusters.
14
+ export function useVeleroWorkspace(options?: { enabled?: boolean }) {
15
+ const { guard, gatedKey } = useRadarFeature('veleroWorkspace')
16
+ const base = getApiBase()
17
+ return useQuery<VeleroWorkspaceResponse>({
18
+ queryKey: ['velero', 'workspace', base, ...gatedKey],
19
+ queryFn: ({ signal }) => guard(() => fetchJSON<VeleroWorkspaceResponse>('/velero/workspace', signal)),
20
+ enabled: options?.enabled ?? true,
21
+ staleTime: 10_000,
22
+ refetchInterval: 30_000,
23
+ // Keep the previous answer while refetching, but never another cluster's.
24
+ placeholderData: (prev, prevQuery) => (prevQuery?.queryKey[2] === base ? prev : undefined),
25
+ retry: shouldRetryRadarQuery,
26
+ })
27
+ }
28
+
29
+ // /api/velero/schedules/{namespace}/{name}/activity
30
+ //
31
+ // One Schedule's reading and its recent runs, for the Schedule drawer.
32
+ export function useVeleroScheduleActivity(namespace: string, name: string, options?: { enabled?: boolean }) {
33
+ const { guard, gatedKey } = useRadarFeature('veleroWorkspace')
34
+ const base = getApiBase()
35
+ return useQuery<VeleroScheduleActivityResponse>({
36
+ queryKey: ['velero', 'schedule-activity', base, namespace, name, ...gatedKey],
37
+ queryFn: ({ signal }) =>
38
+ guard(() =>
39
+ fetchJSON<VeleroScheduleActivityResponse>(
40
+ `/velero/schedules/${encodeURIComponent(namespace)}/${encodeURIComponent(name)}/activity`,
41
+ signal,
42
+ ),
43
+ ),
44
+ enabled: (options?.enabled ?? true) && !!namespace && !!name,
45
+ staleTime: 10_000,
46
+ refetchInterval: 30_000,
47
+ // Keep the previous answer only for the same schedule on the same cluster:
48
+ // another schedule's reading must never stand in for this one while it loads.
49
+ placeholderData: (prev, prevQuery) =>
50
+ prev && prevQuery?.queryKey[2] === base && prev.reading.namespace === namespace && prev.reading.name === name ? prev : undefined,
51
+ retry: shouldRetryRadarQuery,
52
+ })
53
+ }
54
+
55
+ // POST /api/velero/schedules/{namespace}/{name}/backup
56
+ //
57
+ // Creates a Backup from the schedule's template, bound to the version of the
58
+ // schedule the user reviewed: a schedule edited since is refused (409).
59
+ export function useVeleroBackupNow() {
60
+ const queryClient = useQueryClient()
61
+ return useMutation({
62
+ // backupName and submission (8–64 letters, digits or hyphens) are chosen
63
+ // when the confirmation opens. Sending the same confirmation again, with
64
+ // both unchanged, returns the backup it already created; without
65
+ // backupName each request creates a new backup.
66
+ mutationFn: async ({ namespace, name, resourceVersion, backupName, submission }: { namespace: string; name: string; resourceVersion: string; backupName?: string; submission: string }) => {
67
+ const response = await apiFetch(
68
+ `${getApiBase()}/velero/schedules/${encodeURIComponent(namespace)}/${encodeURIComponent(name)}/backup`,
69
+ { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ resourceVersion, name: backupName, submission }) },
70
+ )
71
+ if (!response.ok) {
72
+ const error = await readErrorBody(response)
73
+ throw new Error(error.error || `HTTP ${response.status}`)
74
+ }
75
+ return (await response.json()) as { namespace: string; name: string }
76
+ },
77
+ meta: { errorMessage: 'Could not start the backup' },
78
+ onSuccess: () => {
79
+ void queryClient.invalidateQueries({ queryKey: ['velero'] })
80
+ },
81
+ })
82
+ }
83
+
84
+ // POST /api/velero/schedules/{namespace}/{name}/{pause|resume}
85
+ //
86
+ // Sets spec.paused, bound to the version of the schedule the user reviewed (a
87
+ // schedule edited since is refused, 409). skipImmediately is written to the
88
+ // schedule: true skips the run due on resume, null leaves it to the server.
89
+ export function useVeleroSchedulePause() {
90
+ const queryClient = useQueryClient()
91
+ const { guard } = useRadarFeature('veleroSchedulePause')
92
+ return useMutation({
93
+ mutationFn: ({ namespace, name, paused, resourceVersion, skipImmediately = null }: {
94
+ namespace: string
95
+ name: string
96
+ paused: boolean
97
+ resourceVersion: string
98
+ skipImmediately?: boolean | null
99
+ }) =>
100
+ guard(() =>
101
+ fetchJSON<{ paused: boolean; changed: boolean }>(
102
+ `/velero/schedules/${encodeURIComponent(namespace)}/${encodeURIComponent(name)}/${paused ? 'pause' : 'resume'}`,
103
+ { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ resourceVersion, skipImmediately }) },
104
+ ),
105
+ ),
106
+ onSuccess: () => {
107
+ void queryClient.invalidateQueries({ queryKey: ['velero'] })
108
+ void queryClient.invalidateQueries({ queryKey: ['resource'] })
109
+ },
110
+ })
111
+ }
112
+
113
+ /** internal/velero RunRow: one Backup or Restore as its list and pages show it. */
114
+ export interface VeleroRunRow {
115
+ namespace: string
116
+ name: string
117
+ uid: string
118
+ phase?: string
119
+ created?: string
120
+ started?: string
121
+ completed?: string
122
+ expiration?: string
123
+ /** A Backup's velero.io/schedule-name label: the schedule that submitted it. Never set on a Restore. */
124
+ schedule?: string
125
+ storageLocation?: string
126
+ /** Velero's progress: items processed so far (a Restore's itemsRestored also counts skipped and failed items), of itemsTotal. Absent until Velero reports them. */
127
+ itemsDone?: number
128
+ itemsTotal?: number
129
+ errors: number
130
+ warnings: number
131
+ /** A Backup created by Radar's Back up now from its schedule. */
132
+ manual?: boolean
133
+ reason?: string
134
+ backupName?: string
135
+ /** A Restore's spec.scheduleName: restore from that schedule's newest completed backup. Unrelated to schedule. */
136
+ scheduleName?: string
137
+ namespaceMapping?: Record<string, string>
138
+ }
139
+
140
+ /** A Restore's row: its namespace selection is always sent, empty for every namespace in the backup. */
141
+ export interface VeleroRestoreRow extends VeleroRunRow {
142
+ includedNamespaces: string[]
143
+ excludedNamespaces: string[]
144
+ }
145
+
146
+ export interface VeleroRunsResponse<R extends VeleroRunRow = VeleroRunRow> {
147
+ observedAt: string
148
+ coverage: import('@skyhook-io/k8s-ui').VeleroKindCoverage
149
+ runs: R[]
150
+ /** The runs that passed the schedule or backup filter, before the cap; runs holds the newest. */
151
+ total: number
152
+ truncated?: boolean
153
+ }
154
+
155
+ // GET /api/velero/runs/{backups|restores}?namespace=&schedule=&backup=
156
+ //
157
+ // Every Backup or Restore the caller can read, newest first, read through the
158
+ // same per-kind access as the Velero views; `coverage` says what it covered.
159
+ // `schedule` and `backup` narrow the answer on the server: one schedule's
160
+ // runs, or the restores made from one backup.
161
+ export function useVeleroRuns(kind: 'restores', namespace?: string, filter?: { backup?: string }, options?: { enabled?: boolean }): UseQueryResult<VeleroRunsResponse<VeleroRestoreRow>>
162
+ export function useVeleroRuns(kind: 'backups', namespace?: string, filter?: { schedule?: string }, options?: { enabled?: boolean }): UseQueryResult<VeleroRunsResponse>
163
+ export function useVeleroRuns(kind: 'backups' | 'restores', namespace?: string, filter?: { schedule?: string; backup?: string }, options?: { enabled?: boolean }) {
164
+ const { guard, gatedKey } = useRadarFeature('veleroRuns')
165
+ const base = getApiBase()
166
+ const params = new URLSearchParams()
167
+ if (namespace) params.set('namespace', namespace)
168
+ if (filter?.schedule) params.set('schedule', filter.schedule)
169
+ if (filter?.backup) params.set('backup', filter.backup)
170
+ const query = params.toString()
171
+ return useQuery<VeleroRunsResponse>({
172
+ queryKey: ['velero', 'runs', base, kind, namespace ?? '', filter?.schedule ?? '', filter?.backup ?? '', ...gatedKey],
173
+ queryFn: ({ signal }) => guard(() => fetchJSON<VeleroRunsResponse>(`/velero/runs/${kind}${query ? `?${query}` : ''}`, signal)),
174
+ enabled: options?.enabled ?? true,
175
+ staleTime: 10_000,
176
+ refetchInterval: 30_000,
177
+ placeholderData: (prev, prevQuery) =>
178
+ prevQuery?.queryKey[2] === base && prevQuery?.queryKey[3] === kind && prevQuery?.queryKey[4] === (namespace ?? '') && prevQuery?.queryKey[5] === (filter?.schedule ?? '') && prevQuery?.queryKey[6] === (filter?.backup ?? '') ? prev : undefined,
179
+ retry: shouldRetryRadarQuery,
180
+ })
181
+ }
182
+
183
+ export interface VeleroDeletion {
184
+ state: 'waiting' | 'inProgress' | 'refused' | 'failed' | 'deleted' | 'unknown'
185
+ errors?: string[]
186
+ /** Absent when no request for the backup is retained: Velero removes a successful one with the backup, and any processed one after a day. */
187
+ request?: string
188
+ /** When the request was made; absent with request, or when it has no creation time. */
189
+ created?: string
190
+ /** A waiting request whose server Deployment has no pods (status.replicas is 0). Sent only when true, and checked only while waiting. */
191
+ serverStopped?: boolean
192
+ }
193
+
194
+ // POST /api/velero/backups/{namespace}/{name}/delete
195
+ //
196
+ // Asks Velero to delete a backup through a DeleteBackupRequest, bound to the
197
+ // backup the user reviewed (its UID). An open request is reused by the server.
198
+ export function useVeleroDeleteBackup() {
199
+ return useMutation({
200
+ // fetchJSON throws ApiError, so the dialog can tell a refusal (4xx) from a
201
+ // write whose outcome is unknown.
202
+ mutationFn: ({ namespace, name, uid }: { namespace: string; name: string; uid: string }) =>
203
+ fetchJSON<{ request: string }>(
204
+ `/velero/backups/${encodeURIComponent(namespace)}/${encodeURIComponent(name)}/delete`,
205
+ { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ uid }) },
206
+ ),
207
+ })
208
+ }
209
+
210
+ const SETTLED = ['refused', 'failed', 'deleted', 'unknown']
211
+
212
+ export function useVeleroBackupDeletion(namespace: string, name: string, uid: string, enabled = true) {
213
+ const { guard, gatedKey } = useRadarFeature('veleroDeleteBackup')
214
+ const base = getApiBase()
215
+ return useQuery<VeleroDeletion>({
216
+ queryKey: ['velero', 'deletion', base, namespace, name, uid, ...gatedKey],
217
+ queryFn: ({ signal }) => guard(() => fetchJSON<VeleroDeletion>(
218
+ `/velero/backups/${encodeURIComponent(namespace)}/${encodeURIComponent(name)}/deletion?uid=${encodeURIComponent(uid)}`, signal)),
219
+ enabled: enabled && !!uid && !!namespace && !!name,
220
+ refetchInterval: (query) => {
221
+ const status = (query.state.error as { status?: number } | null)?.status
222
+ if (status && status >= 400 && status < 500) return false
223
+ return query.state.data && SETTLED.includes(query.state.data.state) ? false : 2_000
224
+ },
225
+ retry: (count, error) => {
226
+ const status = (error as { status?: number } | null)?.status
227
+ return status && status >= 400 && status < 500 ? false : shouldRetryRadarQuery(count, error)
228
+ },
229
+ })
230
+ }
231
+ export interface VeleroRunContentsResponse {
232
+ groups: { kind: string; count: number; matched: number; items: { namespace: string; name: string; action?: string }[] }[]
233
+ total: number
234
+ matched: number
235
+ namespaces: string[]
236
+ actions: Record<string, number>
237
+ truncated: boolean
238
+ }
239
+
240
+ export type VeleroLogLevel = 'error' | 'warning' | 'info' | 'debug' | 'other'
241
+ export interface VeleroRunLogResponse {
242
+ lines: { number: number; level: VeleroLogLevel; text: string }[]
243
+ counts: Record<VeleroLogLevel, number>
244
+ matched: number
245
+ truncated: boolean
246
+ partial: boolean
247
+ decodedBytes: number
248
+ limit?: string
249
+ /** The levels the lines were selected from; with levels=auto, the server's choice. */
250
+ levels: VeleroLogLevel[]
251
+ }
252
+
253
+ function useVeleroRunArtifact<T>(kind: 'backups' | 'restores', namespace: string, name: string, artifact: 'contents' | 'log' | 'volumes', params: URLSearchParams) {
254
+ const { guard, gatedKey } = useRadarFeature(artifact === 'volumes' ? 'veleroRunVolumes' : 'veleroRunArtifacts')
255
+ const base = getApiBase()
256
+ const search = params.toString()
257
+ return useQuery<T>({
258
+ queryKey: ['velero', artifact, base, kind, namespace, name, search, ...gatedKey],
259
+ queryFn: ({ signal }) => guard(() => fetchJSON<T>(`/velero/${kind}/${encodeURIComponent(namespace)}/${encodeURIComponent(name)}/${artifact}?${search}`, { method: 'POST', signal })),
260
+ enabled: !!namespace && !!name,
261
+ // A tab or filter is the user's request; don't create DownloadRequests on focus or a timer.
262
+ staleTime: 0,
263
+ refetchOnWindowFocus: false,
264
+ refetchOnReconnect: false,
265
+ retry: false,
266
+ })
267
+ }
268
+
269
+ export function useVeleroRunContents(kind: 'backups' | 'restores', namespace: string, name: string, filters: { q: string; action: string; namespace: string }) {
270
+ return useVeleroRunArtifact<VeleroRunContentsResponse>(kind, namespace, name, 'contents', new URLSearchParams(filters))
271
+ }
272
+
273
+ export function useVeleroRunLog(kind: 'backups' | 'restores', namespace: string, name: string, levels: string, q: string) {
274
+ return useVeleroRunArtifact<VeleroRunLogResponse>(kind, namespace, name, 'log', new URLSearchParams({ levels, q }))
275
+ }
276
+
277
+ export interface VeleroVolumeDetails {
278
+ snapshotHandle?: string
279
+ size?: number
280
+ incrementalSize?: number
281
+ driver?: string
282
+ vscName?: string
283
+ operationID?: string
284
+ readyToUse?: boolean
285
+ volumeGroupSnapshotHandle?: string
286
+ dataMover?: string
287
+ uploaderType?: string
288
+ retainedSnapshot?: string
289
+ volumeType?: string
290
+ volumeAZ?: string
291
+ iops?: string
292
+ volumeName?: string
293
+ podName?: string
294
+ podNamespace?: string
295
+ nodeName?: string
296
+ phase?: string
297
+ }
298
+
299
+ export interface VeleroVolumeRecord {
300
+ pvcName?: string
301
+ pvcNamespace?: string
302
+ pvName?: string
303
+ method?: string
304
+ snapshotDataMoved: boolean
305
+ preserveLocalSnapshot?: boolean
306
+ result?: string
307
+ skipped?: boolean
308
+ skippedReason?: string
309
+ started?: string
310
+ completed?: string
311
+ csiSnapshotInfo?: VeleroVolumeDetails
312
+ snapshotDataMovementInfo?: VeleroVolumeDetails
313
+ nativeSnapshotInfo?: VeleroVolumeDetails
314
+ podVolumeInfo?: VeleroVolumeDetails
315
+ }
316
+
317
+ export interface VeleroRunVolumesResponse {
318
+ volumes: VeleroVolumeRecord[]
319
+ total: number
320
+ truncated: boolean
321
+ /** The run had finished when Radar read it, just before fetching the file; otherwise Velero may still rewrite the record. */
322
+ finishedAtRead: boolean
323
+ }
324
+
325
+ export interface VeleroVolumeOperation {
326
+ kind: string
327
+ name: string
328
+ pod?: string
329
+ podNamespace?: string
330
+ volume?: string
331
+ pvc?: string
332
+ pvcNamespace?: string
333
+ node?: string
334
+ phase?: string
335
+ bytesDone?: number
336
+ bytesTotal?: number
337
+ message?: string
338
+ started?: string
339
+ completed?: string
340
+ longRunning: boolean
341
+ nodeAgent?: 'running' | 'notRunning' | 'unknown'
342
+ }
343
+
344
+ export interface VeleroVolumeOperationsResponse {
345
+ observedAt: string
346
+ runPhase: string
347
+ coverage: Record<string, import('@skyhook-io/k8s-ui').VeleroKindCoverage>
348
+ operations: VeleroVolumeOperation[]
349
+ }
350
+
351
+ export function useVeleroRunVolumes(kind: 'backups' | 'restores', namespace: string, name: string) {
352
+ return useVeleroRunArtifact<VeleroRunVolumesResponse>(kind, namespace, name, 'volumes', new URLSearchParams())
353
+ }
354
+
355
+ export function isVeleroRunFinished(phase: string | undefined): boolean {
356
+ return phase !== undefined && ['Completed', 'Failed', 'PartiallyFailed', 'FailedValidation', 'Deleting'].includes(phase)
357
+ }
358
+
359
+ export function useVeleroVolumeOperations(kind: 'backups' | 'restores', namespace: string, name: string) {
360
+ const { guard, gatedKey } = useRadarFeature('veleroRunVolumes')
361
+ const base = getApiBase()
362
+ return useQuery<VeleroVolumeOperationsResponse>({
363
+ queryKey: ['velero', 'volume-operations', base, kind, namespace, name, ...gatedKey],
364
+ queryFn: ({ signal }) => guard(() => fetchJSON<VeleroVolumeOperationsResponse>(`/velero/${kind}/${encodeURIComponent(namespace)}/${encodeURIComponent(name)}/volume-operations`, signal)),
365
+ enabled: !!namespace && !!name,
366
+ staleTime: 10_000,
367
+ refetchInterval: (query) => {
368
+ const data = query.state.data
369
+ if (!data) return false
370
+ // Velero leaves finished operation objects in place, so only an
371
+ // unfinished one, a run still going or a kind still loading needs polling.
372
+ const settled = (phase?: string) => phase === 'Completed' || phase === 'Failed' || phase === 'Canceled'
373
+ return data.operations.some((row) => !settled(row.phase)) || Object.values(data.coverage).some((coverage) => coverage.state === 'syncing') || !isVeleroRunFinished(data.runPhase) ? 10_000 : false
374
+ },
375
+ retry: shouldRetryRadarQuery,
376
+ })
377
+ }
@@ -0,0 +1,313 @@
1
+ import { useQuery } from '@tanstack/react-query'
2
+ import type { ReadGap } from '@skyhook-io/k8s-ui/types/read-coverage'
3
+ import type { ResourceReadCoverage } from '@skyhook-io/k8s-ui/types/resource-coverage'
4
+ import type { APIResource } from '../types'
5
+ import { ApiError, fetchJSON, useRadarFeature } from './client'
6
+ import { readActionFor } from '@skyhook-io/k8s-ui/utils/read-actions'
7
+ import { getApiBase } from './config'
8
+ import { shouldRetryRadarQuery } from './radarFeatures'
9
+
10
+ // Mirrors internal/vulnerabilities/types.go.
11
+
12
+ /** 'summary' is the totals and coverage without rows, for a page that shows counts. */
13
+ export type VulnerabilityView = 'image' | 'fix' | 'cve' | 'workload' | 'summary'
14
+ export type VulnerabilitySeverity = 'critical' | 'high' | 'medium' | 'low' | 'unknown'
15
+
16
+ export interface VulnerabilityCounts {
17
+ critical: number
18
+ high: number
19
+ medium: number
20
+ low: number
21
+ unknown: number
22
+ }
23
+
24
+ export interface VulnerabilityWorkloadRef {
25
+ kind: string
26
+ group: string
27
+ namespace: string
28
+ name: string
29
+ container?: string
30
+ }
31
+
32
+ export interface VulnerabilityFinding {
33
+ id: string
34
+ severity: VulnerabilitySeverity
35
+ /** The scanner gave no severity; this is the CVSS rating of score. */
36
+ severityFromScore?: boolean
37
+ score?: number
38
+ package: string
39
+ installedVersion: string
40
+ fixedVersion?: string
41
+ /** The smallest fixed version above the installed one, when Radar can order the package's versions. */
42
+ fixTarget?: string
43
+ packageType?: string
44
+ title?: string
45
+ link?: string
46
+ }
47
+
48
+ export interface VulnerableImage {
49
+ id: string
50
+ image: string
51
+ digest?: string
52
+ os?: string
53
+ scannedAt: string
54
+ counts: VulnerabilityCounts
55
+ fixable: VulnerabilityCounts
56
+ matching: number
57
+ /** Past the request's findings budget: counts unknown, not zero. */
58
+ findingsUnread?: boolean
59
+ workloads: VulnerabilityWorkloadRef[]
60
+ workloadsTotal: number
61
+ findings: VulnerabilityFinding[]
62
+ findingsTotal: number
63
+ report: { kind: string; group?: string; namespace?: string; name: string }
64
+ }
65
+
66
+ export interface VulnerabilityCVEImage {
67
+ imageId: string
68
+ image: string
69
+ packages: { package: string; installedVersion: string; fixedVersion?: string; fixTarget?: string }[]
70
+ workloads: VulnerabilityWorkloadRef[]
71
+ workloadsTotal: number
72
+ }
73
+
74
+ export interface VulnerabilityCVE {
75
+ id: string
76
+ severity: VulnerabilitySeverity
77
+ score?: number
78
+ packages: string[]
79
+ fixable: boolean
80
+ /** Of `images`, the ones where every package the CVE is in has a fixed version. */
81
+ fixableImages: number
82
+ title?: string
83
+ link?: string
84
+ images: number
85
+ workloads: number
86
+ affected: VulnerabilityCVEImage[]
87
+ }
88
+
89
+ export interface VulnerabilityFix {
90
+ package: string
91
+ packageType?: string
92
+ /** The lowest listed release that fixes every listed CVE; absent when none can be chosen from the scanner's versions. */
93
+ to?: string
94
+ /** Each distinct fixed-version text the scanner wrote, when there is no target. */
95
+ fixedVersions?: string[]
96
+ from: string[]
97
+ severity: VulnerabilitySeverity
98
+ counts: VulnerabilityCounts
99
+ cves: string[]
100
+ cvesTotal: number
101
+ images: number
102
+ workloads: number
103
+ affected: { imageId: string; image: string; installedVersions: string[]; workloads: VulnerabilityWorkloadRef[]; workloadsTotal: number }[]
104
+ }
105
+
106
+ export interface VulnerabilityWorkloadContainer {
107
+ name: string
108
+ image: string
109
+ imageId?: string
110
+ scanned: boolean
111
+ scannedAt?: string
112
+ findingsUnread?: boolean
113
+ counts?: VulnerabilityCounts
114
+ fixable?: VulnerabilityCounts
115
+ }
116
+
117
+ export interface VulnerabilityWorkload {
118
+ kind: string
119
+ group: string
120
+ namespace: string
121
+ name: string
122
+ counts: VulnerabilityCounts
123
+ fixable: VulnerabilityCounts
124
+ containers: VulnerabilityWorkloadContainer[]
125
+ }
126
+
127
+ export interface VulnerabilitySummary {
128
+ imagesScanned: number
129
+ imagesClean: number
130
+ imagesUnscanned: number
131
+ imagesWithCritical: number
132
+ fixableCriticalHighCves: number
133
+ workloadsWithCriticalOrHigh: number
134
+ workloads: number
135
+ counts: VulnerabilityCounts
136
+ newestScan?: string
137
+ oldestScan?: string
138
+ }
139
+
140
+ /** A shared read gap; `kinds` names what wasn't read, absent meaning the reports themselves. */
141
+ export type VulnerabilityGap = ReadGap
142
+
143
+ export interface VulnerabilitiesResponse {
144
+ source: string
145
+ view: VulnerabilityView
146
+ summary: VulnerabilitySummary
147
+ images?: VulnerableImage[]
148
+ cves?: VulnerabilityCVE[]
149
+ workloads?: VulnerabilityWorkload[]
150
+ fixes?: VulnerabilityFix[]
151
+ /** Scanned images with no findings, kept out of the rows unless searched for. */
152
+ clean?: { id: string; image: string; scannedAt: string; workloads: VulnerabilityWorkloadRef[]; workloadsTotal: number; report: VulnerableImage['report'] }[]
153
+ /** Workloads whose every container is scanned and clean. */
154
+ cleanWorkloads?: VulnerabilityWorkloadRef[]
155
+ /** otherBuildScanned: Trivy's report is of another build of this tag, as after the tag moved. */
156
+ unscanned?: { image: string; otherBuildScanned?: boolean; workloads: VulnerabilityWorkloadRef[]; workloadsTotal: number }[]
157
+ coverage: {
158
+ complete: boolean
159
+ gaps: VulnerabilityGap[]
160
+ inactiveReports: number
161
+ truncated?: boolean
162
+ rowsOmitted?: number
163
+ cleanOmitted?: number
164
+ unscannedOmitted?: number
165
+ }
166
+ }
167
+
168
+ export interface VulnerabilitiesParams {
169
+ view: VulnerabilityView
170
+ namespaces?: string[]
171
+ severities?: VulnerabilitySeverity[]
172
+ fixableOnly?: boolean
173
+ query?: string
174
+ workload?: { kind: string; group?: string; namespace: string; name: string }
175
+ }
176
+
177
+ export interface Java4ShellFinding {
178
+ workload: VulnerabilityWorkloadRef
179
+ container: string
180
+ image: string
181
+ digest: string
182
+ version: string
183
+ fixedIn?: string
184
+ pods: number
185
+ vbmiPods: number
186
+ unknownCPUPods: number
187
+ mitigationDeclaredPods: number
188
+ }
189
+
190
+ export const JAVA4SHELL_CVE = 'CVE-2026-114938'
191
+
192
+ export interface Java4ShellUnassessed {
193
+ workload: VulnerabilityWorkloadRef
194
+ container: string
195
+ image: string
196
+ digest?: string
197
+ reason: string
198
+ pods: number
199
+ }
200
+
201
+ export interface Java4ShellResult {
202
+ findings: Java4ShellFinding[]
203
+ containers: number
204
+ matches: number
205
+ findingGroups: number
206
+ unassessed: Record<string, number>
207
+ unassessedRows: Java4ShellUnassessed[]
208
+ unassessedGroups: number
209
+ coverage: ResourceReadCoverage
210
+ workload?: VulnerabilityWorkloadRef
211
+ }
212
+
213
+ export function useJava4ShellCheck(namespaces: string[], context: string, workload?: VulnerabilityWorkloadRef) {
214
+ const { guard } = useRadarFeature('runtimeAdvisoryChecks')
215
+ const query = new URLSearchParams()
216
+ if (workload) {
217
+ query.set('workloadKind', workload.kind)
218
+ query.set('workloadGroup', workload.group)
219
+ query.set('workloadNamespace', workload.namespace)
220
+ query.set('workloadName', workload.name)
221
+ } else if (namespaces.length > 0) {
222
+ query.set('namespaces', [...namespaces].sort().join(','))
223
+ }
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' })),
228
+ enabled: false,
229
+ retry: false,
230
+ })
231
+ }
232
+
233
+ // What an answer is about, apart from its filters: the workload and the
234
+ // namespaces. An answer about another one is never shown as a placeholder.
235
+ function subjectOfPath(path: unknown): string {
236
+ if (typeof path !== 'string') return ''
237
+ const q = new URLSearchParams(path.split('?')[1] ?? '')
238
+ return [q.get('workloadKind'), q.get('workloadNamespace'), q.get('workloadName'), q.get('namespaces')].join('/')
239
+ }
240
+
241
+ /** The cluster doesn't serve the report kind: no scanner, not a failure. */
242
+ export function isKindUnknown(error: unknown): boolean {
243
+ return error instanceof ApiError && error.status === 404 && error.data?.error_code === 'kind_unknown'
244
+ }
245
+
246
+ /** A workload as the tab's `workload` URL filter writes it: Kind/namespace/name. */
247
+ export function workloadParam(w: { kind: string; namespace: string; name: string }): string {
248
+ return `${w.kind}/${w.namespace}/${w.name}`
249
+ }
250
+
251
+ export function parseWorkloadParam(value: string | null): { kind: string; namespace: string; name: string } | undefined {
252
+ const parts = (value ?? '').split('/')
253
+ if (parts.length !== 3 || parts.some((p) => p === '')) return undefined
254
+ return { kind: parts[0], namespace: parts[1], name: parts[2] }
255
+ }
256
+
257
+ // Trivy Operator's VulnerabilityReport is the one source the rollup reads;
258
+ // the Vulnerabilities tab, Home tile and drawer section show only when the
259
+ // cluster serves it.
260
+ export function hasVulnerabilityReports(resources: APIResource[] | undefined): boolean {
261
+ return !!resources?.some((r) => r.group === 'aquasecurity.github.io' && r.name === 'vulnerabilityreports')
262
+ }
263
+
264
+ export function vulnerabilitiesPath(p: VulnerabilitiesParams): string {
265
+ const params = new URLSearchParams()
266
+ params.set('view', p.view)
267
+ if (p.namespaces && p.namespaces.length > 0) params.set('namespaces', p.namespaces.join(','))
268
+ if (p.severities && p.severities.length > 0) params.set('severity', p.severities.join(','))
269
+ if (p.fixableOnly) params.set('fixable', '1')
270
+ if (p.query?.trim()) params.set('q', p.query.trim())
271
+ if (p.workload) {
272
+ params.set('workloadKind', p.workload.kind)
273
+ params.set('workloadNamespace', p.workload.namespace)
274
+ params.set('workloadName', p.workload.name)
275
+ if (p.workload.group) params.set('workloadGroup', p.workload.group)
276
+ }
277
+ return `/vulnerabilities?${params.toString()}`
278
+ }
279
+
280
+ // GET /api/vulnerabilities. Filters run server-side so the summary always
281
+ // describes the unfiltered scope and every surface (REST, MCP) filters alike.
282
+ export function useVulnerabilities(p: VulnerabilitiesParams, enabled = true) {
283
+ const { guard, gatedKey } = useRadarFeature('vulnerabilities')
284
+ const path = vulnerabilitiesPath(p)
285
+ return useQuery<VulnerabilitiesResponse>({
286
+ queryKey: ['vulnerabilities', path, ...gatedKey],
287
+ queryFn: ({ signal }) => guard(() => fetchJSON<VulnerabilitiesResponse>(path, signal)),
288
+ enabled,
289
+ // A read that settles by itself (the kind still syncing on a cold start,
290
+ // the connection just changed) keeps retrying, so callers show their
291
+ // loading state rather than an error.
292
+ retry: (failures, error) => (readSettles(error) ? failures < 8 : shouldRetryRadarQuery(failures, error)),
293
+ staleTime: 30_000,
294
+ // The tab's tables can run to megabytes and scans change hourly, so they
295
+ // refresh every five minutes; Home's totals and one workload's rows are
296
+ // small and stay at a minute.
297
+ refetchInterval: p.view === 'summary' || p.workload ? 60_000 : 300_000,
298
+ refetchIntervalInBackground: false,
299
+ // Keep showing the last answer, dimmed, while the tab's filters or view
300
+ // change (the summary is the same in every view; a caller shows rows
301
+ // only once data.view matches), but never carry one workload's or
302
+ // namespace scope's answer to another.
303
+ placeholderData: (prev, prevQuery) => (subjectOfPath(prevQuery?.queryKey[1]) === subjectOfPath(path) ? prev : undefined),
304
+ })
305
+ }
306
+
307
+ // Whether a failed read settles by itself: Radar still loading the kind, or
308
+ // its connection just changed. A 503 naming something to fix doesn't.
309
+ export function readSettles(error: unknown): boolean {
310
+ if (!(error instanceof ApiError)) return false
311
+ const code = error.data?.error_code
312
+ return error.status === 409 || (error.status === 503 && (code === undefined || readActionFor(code) === 'retry'))
313
+ }