@skyhook-io/radar-app 1.20.1 → 1.20.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 (81) hide show
  1. package/package.json +1 -1
  2. package/src/App.tsx +12 -7
  3. package/src/api/client.namespaceSwitch.hook.test.tsx +170 -1
  4. package/src/api/client.pauseDeployment.test.tsx +77 -0
  5. package/src/api/client.restartError.test.ts +14 -0
  6. package/src/api/client.revisionRefresh.test.tsx +44 -0
  7. package/src/api/client.rollbackError.test.ts +14 -0
  8. package/src/api/client.ts +218 -11
  9. package/src/api/networkAttachments.test.tsx +120 -0
  10. package/src/api/networkAttachments.ts +30 -0
  11. package/src/api/radarFeatures.test.ts +5 -0
  12. package/src/api/radarFeatures.ts +3 -0
  13. package/src/api/secretsStore.test.ts +33 -0
  14. package/src/api/secretsStore.ts +37 -0
  15. package/src/components/ConnectionErrorView.test.tsx +11 -0
  16. package/src/components/ConnectionErrorView.tsx +19 -0
  17. package/src/components/ContextSwitcher.tsx +9 -2
  18. package/src/components/applications/ApplicationsView.openResource.test.tsx +118 -0
  19. package/src/components/applications/ApplicationsView.tsx +8 -11
  20. package/src/components/cost/CostView.tsx +27 -9
  21. package/src/components/diagnose/InvestigationView.tsx +12 -3
  22. package/src/components/diagnose/investigationEvidence/adapters/helm.test.tsx +52 -0
  23. package/src/components/diagnose/investigationEvidence/adapters/helm.ts +10 -0
  24. package/src/components/diagnose/investigationEvidence/bodies/platform.tsx +82 -51
  25. package/src/components/diagnose/investigationEvidence/types.ts +5 -0
  26. package/src/components/dock/TerminalPreferences.query.test.tsx +57 -0
  27. package/src/components/dock/TerminalPreferences.test.tsx +68 -0
  28. package/src/components/dock/TerminalPreferences.tsx +73 -0
  29. package/src/components/gitops/GitOpsView.tsx +1 -9
  30. package/src/components/helm/HelmReleaseDrawer.tsx +24 -12
  31. package/src/components/helm/HelmView.tsx +5 -3
  32. package/src/components/helm/NotCheckedBadge.test.tsx +62 -0
  33. package/src/components/helm/NotCheckedBadge.tsx +39 -0
  34. package/src/components/helm/OwnedResources.test.tsx +86 -0
  35. package/src/components/helm/OwnedResources.tsx +65 -8
  36. package/src/components/home/ClusterHealthCard.heading.test.tsx +72 -0
  37. package/src/components/home/ClusterHealthCard.test.ts +44 -1
  38. package/src/components/home/ClusterHealthCard.tsx +22 -10
  39. package/src/components/home/HelmSummary.tsx +15 -15
  40. package/src/components/home/mcpToolCatalog.ts +2 -2
  41. package/src/components/resource/RightsizingStrip.test.ts +57 -0
  42. package/src/components/resource/RightsizingStrip.tsx +53 -4
  43. package/src/components/resources/ImageFilesystemModal.test.tsx +74 -6
  44. package/src/components/resources/ImageFilesystemModal.tsx +98 -6
  45. package/src/components/resources/PodFileUploadPanel.tsx +150 -0
  46. package/src/components/resources/PodFilesystemModal.tsx +246 -3
  47. package/src/components/resources/pod-file-upload.test.tsx +223 -0
  48. package/src/components/resources/pod-file-upload.ts +266 -0
  49. package/src/components/resources/renderers/HTTPRouteRenderer.test.tsx +50 -0
  50. package/src/components/resources/renderers/HTTPRouteRenderer.tsx +27 -0
  51. package/src/components/resources/renderers/PodRenderer.tsx +26 -1
  52. package/src/components/resources/renderers/SecretProviderClassRenderer.tsx +25 -0
  53. package/src/components/rightsizing/RightsizingScanView.tsx +16 -1
  54. package/src/components/rightsizing/model.test.ts +11 -0
  55. package/src/components/rightsizing/model.ts +3 -1
  56. package/src/components/rightsizing/presentation.test.ts +46 -0
  57. package/src/components/rightsizing/presentation.ts +17 -2
  58. package/src/components/traffic/TrafficView.tsx +27 -27
  59. package/src/components/traffic/trafficFilters.test.ts +18 -1
  60. package/src/components/traffic/trafficFilters.ts +30 -1
  61. package/src/components/ui/Omnibar.tsx +4 -1
  62. package/src/components/ui/RadarOmnibar.test.tsx +55 -2
  63. package/src/components/ui/RadarOmnibar.tsx +7 -1
  64. package/src/components/ui/SearchSyntaxHelp.test.tsx +9 -2
  65. package/src/components/ui/SearchSyntaxHelp.tsx +3 -2
  66. package/src/components/ui/UpdateNotification.test.tsx +23 -1
  67. package/src/components/ui/UpdateNotification.tsx +26 -2
  68. package/src/components/ui/omnibar-match.test.ts +7 -0
  69. package/src/components/ui/omnibar-match.ts +1 -0
  70. package/src/components/ui/searchCoverageNote.test.ts +17 -0
  71. package/src/components/ui/searchCoverageNote.ts +31 -7
  72. package/src/components/useContextSwitchFlow.tsx +9 -1
  73. package/src/components/workload/NodeCertificateEvidence.test.tsx +51 -0
  74. package/src/components/workload/NodeCertificateEvidence.tsx +44 -0
  75. package/src/components/workload/WorkloadView.tsx +51 -11
  76. package/src/context/ConnectionContext.test.ts +1 -0
  77. package/src/context/ConnectionContext.tsx +2 -2
  78. package/src/integrations/resourceHosts.test.tsx +2 -2
  79. package/src/integrations/resourceHosts.tsx +4 -0
  80. package/src/utils/namespacePick.test.ts +87 -0
  81. package/src/utils/namespacePick.ts +88 -0
@@ -0,0 +1,223 @@
1
+ import { describe, expect, it } from 'vitest'
2
+ import { renderToStaticMarkup } from 'react-dom/server'
3
+ import { MemoryRouter } from 'react-router-dom'
4
+ import type { FileNode } from '../../types'
5
+ import {
6
+ canShowUpload,
7
+ fileMountHint,
8
+ isValidUploadName,
9
+ oversizeMessage,
10
+ POD_FILE_PERSISTENCE_NOTE,
11
+ uploadBlockedHint,
12
+ uploadResponseError,
13
+ uploadTarget,
14
+ } from './pod-file-upload'
15
+ import { PodFileUploadButton, PodFileUploadNotices, PodFileUploadStatus } from './PodFileUploadPanel'
16
+
17
+ describe('canShowUpload', () => {
18
+ it('needs exec and a server that serves the endpoint', () => {
19
+ expect(canShowUpload({ canExec: true, featureSupported: true })).toBe(true)
20
+ expect(canShowUpload({ canExec: false, featureSupported: true })).toBe(false)
21
+ expect(canShowUpload({ canExec: true, featureSupported: false })).toBe(false)
22
+ })
23
+ })
24
+
25
+ const pod = {
26
+ spec: {
27
+ containers: [
28
+ {
29
+ name: 'app',
30
+ volumeMounts: [
31
+ { name: 'cfg', mountPath: '/etc/app' },
32
+ { name: 'tls', mountPath: '/etc/tls/' },
33
+ { name: 'data', mountPath: '/data' },
34
+ { name: 'shared', mountPath: '/shared', readOnly: true },
35
+ { name: 'one', mountPath: '/etc/nginx/nginx.conf' },
36
+ { name: 'proj', mountPath: '/var/run/proj' },
37
+ ],
38
+ },
39
+ { name: 'locked', securityContext: { readOnlyRootFilesystem: true }, volumeMounts: [{ name: 'data', mountPath: '/data' }] },
40
+ ],
41
+ initContainers: [
42
+ { name: 'sidecar', restartPolicy: 'Always', volumeMounts: [{ name: 'cfg', mountPath: '/config' }] },
43
+ ],
44
+ volumes: [
45
+ { name: 'cfg', configMap: { name: 'app-config' } },
46
+ { name: 'tls', secret: { secretName: 'app-tls' } },
47
+ { name: 'data', emptyDir: {} },
48
+ { name: 'shared', persistentVolumeClaim: { claimName: 'shared' } },
49
+ { name: 'one', configMap: { name: 'nginx' } },
50
+ { name: 'proj', projected: { sources: [{ secret: { name: 'only-one' } }] } },
51
+ ],
52
+ },
53
+ }
54
+
55
+ describe('uploadBlockedHint', () => {
56
+ it('blocks ConfigMap and Secret mounts and names their source', () => {
57
+ expect(uploadBlockedHint(pod, 'app', '/etc/app')?.source).toEqual({ kind: 'ConfigMap', name: 'app-config' })
58
+ expect(uploadBlockedHint(pod, 'app', '/etc/app/..data')?.source).toEqual({ kind: 'ConfigMap', name: 'app-config' })
59
+ expect(uploadBlockedHint(pod, 'app', '/etc/tls')?.source).toEqual({ kind: 'Secret', name: 'app-tls' })
60
+ })
61
+
62
+ it('names the single source of a projected volume', () => {
63
+ expect(uploadBlockedHint(pod, 'app', '/var/run/proj')?.source).toEqual({ kind: 'Secret', name: 'only-one' })
64
+ })
65
+
66
+ it('blocks read-only mounts', () => {
67
+ expect(uploadBlockedHint(pod, 'app', '/shared/x')?.reason).toMatch(/read-only/)
68
+ })
69
+
70
+ it('allows writable volumes and an unmounted path on a writable root', () => {
71
+ expect(uploadBlockedHint(pod, 'app', '/data')).toBeNull()
72
+ expect(uploadBlockedHint(pod, 'app', '/tmp')).toBeNull()
73
+ expect(uploadBlockedHint(pod, 'app', '/etc')).toBeNull()
74
+ expect(uploadBlockedHint(pod, 'app', '/etc/application')).toBeNull()
75
+ })
76
+
77
+ it('blocks a read-only root filesystem outside writable volumes', () => {
78
+ expect(uploadBlockedHint(pod, 'locked', '/tmp')?.reason).toMatch(/readOnlyRootFilesystem/)
79
+ expect(uploadBlockedHint(pod, 'locked', '/data/sub')).toBeNull()
80
+ })
81
+
82
+ it('reads mounts of native sidecars', () => {
83
+ expect(uploadBlockedHint(pod, 'sidecar', '/config')?.source).toEqual({ kind: 'ConfigMap', name: 'app-config' })
84
+ })
85
+
86
+ it('gives no hint for an unknown container or missing pod', () => {
87
+ expect(uploadBlockedHint(pod, 'nope', '/etc/app')).toBeNull()
88
+ expect(uploadBlockedHint(undefined, 'app', '/etc/app')).toBeNull()
89
+ })
90
+ })
91
+
92
+ describe('fileMountHint', () => {
93
+ it('flags a file mounted on its own', () => {
94
+ const hint = fileMountHint(pod, 'app', '/etc/nginx/nginx.conf')
95
+ expect(hint?.source).toEqual({ kind: 'ConfigMap', name: 'nginx' })
96
+ expect(fileMountHint(pod, 'app', '/etc/nginx/other.conf')).toBeNull()
97
+ })
98
+ })
99
+
100
+ describe('uploadTarget', () => {
101
+ const listing: FileNode = {
102
+ name: 'etc',
103
+ path: '/etc',
104
+ type: 'dir',
105
+ children: [
106
+ { name: 'a.conf', path: '/etc/a.conf', type: 'file' },
107
+ { name: 'conf.d', path: '/etc/conf.d', type: 'dir' },
108
+ { name: 'link', path: '/etc/link', type: 'symlink', linkTarget: '/x' },
109
+ ],
110
+ }
111
+
112
+ it('asks before replacing an existing file', () => {
113
+ expect(uploadTarget(listing, 'a.conf')).toEqual({ kind: 'replace' })
114
+ })
115
+
116
+ it('uploads a new name straight away', () => {
117
+ expect(uploadTarget(listing, 'b.conf')).toEqual({ kind: 'new' })
118
+ })
119
+
120
+ it('refuses directories and symlinks', () => {
121
+ expect(uploadTarget(listing, 'conf.d').kind).toBe('refuse')
122
+ expect(uploadTarget(listing, 'link').kind).toBe('refuse')
123
+ })
124
+ })
125
+
126
+ describe('isValidUploadName', () => {
127
+ it('matches what the server accepts', () => {
128
+ expect(isValidUploadName('app.conf')).toBe(true)
129
+ expect(isValidUploadName('-rf')).toBe(true)
130
+ for (const bad of ['', '.', '..', 'a/b', 'a\0b', 'x'.repeat(256)]) {
131
+ expect(isValidUploadName(bad)).toBe(false)
132
+ }
133
+ })
134
+ })
135
+
136
+ describe('oversizeMessage', () => {
137
+ it('refuses a file over the advertised cap before sending it', () => {
138
+ expect(oversizeMessage(200 * 1024 * 1024)).toMatch(/limited to 100/)
139
+ expect(oversizeMessage(100 * 1024 * 1024)).toBeNull()
140
+ expect(oversizeMessage(10, 5)).toMatch(/limited to/)
141
+ })
142
+ })
143
+
144
+ describe('upload controls', () => {
145
+ it('disables the button under a known read-only mount and says why', () => {
146
+ const html = renderToStaticMarkup(
147
+ <PodFileUploadButton blocked={{ reason: '/etc/app is a ConfigMap volume.' }} busy={false} onClick={() => {}} />,
148
+ )
149
+ expect(html).toMatch(/<button[^>]* disabled=""/)
150
+ })
151
+
152
+ it('disables the button while the listing for the selected container loads', () => {
153
+ const html = renderToStaticMarkup(<PodFileUploadButton blocked={null} busy={false} loading onClick={() => {}} />)
154
+ expect(html).toMatch(/<button[^>]* disabled=""/)
155
+ })
156
+
157
+ it('enables the button when nothing blocks it', () => {
158
+ const html = renderToStaticMarkup(<PodFileUploadButton blocked={null} busy={false} onClick={() => {}} />)
159
+ expect(html).not.toMatch(/<button[^>]* disabled=""/)
160
+ })
161
+
162
+ it('shows the persistence note verbatim and links to the blocking source', () => {
163
+ const html = renderToStaticMarkup(
164
+ <MemoryRouter>
165
+ <PodFileUploadNotices
166
+ namespace="prod"
167
+ blocked={{ reason: 'ConfigMap volume', source: { kind: 'ConfigMap', name: 'app-config' } }}
168
+ onNavigateAway={() => {}}
169
+ />
170
+ </MemoryRouter>,
171
+ )
172
+ expect(html).toContain(POD_FILE_PERSISTENCE_NOTE.replace(/'/g, '&#x27;'))
173
+ expect(html).toContain('href="/resources/configmaps?resource=prod%2Fapp-config"')
174
+ })
175
+
176
+ it('asks for confirmation before replacing', () => {
177
+ const html = renderToStaticMarkup(
178
+ <PodFileUploadStatus
179
+ state={{ phase: 'confirm', name: 'a.conf', dir: '/etc', size: 10 }}
180
+ onConfirmReplace={() => {}}
181
+ onCancel={() => {}}
182
+ onDismiss={() => {}}
183
+ />,
184
+ )
185
+ expect(html).toContain('Replace a.conf?')
186
+ expect(html).toContain('/etc/a.conf already exists')
187
+ expect(html).toContain('>Replace<')
188
+ })
189
+
190
+ it('keeps uploading and saved distinct', () => {
191
+ const uploading = renderToStaticMarkup(
192
+ <PodFileUploadStatus state={{ phase: 'uploading', name: 'a', dir: '/', sent: 50, total: 100 }} onConfirmReplace={() => {}} onCancel={() => {}} onDismiss={() => {}} />,
193
+ )
194
+ expect(uploading).toContain('aria-valuenow="50"')
195
+ expect(uploading).toContain('>Cancel<')
196
+ const saving = renderToStaticMarkup(
197
+ <PodFileUploadStatus state={{ phase: 'saving', name: 'a', dir: '/' }} onConfirmReplace={() => {}} onCancel={() => {}} onDismiss={() => {}} />,
198
+ )
199
+ expect(saving).toContain('Saving a')
200
+ expect(saving).not.toContain('>Cancel<')
201
+ const saved = renderToStaticMarkup(
202
+ <PodFileUploadStatus state={{ phase: 'saved', path: '/a', replaced: false }} onConfirmReplace={() => {}} onCancel={() => {}} onDismiss={() => {}} />,
203
+ )
204
+ expect(saved).toContain('Saved /a')
205
+ })
206
+ })
207
+
208
+ describe('uploadResponseError', () => {
209
+ it('blames a proxy only when a 413 carries no Radar error body', () => {
210
+ const fromProxy = uploadResponseError(413, null)
211
+ expect(fromProxy.message).toMatch(/proxy/)
212
+ expect(fromProxy.code).toBe('file_too_large')
213
+
214
+ const fromRadar = uploadResponseError(413, { error: 'Uploads are limited to 104857600 bytes', error_code: 'file_too_large' })
215
+ expect(fromRadar.message).toBe('Uploads are limited to 104857600 bytes')
216
+ expect(fromRadar.message).not.toMatch(/proxy/)
217
+ })
218
+
219
+ it('keeps other failures as before', () => {
220
+ expect(uploadResponseError(500, null).message).toBe('Upload failed (HTTP 500)')
221
+ expect(uploadResponseError(409, { error: 'x exists', error_code: 'file_exists' }).code).toBe('file_exists')
222
+ })
223
+ })
@@ -0,0 +1,266 @@
1
+ import type { FileNode } from '../../types'
2
+ import { apiUrl, getAuthHeaders, getCredentialsMode } from '../../api/config'
3
+ import { formatBytes } from '../../utils/format'
4
+
5
+ export const POD_FILE_PERSISTENCE_NOTE =
6
+ "Changes apply to the running container immediately. Files in the container's own filesystem are lost when it's recreated; files on volumes may persist. For lasting changes, update the source (image, ConfigMap, manifest)."
7
+
8
+ /** Mirrors the server's podFileUploadMaxBytes, so an oversize file is refused before it is sent. */
9
+ export const POD_FILE_UPLOAD_MAX_BYTES = 100 * 1024 * 1024
10
+
11
+ export interface UploadGateInput {
12
+ canExec: boolean
13
+ featureSupported: boolean
14
+ }
15
+
16
+ /**
17
+ * Uploads ride on exec: anyone who can exec can already write through the
18
+ * terminal. The feature check keeps them off an older Radar without the endpoint.
19
+ */
20
+ export function canShowUpload({ canExec, featureSupported }: UploadGateInput): boolean {
21
+ return canExec && featureSupported
22
+ }
23
+
24
+ interface VolumeMountLike {
25
+ name?: string
26
+ mountPath?: string
27
+ readOnly?: boolean
28
+ }
29
+
30
+ interface ContainerLike {
31
+ name?: string
32
+ volumeMounts?: VolumeMountLike[]
33
+ securityContext?: { readOnlyRootFilesystem?: boolean }
34
+ }
35
+
36
+ interface ProjectionLike {
37
+ configMap?: { name?: string }
38
+ secret?: { name?: string }
39
+ }
40
+
41
+ interface VolumeLike {
42
+ name?: string
43
+ configMap?: { name?: string }
44
+ secret?: { secretName?: string }
45
+ projected?: { sources?: ProjectionLike[] }
46
+ downwardAPI?: object
47
+ }
48
+
49
+ interface PodLike {
50
+ spec?: {
51
+ containers?: ContainerLike[]
52
+ initContainers?: ContainerLike[]
53
+ ephemeralContainers?: ContainerLike[]
54
+ volumes?: VolumeLike[]
55
+ }
56
+ }
57
+
58
+ export interface MountSource {
59
+ kind: 'ConfigMap' | 'Secret'
60
+ name: string
61
+ }
62
+
63
+ export interface MountHint {
64
+ reason: string
65
+ source?: MountSource
66
+ }
67
+
68
+ function findContainer(pod: unknown, container: string): ContainerLike | undefined {
69
+ const spec = (pod as PodLike | undefined)?.spec ?? {}
70
+ // Native sidecars are init containers with restartPolicy Always; they are
71
+ // browsable, so their mounts count too.
72
+ for (const list of [spec.containers, spec.initContainers, spec.ephemeralContainers]) {
73
+ const found = (list ?? []).find((c) => c?.name === container)
74
+ if (found) return found
75
+ }
76
+ return undefined
77
+ }
78
+
79
+ function covers(mountPath: string, dir: string): boolean {
80
+ const mp = mountPath.length > 1 ? mountPath.replace(/\/+$/, '') : mountPath
81
+ return mp === '/' || dir === mp || dir.startsWith(mp + '/')
82
+ }
83
+
84
+ function managedVolumeHint(volume: VolumeLike | undefined, mountPath: string): MountHint | null {
85
+ if (volume?.configMap) {
86
+ return {
87
+ reason: `${mountPath} is a ConfigMap volume. Kubernetes manages these files and they are read-only; change the ConfigMap instead.`,
88
+ source: volume.configMap.name ? { kind: 'ConfigMap', name: volume.configMap.name } : undefined,
89
+ }
90
+ }
91
+ if (volume?.secret) {
92
+ return {
93
+ reason: `${mountPath} is a Secret volume. Kubernetes manages these files and they are read-only; change the Secret instead.`,
94
+ source: volume.secret.secretName ? { kind: 'Secret', name: volume.secret.secretName } : undefined,
95
+ }
96
+ }
97
+ if (volume?.projected) {
98
+ const sources = volume.projected.sources ?? []
99
+ const single = sources.length === 1 ? sources[0] : undefined
100
+ let source: MountSource | undefined
101
+ if (single?.configMap?.name) source = { kind: 'ConfigMap', name: single.configMap.name }
102
+ else if (single?.secret?.name) source = { kind: 'Secret', name: single.secret.name }
103
+ return {
104
+ reason: `${mountPath} is a projected volume. Kubernetes manages these files and they are read-only; change their source instead.`,
105
+ source,
106
+ }
107
+ }
108
+ if (volume?.downwardAPI) {
109
+ return { reason: `${mountPath} is a downward API volume. Kubernetes writes these files from the pod's own fields.` }
110
+ }
111
+ return null
112
+ }
113
+
114
+ /**
115
+ * Why uploading into `dir` of `container` cannot work, read from the pod spec,
116
+ * or null when nothing in the spec says so. A hint only: the server is the
117
+ * authority and reports what actually happened.
118
+ */
119
+ export function uploadBlockedHint(pod: unknown, container: string, dir: string): MountHint | null {
120
+ const c = findContainer(pod, container)
121
+ if (!c) return null
122
+ const volumes = (pod as PodLike | undefined)?.spec?.volumes ?? []
123
+ const mounts = (c.volumeMounts ?? [])
124
+ .filter((m): m is VolumeMountLike & { mountPath: string } => typeof m?.mountPath === 'string' && covers(m.mountPath, dir))
125
+ .sort((a, b) => b.mountPath.length - a.mountPath.length)
126
+ const mount = mounts[0]
127
+ if (mount) {
128
+ const volume = volumes.find((v) => v?.name === mount.name)
129
+ const managed = managedVolumeHint(volume, mount.mountPath)
130
+ if (managed) return managed
131
+ if (mount.readOnly) return { reason: `${mount.mountPath} is mounted read-only.` }
132
+ return null
133
+ }
134
+ if (c.securityContext?.readOnlyRootFilesystem) {
135
+ return { reason: "This container's root filesystem is read-only (readOnlyRootFilesystem), and this directory is not on a writable volume." }
136
+ }
137
+ return null
138
+ }
139
+
140
+ /** A volume mounted onto exactly `filePath` (a subPath file mount), which no rename can replace. */
141
+ export function fileMountHint(pod: unknown, container: string, filePath: string): MountHint | null {
142
+ const c = findContainer(pod, container)
143
+ const mount = (c?.volumeMounts ?? []).find((m) => m?.mountPath === filePath)
144
+ if (!mount) return null
145
+ const volume = (pod as PodLike | undefined)?.spec?.volumes?.find((v) => v?.name === mount.name)
146
+ const managed = managedVolumeHint(volume, filePath)
147
+ return {
148
+ reason: `${filePath} is mounted into the container on its own, so it cannot be replaced here.${managed?.source ? ` Change the ${managed.source.kind} instead.` : ''}`,
149
+ source: managed?.source,
150
+ }
151
+ }
152
+
153
+ export type UploadTarget =
154
+ | { kind: 'new' }
155
+ | { kind: 'replace' }
156
+ | { kind: 'refuse'; reason: string }
157
+
158
+ /** What uploading `name` into the listed directory would do, from the listing. */
159
+ export function uploadTarget(listing: FileNode | undefined, name: string): UploadTarget {
160
+ const existing = listing?.children?.find((c) => c.name === name)
161
+ if (!existing) return { kind: 'new' }
162
+ if (existing.type === 'dir') return { kind: 'refuse', reason: `${name} is a directory here.` }
163
+ if (existing.type === 'symlink') return { kind: 'refuse', reason: `${name} is a symlink here; uploads never follow symlinks.` }
164
+ return { kind: 'replace' }
165
+ }
166
+
167
+ /** Why a file is over the upload cap, or null when it fits. */
168
+ export function oversizeMessage(size: number, max: number = POD_FILE_UPLOAD_MAX_BYTES): string | null {
169
+ if (size <= max) return null
170
+ return `This file is ${formatBytes(size)}; uploads on this Radar are limited to ${formatBytes(max)}.`
171
+ }
172
+
173
+ /** A single path segment the server will accept as a file name. */
174
+ export function isValidUploadName(name: string): boolean {
175
+ if (name === '' || name === '.' || name === '..') return false
176
+ if (name.includes('/') || name.includes('\0')) return false
177
+ return new TextEncoder().encode(name).length <= 255
178
+ }
179
+
180
+ export interface UploadResult {
181
+ path: string
182
+ size: number
183
+ replaced: boolean
184
+ }
185
+
186
+ export class PodFileUploadError extends Error {
187
+ readonly code: string
188
+ readonly status: number
189
+ constructor(message: string, code: string, status: number) {
190
+ super(message)
191
+ this.name = 'PodFileUploadError'
192
+ this.code = code
193
+ this.status = status
194
+ }
195
+ }
196
+
197
+ // A 413 without Radar's own error body was refused before it reached Radar,
198
+ // usually by a proxy with a smaller request size limit than Radar's.
199
+ export function uploadResponseError(status: number, body: { error?: string; error_code?: string } | null): PodFileUploadError {
200
+ if (status === 413 && !body?.error) {
201
+ return new PodFileUploadError(
202
+ 'The upload was rejected as too large, possibly by a proxy in front of Radar. If so, that proxy\'s request size limit needs raising for uploads.',
203
+ 'file_too_large',
204
+ status,
205
+ )
206
+ }
207
+ return new PodFileUploadError(body?.error || `Upload failed (HTTP ${status})`, body?.error_code || 'upload_failed', status)
208
+ }
209
+
210
+ export const UPLOAD_CANCELLED = 'upload_cancelled'
211
+
212
+ export interface UploadRequest {
213
+ namespace: string
214
+ podName: string
215
+ container: string
216
+ dir: string
217
+ file: Blob
218
+ name: string
219
+ overwrite: boolean
220
+ onProgress?: (sent: number, total: number) => void
221
+ signal?: AbortSignal
222
+ }
223
+
224
+ /**
225
+ * Sends one file. XHR rather than fetch because fetch reports no upload
226
+ * progress.
227
+ */
228
+ export function uploadPodFile(req: UploadRequest): Promise<UploadResult> {
229
+ const params = new URLSearchParams({ container: req.container, dir: req.dir, name: req.name })
230
+ if (req.overwrite) params.set('overwrite', 'true')
231
+ const url = apiUrl(`/pods/${encodeURIComponent(req.namespace)}/${encodeURIComponent(req.podName)}/files/upload?${params}`)
232
+
233
+ return new Promise((resolve, reject) => {
234
+ const xhr = new XMLHttpRequest()
235
+ xhr.open('POST', url)
236
+ xhr.withCredentials = getCredentialsMode() === 'include'
237
+ for (const [k, v] of Object.entries(getAuthHeaders())) xhr.setRequestHeader(k, v)
238
+ xhr.setRequestHeader('Content-Type', 'application/octet-stream')
239
+ xhr.upload.onprogress = (e) => {
240
+ if (e.lengthComputable) req.onProgress?.(e.loaded, e.total)
241
+ }
242
+ xhr.onload = () => {
243
+ let body: { error?: string; error_code?: string } & Partial<UploadResult> | null = null
244
+ try {
245
+ body = JSON.parse(xhr.responseText)
246
+ } catch {
247
+ // fall through with the status alone
248
+ }
249
+ if (xhr.status >= 200 && xhr.status < 300 && body) {
250
+ resolve(body as UploadResult)
251
+ return
252
+ }
253
+ reject(uploadResponseError(xhr.status, body))
254
+ }
255
+ xhr.onerror = () => reject(new PodFileUploadError('The upload could not reach Radar', 'network_error', 0))
256
+ xhr.onabort = () => reject(new PodFileUploadError('Upload cancelled', UPLOAD_CANCELLED, 0))
257
+ if (req.signal) {
258
+ if (req.signal.aborted) {
259
+ xhr.abort()
260
+ return
261
+ }
262
+ req.signal.addEventListener('abort', () => xhr.abort(), { once: true })
263
+ }
264
+ xhr.send(req.file)
265
+ })
266
+ }
@@ -0,0 +1,50 @@
1
+ // @vitest-environment jsdom
2
+ import { act } from 'react'
3
+ import { createRoot } from 'react-dom/client'
4
+ import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
5
+ import { describe, expect, it, vi } from 'vitest'
6
+ import { HTTPRouteRenderer } from './HTTPRouteRenderer'
7
+
8
+ vi.stubGlobal('IS_REACT_ACT_ENVIRONMENT', true)
9
+
10
+ const mock = vi.hoisted(() => ({ reads: [] as unknown[][], responses: new Map<string, () => Promise<unknown>>() }))
11
+ vi.mock('../../../api/client', () => ({
12
+ resourceQueryOptions: (kind: string, namespace: string, name: string, group: string) => {
13
+ mock.reads.push([kind, namespace, name, group])
14
+ return { queryKey: ['resource', kind, namespace, name, group], queryFn: mock.responses.get(`${namespace}/${name}`)!, retry: false }
15
+ },
16
+ }))
17
+
18
+ const route = {
19
+ metadata: { name: 'storefront', namespace: 'shop' },
20
+ spec: { parentRefs: [{ name: 'main-gw' }], hostnames: ['store.example.com'], rules: [] },
21
+ }
22
+
23
+ async function mount() {
24
+ const element = document.createElement('div')
25
+ document.body.append(element)
26
+ const root = createRoot(element)
27
+ const client = new QueryClient()
28
+ await act(async () => root.render(<QueryClientProvider client={client}><HTTPRouteRenderer data={route} /></QueryClientProvider>))
29
+ await act(async () => { await new Promise(r => setTimeout(r, 0)) })
30
+ return { element, done: async () => { await act(async () => root.unmount()); element.remove() } }
31
+ }
32
+
33
+ describe('HTTPRoute host wrapper', () => {
34
+ it('reads the parent Gateway from the resource envelope and opens with its listener scheme', async () => {
35
+ mock.reads = []
36
+ mock.responses.set('shop/main-gw', async () => ({ resource: { spec: { listeners: [{ name: 'https', protocol: 'HTTPS', port: 443 }] } }, relationships: {} }))
37
+ const { element, done } = await mount()
38
+ expect(new Set(mock.reads.map(r => r.join('|')))).toEqual(new Set(['gateways|shop|main-gw|gateway.networking.k8s.io']))
39
+ expect(element.querySelector('a[target="_blank"]')?.getAttribute('href')).toBe('https://store.example.com')
40
+ await done()
41
+ })
42
+
43
+ it('falls back to copying the hostname when the Gateway read fails', async () => {
44
+ mock.responses.set('shop/main-gw', async () => { throw new Error('forbidden') })
45
+ const { element, done } = await mount()
46
+ expect(element.querySelector('a[target="_blank"]')).toBeNull()
47
+ expect(element.querySelector('button[aria-label^="Copy hostname"]')).not.toBeNull()
48
+ await done()
49
+ })
50
+ })
@@ -0,0 +1,27 @@
1
+ import { useQueries } from '@tanstack/react-query'
2
+ import { HTTPRouteRenderer as BaseHTTPRouteRenderer } from '@skyhook-io/k8s-ui/components/resources/renderers/HTTPRouteRenderer'
3
+ import { routeGateways, type GatewayLookup, type GatewayObject } from '@skyhook-io/k8s-ui/utils/host-url'
4
+ import { resourceQueryOptions } from '../../../api/client'
5
+ import type { ResourceRef } from '../../../types'
6
+
7
+ const GATEWAY_GROUP = 'gateway.networking.k8s.io'
8
+
9
+ interface HTTPRouteRendererProps {
10
+ data: any
11
+ onNavigate?: (ref: ResourceRef) => void
12
+ }
13
+
14
+ /** Reads the route's parent Gateways so its hostnames can open with the
15
+ * scheme their listeners serve. Shares the Gateway drawer's query. */
16
+ export function HTTPRouteRenderer({ data, onNavigate }: HTTPRouteRendererProps) {
17
+ const refs = routeGateways(data)
18
+ const parentGateways = useQueries({
19
+ queries: refs.map(ref => resourceQueryOptions<GatewayObject>('gateways', ref.namespace, ref.name, GATEWAY_GROUP)),
20
+ combine: (results): GatewayLookup[] => results.map((result, i) => ({
21
+ ...refs[i],
22
+ gateway: result.data?.resource,
23
+ status: result.data?.resource ? 'loaded' : result.isPending ? 'loading' : 'unavailable',
24
+ })),
25
+ })
26
+ return <BaseHTTPRouteRenderer data={data} onNavigate={onNavigate} parentGateways={parentGateways} />
27
+ }
@@ -1,12 +1,19 @@
1
1
  import { PodRenderer as BasePodRenderer } from '@skyhook-io/k8s-ui/components/resources/renderers/PodRenderer'
2
2
  import type { CopyHandler } from '@skyhook-io/k8s-ui/components/ui/drawer-components'
3
+ import { getPodNetworks, uniqueNetworkAttachmentRefs } from '@skyhook-io/k8s-ui/utils/multus'
3
4
  import type { PodEnvironmentRevealResponse, ResolvedEnvFrom } from '@skyhook-io/k8s-ui'
5
+ import { useMemo } from 'react'
4
6
  import { useNavigate } from 'react-router-dom'
5
7
  import { useOpenTerminal, useOpenLogs } from '../../dock'
6
8
  import { useCapabilitiesContext, useNamespacedCapabilities, useIsLocalDeployment } from '../../../contexts/CapabilitiesContext'
7
- import { getVisibleLiveMetrics, isLiveMetricsUnavailable, shouldFetchLiveMetrics, usePodEnvironment, usePodMetrics, usePodMetricsHistory, usePrometheusResourceMetrics, usePrometheusStatus, useRevealPodEnvironment } from '../../../api/client'
9
+ import { getVisibleLiveMetrics, isLiveMetricsUnavailable, shouldFetchLiveMetrics, usePodEnvironment, usePodMetrics, usePodMetricsHistory, usePrometheusResourceMetrics, usePrometheusStatus, useResourceEvents, useResources, useRevealPodEnvironment } from '../../../api/client'
10
+ import { toSecretsStoreRead } from '../../../api/secretsStore'
11
+ import {
12
+ SECRETS_STORE_GROUP, SECRET_PROVIDER_CLASSES, SECRET_PROVIDER_CLASS_POD_STATUSES, getSecretsStoreVolumes,
13
+ } from '@skyhook-io/k8s-ui/components/resources/resource-utils-secrets-store'
8
14
  import { useRBACSubject } from '../../../api/rbac'
9
15
  import { usePolicyResource } from '../../../api/policy'
16
+ import { useNetworkAttachmentLookups } from '../../../api/networkAttachments'
10
17
  import { podLimitRangeNames, useNamespaceLimitRanges } from '../../../api/quotas'
11
18
  import { podAwaitsScheduling } from '../../capacity/podDemandGate'
12
19
  import { PortForwardInlineButton } from '../../portforward/PortForwardButton'
@@ -83,6 +90,16 @@ export function PodRenderer({ data, onCopy, copied, onNavigate, onOpenLogs, reso
83
90
 
84
91
  const { data: limitRanges, isSuccess: limitRangesReady } = useNamespaceLimitRanges(namespace ?? '', !!namespace)
85
92
 
93
+ const networkAttachmentRefs = useMemo(() => uniqueNetworkAttachmentRefs(getPodNetworks(data).rows), [data])
94
+ const networkAttachmentLookups = useNetworkAttachmentLookups(networkAttachmentRefs)
95
+
96
+ // Secrets Store CSI: read only for a Pod that mounts such a volume.
97
+ const usesSecretsStore = !!namespace && getSecretsStoreVolumes(data).length > 0
98
+ const providerClasses = useResources<any>(SECRET_PROVIDER_CLASSES, namespace, SECRETS_STORE_GROUP, { enabled: usesSecretsStore })
99
+ const providerStatuses = useResources<any>(SECRET_PROVIDER_CLASS_POD_STATUSES, namespace, SECRETS_STORE_GROUP, { enabled: usesSecretsStore })
100
+ // The query the detail view's Events section already runs, so it shares that cache.
101
+ const podEvents = useResourceEvents(usesSecretsStore ? 'pods' : '', namespace ?? '', podName ?? '', '')
102
+
86
103
  return (
87
104
  <BasePodRenderer
88
105
  data={data}
@@ -115,6 +132,13 @@ export function PodRenderer({ data, onCopy, copied, onNavigate, onOpenLogs, reso
115
132
  policyLoading={policyLoading}
116
133
  policyError={policyError as Error | null}
117
134
  namespaceLimitRangeNames={limitRangesReady ? podLimitRangeNames(limitRanges) : undefined}
135
+ networkAttachmentLookups={networkAttachmentLookups}
136
+
137
+ secretsStore={usesSecretsStore ? {
138
+ classes: toSecretsStoreRead({ data: providerClasses.data, coverage: providerClasses.coverage, error: providerClasses.error, isLoading: providerClasses.isLoading }),
139
+ statuses: toSecretsStoreRead({ data: providerStatuses.data, coverage: providerStatuses.coverage, error: providerStatuses.error, isLoading: providerStatuses.isLoading }),
140
+ events: podEvents.k8sError ? undefined : podEvents.k8sEvents,
141
+ } : undefined}
118
142
  canExec={canExec}
119
143
  canViewLogs={canViewLogs}
120
144
  canPortForward={showPortForward}
@@ -155,6 +179,7 @@ export function PodRenderer({ data, onCopy, copied, onNavigate, onOpenLogs, reso
155
179
  containers={containers}
156
180
  initialContainer={initialContainer}
157
181
  onSwitchToImageFiles={onSwitchToImageFiles}
182
+ pod={data}
158
183
  />
159
184
  )}
160
185
  />
@@ -0,0 +1,25 @@
1
+ import { SecretProviderClassRenderer as BaseSecretProviderClassRenderer } from '@skyhook-io/k8s-ui/components/resources/renderers/SecretsStoreRenderers'
2
+ import {
3
+ SECRETS_STORE_GROUP, SECRET_PROVIDER_CLASS_POD_STATUSES,
4
+ } from '@skyhook-io/k8s-ui/components/resources/resource-utils-secrets-store'
5
+ import type { ResourceRef } from '@skyhook-io/k8s-ui'
6
+ import { useResources } from '../../../api/client'
7
+ import { toSecretsStoreRead } from '../../../api/secretsStore'
8
+
9
+ /**
10
+ * Host wrapper adding the reverse lookup the package renderer cannot do: which
11
+ * Pods in this namespace mount the class, and what the driver recorded for each.
12
+ */
13
+ export function SecretProviderClassRenderer({ data, onNavigate }: { data: any; onNavigate?: (ref: ResourceRef) => void }) {
14
+ const namespace = data?.metadata?.namespace ?? ''
15
+ const pods = useResources<any>('pods', namespace, undefined, { enabled: !!namespace })
16
+ const statuses = useResources<any>(SECRET_PROVIDER_CLASS_POD_STATUSES, namespace, SECRETS_STORE_GROUP, { enabled: !!namespace })
17
+ return (
18
+ <BaseSecretProviderClassRenderer
19
+ data={data}
20
+ pods={toSecretsStoreRead({ data: pods.data, coverage: pods.coverage, error: pods.error, isLoading: pods.isLoading })}
21
+ statuses={toSecretsStoreRead({ data: statuses.data, coverage: statuses.coverage, error: statuses.error, isLoading: statuses.isLoading })}
22
+ onNavigate={onNavigate}
23
+ />
24
+ )
25
+ }