@skyhook-io/radar-app 1.21.6 → 1.21.7

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 (107) hide show
  1. package/README.md +1 -1
  2. package/package.json +7 -7
  3. package/src/App.tsx +19 -1
  4. package/src/RadarApp.tsx +8 -2
  5. package/src/api/client.discoverMetrics.test.tsx +69 -0
  6. package/src/api/client.issueCorrelation.test.tsx +244 -0
  7. package/src/api/client.issueRowChanges.test.tsx +129 -0
  8. package/src/api/client.pendingOwnership.test.tsx +197 -0
  9. package/src/api/client.prometheusStatus.test.ts +4 -0
  10. package/src/api/client.restartError.test.ts +36 -1
  11. package/src/api/client.stopWorkflow.test.tsx +133 -0
  12. package/src/api/client.submitWorkflowTemplate.test.tsx +127 -0
  13. package/src/api/client.ts +572 -111
  14. package/src/api/connectionBinding.test.tsx +3 -1
  15. package/src/api/connectionBinding.ts +14 -2
  16. package/src/api/gitOpsPermissions.render.test.tsx +155 -0
  17. package/src/api/gitOpsPermissions.test.ts +90 -0
  18. package/src/api/gitOpsPermissions.ts +51 -0
  19. package/src/api/httpErrors.test.ts +30 -1
  20. package/src/api/httpErrors.ts +17 -0
  21. package/src/api/openobserveSetup.ts +85 -0
  22. package/src/api/podDebug.test.tsx +137 -0
  23. package/src/api/podDebug.ts +82 -0
  24. package/src/api/prometheusCharts.test.ts +23 -0
  25. package/src/api/prometheusCharts.ts +25 -0
  26. package/src/api/radarFeatures.render.test.tsx +43 -2
  27. package/src/api/radarFeatures.test.ts +18 -1
  28. package/src/api/radarFeatures.ts +17 -4
  29. package/src/api/reviewedActionMutation.ts +9 -2
  30. package/src/api/workloadMetrics.ts +2 -0
  31. package/src/components/applications/ApplicationsView.openResource.test.tsx +137 -11
  32. package/src/components/applications/ApplicationsView.tsx +56 -31
  33. package/src/components/cnpg/host.test.tsx +1 -1
  34. package/src/components/cnpg/host.tsx +0 -2
  35. package/src/components/dock/BottomDock.tsx +7 -3
  36. package/src/components/dock/MissingShellDebug.test.tsx +193 -0
  37. package/src/components/dock/MissingShellDebug.tsx +114 -0
  38. package/src/components/dock/PodDebugSession.test.tsx +60 -0
  39. package/src/components/dock/PodDebugSession.tsx +96 -0
  40. package/src/components/dock/TerminalTab.test.tsx +48 -4
  41. package/src/components/dock/TerminalTab.tsx +47 -25
  42. package/src/components/dock/WorkloadLogsTab.test.tsx +24 -1
  43. package/src/components/dock/WorkloadLogsTab.tsx +16 -0
  44. package/src/components/execution/BatchExecutionView.command.test.tsx +69 -0
  45. package/src/components/execution/BatchExecutionView.tsx +88 -5
  46. package/src/components/execution/BatchExecutionView.workflow-stop.test.tsx +69 -0
  47. package/src/components/execution/WorkflowRunStopAction.tsx +8 -0
  48. package/src/components/gitops/GitOpsPermissionRowActions.test.tsx +100 -0
  49. package/src/components/gitops/GitOpsPermissionRowActions.tsx +27 -0
  50. package/src/components/gitops/GitOpsView.identity.test.tsx +1 -0
  51. package/src/components/gitops/GitOpsView.permissions.test.tsx +102 -0
  52. package/src/components/gitops/GitOpsView.syncRequest.test.tsx +95 -7
  53. package/src/components/gitops/GitOpsView.tsx +93 -32
  54. package/src/components/helm/OwnedResources.tsx +1 -0
  55. package/src/components/home/mcpToolCatalog.ts +1 -0
  56. package/src/components/issues/IssuesPane.render.test.tsx +1 -1
  57. package/src/components/issues/IssuesPane.tsx +11 -0
  58. package/src/components/issues/useIssueExpansion.ts +91 -0
  59. package/src/components/resource/MetricsNotConnected.test.tsx +50 -0
  60. package/src/components/resource/MetricsNotConnected.tsx +114 -0
  61. package/src/components/resource/PVCUsageBar.tsx +2 -1
  62. package/src/components/resource/PrometheusCharts.render.test.tsx +47 -0
  63. package/src/components/resource/PrometheusCharts.tsx +14 -2
  64. package/src/components/resource/PrometheusChartsGrid.render.test.tsx +91 -1
  65. package/src/components/resource/PrometheusChartsGrid.tsx +28 -52
  66. package/src/components/resource/RestartChart.tsx +4 -3
  67. package/src/components/resource/RightsizingPanel.source.test.tsx +34 -0
  68. package/src/components/resource/RightsizingStrip.tsx +5 -3
  69. package/src/components/resource/WorkloadMetricsSection.render.test.tsx +6 -0
  70. package/src/components/resource/WorkloadMetricsSection.tsx +14 -11
  71. package/src/components/resource/nameMatchedScope.ts +9 -3
  72. package/src/components/resources/EmptyNamespaceHint.tsx +42 -0
  73. package/src/components/resources/PodDebugAction.test.tsx +157 -0
  74. package/src/components/resources/PodDebugAction.tsx +207 -0
  75. package/src/components/resources/PodDebugPermission.tsx +21 -0
  76. package/src/components/resources/ResourcesView.empty-hint.test.tsx +132 -0
  77. package/src/components/resources/ResourcesView.tsx +39 -5
  78. package/src/components/resources/namespaceHint.test.ts +34 -0
  79. package/src/components/resources/namespaceHint.ts +19 -0
  80. package/src/components/resources/renderers/AdmissionPolicyRenderers.tsx +135 -0
  81. package/src/components/resources/renderers/NodeRenderer.tsx +2 -1
  82. package/src/components/resources/renderers/PodRenderer.tsx +12 -5
  83. package/src/components/resources/renderers/ValidatingAdmissionPolicyRenderer.test.tsx +24 -1
  84. package/src/components/settings/LocalIntegrationStatus.tsx +14 -3
  85. package/src/components/settings/MetricsBackendSwitch.tsx +167 -0
  86. package/src/components/settings/OpenObserveSetup.test.tsx +343 -0
  87. package/src/components/settings/OpenObserveSetup.tsx +358 -0
  88. package/src/components/settings/SettingsDialog.tsx +21 -7
  89. package/src/components/settings/openobserveStatus.test.ts +34 -0
  90. package/src/components/settings/openobserveStatus.ts +55 -0
  91. package/src/components/timeline/TimelineList.selection.test.tsx +40 -0
  92. package/src/components/timeline/TimelineList.test.ts +18 -0
  93. package/src/components/timeline/TimelineList.tsx +19 -5
  94. package/src/components/timeline/TimelineView.tsx +2 -0
  95. package/src/components/workload/WorkloadView.pendingOwnership.test.tsx +34 -0
  96. package/src/components/workload/WorkloadView.tabUrl.test.tsx +44 -0
  97. package/src/components/workload/WorkloadView.tsx +95 -10
  98. package/src/context/TimelineNavigation.test.ts +59 -0
  99. package/src/context/TimelineNavigation.tsx +86 -0
  100. package/src/contexts/CapabilitiesContext.tsx +3 -1
  101. package/src/hooks/useResourceCounts.ts +2 -1
  102. package/src/hooks/useWorkflowStopAction.ts +31 -0
  103. package/src/index.css +1 -0
  104. package/src/integrations/resourceHosts.test.tsx +2 -2
  105. package/src/integrations/resourceHosts.tsx +4 -2
  106. package/src/k8s-ui-exports.test.ts +10 -0
  107. package/src/components/resources/renderers/ValidatingAdmissionPolicyRenderer.tsx +0 -128
@@ -48,6 +48,8 @@ it("shows the server's refusal when a restart names a connection it no longer se
48
48
  const message = 'Nothing was changed: the cluster changed since this view loaded. Check the current cluster and try again.'
49
49
  const seen = recordHeaders(409, JSON.stringify({ error: message, code: 'context_changed', error_code: 'context_changed' }))
50
50
  const client = new QueryClient()
51
+ client.setQueryData(['capabilities'], { features: { workloadRestartPreconditions: true } })
52
+ client.setQueryData(['version-check', getApiBase()], {})
51
53
  let restart: ReturnType<typeof useRestartWorkload> | undefined
52
54
  function Probe() {
53
55
  restart = useRestartWorkload()
@@ -59,7 +61,7 @@ it("shows the server's refusal when a restart names a connection it no longer se
59
61
  })
60
62
  let error: unknown
61
63
  await act(async () => {
62
- await restart!.mutateAsync({ kind: 'deployments', namespace: 'default', name: 'web' }).catch((e) => { error = e })
64
+ await restart!.mutateAsync({ kind: 'deployments', namespace: 'default', name: 'web', uid: 'uid-1' }).catch((e) => { error = e })
63
65
  })
64
66
  expect(seen).toEqual(['n-1'])
65
67
  expect((error as Error).message).toBe(message)
@@ -1,4 +1,4 @@
1
- import { useState } from 'react'
1
+ import { useState, useSyncExternalStore } from 'react'
2
2
  import { getApiBase } from './config'
3
3
 
4
4
  // Which cluster connection this tab is on, per API base.
@@ -14,10 +14,18 @@ import { getApiBase } from './config'
14
14
  export const CONNECTION_HEADER = 'X-Radar-Connection'
15
15
 
16
16
  const ids = new Map<string, string>()
17
+ const listeners = new Set<() => void>()
18
+
19
+ function subscribe(listener: () => void) {
20
+ listeners.add(listener)
21
+ return () => { listeners.delete(listener) }
22
+ }
17
23
 
18
24
  /** Record the connection named by a status the tab received (poll, SSE frame, retry result). */
19
25
  export function observeConnectionStatus(status: { connectionId?: string }, base = getApiBase()): void {
20
- if (status.connectionId) ids.set(base, status.connectionId)
26
+ if (!status.connectionId || ids.get(base) === status.connectionId) return
27
+ ids.set(base, status.connectionId)
28
+ listeners.forEach(listener => listener())
21
29
  }
22
30
 
23
31
  /** The connection ID to send, or undefined when the server publishes none. */
@@ -25,6 +33,10 @@ export function connectionHeaderValue(base = getApiBase()): string | undefined {
25
33
  return ids.get(base)
26
34
  }
27
35
 
36
+ export function useCurrentConnectionId(base = getApiBase()): string | undefined {
37
+ return useSyncExternalStore(subscribe, () => connectionHeaderValue(base), () => undefined)
38
+ }
39
+
28
40
  /** A WebSocket URL naming a connection (a browser can't set headers on one); by default this tab's latest. */
29
41
  export function withConnectionParam(url: string, id = connectionHeaderValue()): string {
30
42
  if (!id) return url
@@ -0,0 +1,155 @@
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 { afterEach, beforeEach, expect, it, vi } from 'vitest'
6
+ import { useGitOpsActionCapabilities } from './client'
7
+ import { observeConnectionStatus, resetConnectionBindingForTest } from './connectionBinding'
8
+
9
+ vi.mock('../context/RadarUpgradeHost', () => ({ useRadarUpgradeHost: () => ({}) }))
10
+ vi.stubGlobal('IS_REACT_ACT_ENVIRONMENT', true)
11
+ let client: QueryClient
12
+ let element: HTMLDivElement
13
+ let root: ReturnType<typeof createRoot>
14
+ let query: ReturnType<typeof useGitOpsActionCapabilities>
15
+ let answer: () => Promise<Response>
16
+ const fetcher = vi.fn((input: RequestInfo | URL) => String(input).includes('/gitops/capabilities/') ? answer() : new Promise<Response>(() => {}))
17
+
18
+ beforeEach(() => {
19
+ client = new QueryClient({ defaultOptions: { queries: { retry: false } } })
20
+ client.setQueryData(['capabilities'], { features: { gitopsActionCapabilities: true } })
21
+ answer = () => new Promise<Response>(() => {})
22
+ fetcher.mockClear()
23
+ vi.stubGlobal('fetch', fetcher)
24
+ element = document.createElement('div')
25
+ root = createRoot(element)
26
+ })
27
+ afterEach(async () => {
28
+ await act(async () => root.unmount())
29
+ client.clear()
30
+ resetConnectionBindingForTest()
31
+ vi.useRealTimers()
32
+ vi.unstubAllGlobals()
33
+ vi.stubGlobal('IS_REACT_ACT_ENVIRONMENT', true)
34
+ })
35
+ async function render(group = 'argoproj.io') {
36
+ function Probe() {
37
+ query = useGitOpsActionCapabilities('applications', group, 'argocd', 'demo')
38
+ return <button disabled={!!query.disabledReasons.sync}>Sync</button>
39
+ }
40
+ await act(async () => root.render(<QueryClientProvider client={client}><Probe /></QueryClientProvider>))
41
+ }
42
+ async function refetch() {
43
+ await act(async () => { await query.refetch(); await new Promise(resolve => setTimeout(resolve, 0)) })
44
+ }
45
+ it('enables controls on initial load, retains allowed results through failed and unknown refetches', async () => {
46
+ let finish: (response: Response) => void
47
+ answer = () => new Promise(resolve => { finish = resolve })
48
+ await render()
49
+ expect(element.querySelector('button')!.disabled).toBe(false)
50
+ expect(query.permissionCheckUnavailable).toBe(false)
51
+ await act(async () => { finish!(Response.json({ actions: { sync: { allowed: true } } })); await new Promise(resolve => setTimeout(resolve, 0)) })
52
+ answer = async () => { throw new Error('background poll failed') }
53
+ await refetch()
54
+ expect(query.data?.actions.sync.allowed).toBe(true)
55
+ expect(element.querySelector('button')!.disabled).toBe(false)
56
+ answer = async () => Response.json({ actions: { sync: { reason: "Couldn't check your permissions — retrying" } } })
57
+ await refetch()
58
+ expect(query.data?.actions.sync.allowed).toBe(true)
59
+ expect(element.querySelector('button')!.disabled).toBe(false)
60
+ })
61
+ it('enables a failed first probe and disables only a definite denial', async () => {
62
+ answer = async () => { throw new Error('offline') }
63
+ await render()
64
+ await new Promise(resolve => setTimeout(resolve, 0))
65
+ expect(element.querySelector('button')!.disabled).toBe(false)
66
+ expect(query.permissionCheckUnavailable).toBe(true)
67
+ answer = async () => Response.json({ actions: { sync: { allowed: false, denied: [{ verb: 'patch', resource: 'applications', group: 'argoproj.io', namespace: 'argocd' }] } } })
68
+ await refetch()
69
+ expect(element.querySelector('button')!.disabled).toBe(true)
70
+ })
71
+ it('replaces a previous result with an unsupported one instead of retaining it', async () => {
72
+ answer = async () => Response.json({ actions: { sync: { allowed: true } } })
73
+ await render()
74
+ await new Promise(resolve => setTimeout(resolve, 0))
75
+ answer = async () => Response.json({ actions: { sync: { unsupported: true, reason: 'Not supported here.' } } })
76
+ await refetch()
77
+ expect(query.data?.actions.sync.unsupported).toBe(true)
78
+ expect(query.disabledReasons.sync).toBe('Not supported here.')
79
+ expect(element.querySelector('button')!.disabled).toBe(true)
80
+ })
81
+ it('does not fetch Argo capabilities for a KubeVela Application', async () => {
82
+ await render('core.oam.dev')
83
+ expect(fetcher.mock.calls.some(([url]) => String(url).includes('/gitops/capabilities/'))).toBe(false)
84
+ })
85
+
86
+ it.each(['unknown', 'failed', 'pending'].flatMap(mode => ['denied', 'unsupported'].map(state => ({ mode, state }))))('expires a $state result after two minutes of $mode checks', async ({ mode, state }) => {
87
+ vi.useFakeTimers()
88
+ const denial = { allowed: false, denied: [{ verb: 'patch', resource: 'applications', group: 'argoproj.io', namespace: 'argocd' }] }
89
+ answer = async () => Response.json({ actions: { sync: state === 'unsupported' ? { unsupported: true, reason: 'Not supported here.' } : denial } })
90
+ await render()
91
+ await act(async () => { await vi.advanceTimersByTimeAsync(1) })
92
+ expect(element.querySelector('button')!.disabled).toBe(true)
93
+ answer = mode === 'failed'
94
+ ? async () => { throw new Error('offline') }
95
+ : mode === 'pending'
96
+ ? () => new Promise<Response>(() => {})
97
+ : async () => Response.json({ actions: { sync: { reason: 'Review unavailable' } } })
98
+ await act(async () => { await vi.advanceTimersByTimeAsync(119_998) })
99
+ expect(element.querySelector('button')!.disabled).toBe(true)
100
+ await act(async () => { await vi.advanceTimersByTimeAsync(2) })
101
+ expect(query.data?.actions.sync.allowed).toBeUndefined()
102
+ expect(query.permissions?.sync.allowed).toBeUndefined()
103
+ expect(query.permissions?.sync.unsupported).toBeUndefined()
104
+ expect(query.permissionCheckUnavailable).toBe(true)
105
+ expect(query.disabledReasons.sync).toBeUndefined()
106
+ expect(element.querySelector('button')!.disabled).toBe(false)
107
+ })
108
+
109
+ it('refreshes confirmation times separately for each action', async () => {
110
+ vi.useFakeTimers()
111
+ const denied = { allowed: false, denied: [{ verb: 'patch', resource: 'applications', group: 'argoproj.io', namespace: 'argocd' }] }
112
+ answer = async () => Response.json({ actions: { sync: denied, refresh: denied } })
113
+ await render()
114
+ await act(async () => { await vi.advanceTimersByTimeAsync(1) })
115
+ answer = async () => Response.json({ actions: { sync: { reason: 'Review unavailable' }, refresh: denied } })
116
+ await act(async () => { await vi.advanceTimersByTimeAsync(120_000) })
117
+ expect(query.disabledReasons.sync).toBeUndefined()
118
+ expect(query.disabledReasons.refresh).toContain("Kubernetes denied permission to")
119
+ answer = async () => Response.json({ actions: { sync: { allowed: true }, refresh: { reason: 'Review unavailable' } } })
120
+ await act(async () => { await query.refetch(); await vi.advanceTimersByTimeAsync(1) })
121
+ expect(query.permissions?.sync.allowed).toBe(true)
122
+ expect(query.disabledReasons.sync).toBeUndefined()
123
+ })
124
+
125
+ it('marks an unknown first answer as unavailable and clears it after confirmation', async () => {
126
+ answer = async () => Response.json({ actions: { sync: { reason: 'Review unavailable' } } })
127
+ await render()
128
+ await new Promise(resolve => setTimeout(resolve, 0))
129
+ expect(query.permissionCheckUnavailable).toBe(true)
130
+ expect(element.querySelector('button')!.disabled).toBe(false)
131
+ answer = async () => Response.json({ actions: { sync: { allowed: true } } })
132
+ await refetch()
133
+ expect(query.permissionCheckUnavailable).toBe(false)
134
+ })
135
+
136
+ it('keeps a pending permission result scoped to its original connection', async () => {
137
+ let finish!: (response: Response) => void
138
+ answer = () => new Promise(resolve => { finish = resolve })
139
+ observeConnectionStatus({ connectionId: 'old-connection' })
140
+ await render()
141
+
142
+ answer = async () => Response.json({ actions: { sync: { allowed: true } } })
143
+ await act(async () => {
144
+ observeConnectionStatus({ connectionId: 'new-connection' })
145
+ await new Promise(resolve => setTimeout(resolve, 0))
146
+ })
147
+ await refetch()
148
+
149
+ await act(async () => {
150
+ finish(Response.json({ actions: { sync: { allowed: false, denied: [{ verb: 'patch', resource: 'applications', namespace: 'argocd' }] } } }))
151
+ await new Promise(resolve => setTimeout(resolve, 0))
152
+ })
153
+ expect(query.permissions?.sync.allowed).toBe(true)
154
+ expect(element.querySelector('button')?.disabled).toBe(false)
155
+ })
@@ -0,0 +1,90 @@
1
+ import { describe, expect, it } from 'vitest'
2
+ import { gitOpsActionPermissions, gitOpsDisabledReasons, isGitOpsActionTarget } from './gitOpsPermissions'
3
+
4
+ const argoApp = { group: 'argoproj.io', resource: 'applications', kind: 'Application', namespace: 'argocd', name: 'demo' }
5
+ const kustomization = { group: 'kustomize.toolkit.fluxcd.io', resource: 'kustomizations', kind: 'Kustomization', namespace: 'apps', name: 'web' }
6
+ const gitRepository = { group: 'source.toolkit.fluxcd.io', resource: 'gitrepositories', kind: 'GitRepository', namespace: 'sources', name: 'repo', source: true }
7
+
8
+ describe('GitOps action permission states', () => {
9
+ it('does not probe colliding Application kinds', () => {
10
+ expect(isGitOpsActionTarget('applications', 'core.oam.dev')).toBe(false)
11
+ expect(isGitOpsActionTarget('applications', 'app.k8s.io')).toBe(false)
12
+ expect(isGitOpsActionTarget('applications', 'argoproj.io')).toBe(true)
13
+ expect(isGitOpsActionTarget('kustomizations', 'kustomize.toolkit.fluxcd.io')).toBe(true)
14
+ // The capability endpoint resolves the controller kind, so a lookalike group must not probe it.
15
+ expect(isGitOpsActionTarget('kustomizations', 'vendor.kustomize.toolkit.fluxcd.io')).toBe(false)
16
+ expect(isGitOpsActionTarget('kustomizations', 'source.toolkit.fluxcd.io')).toBe(false)
17
+ expect(isGitOpsActionTarget('helmreleases', 'source.toolkit.fluxcd.io')).toBe(false)
18
+ expect(isGitOpsActionTarget('alerts', 'notification.toolkit.fluxcd.io')).toBe(true)
19
+ })
20
+ it('retains known permissions during errors and treats review uncertainty as unknown', () => {
21
+ const data = { actions: { sync: { allowed: true }, refresh: { reason: "Couldn't check your permissions — retrying" } } }
22
+ expect(gitOpsDisabledReasons('supported', data, false).sync).toBeUndefined()
23
+ expect(gitOpsDisabledReasons('supported', data, false).refresh).toBeUndefined()
24
+ })
25
+ it('names the Flux source the role is denied, with every denied verb in one sentence', () => {
26
+ const reason = gitOpsDisabledReasons('supported', { actions: { 'sync-with-source': {
27
+ allowed: false, denied: [{ ...gitRepository, verb: 'get' }, { ...gitRepository, verb: 'patch' }],
28
+ } } }, false)['sync-with-source']
29
+ expect(reason).toBe("Sync with source also reconciles GitRepository sources/repo — Kubernetes denied permission to read or patch it.")
30
+ })
31
+ it('names both the target and its source when the role can patch neither', () => {
32
+ const reason = gitOpsDisabledReasons('supported', { actions: { 'sync-with-source': {
33
+ allowed: false, denied: [{ ...kustomization, verb: 'patch' }, { ...gitRepository, verb: 'patch' }],
34
+ } } }, false)['sync-with-source']
35
+ expect(reason).toBe("Kubernetes denied permission to patch Flux Kustomization web in apps or its source GitRepository sources/repo.")
36
+ })
37
+ it('names the Argo CD Application and every denied operation without an access parenthetical', () => {
38
+ const reasons = gitOpsDisabledReasons('supported', { actions: {
39
+ refresh: { allowed: false, denied: [{ ...argoApp, verb: 'patch' }] },
40
+ sync: { allowed: false, denied: [{ ...argoApp, verb: 'get' }, { ...argoApp, verb: 'patch' }] },
41
+ suspend: { allowed: false, denied: [{ ...argoApp, verb: 'get' }] },
42
+ } }, false)
43
+ expect(reasons.refresh).toBe("Kubernetes denied permission to patch Argo CD Application demo in argocd.")
44
+ expect(reasons.sync).toBe("Kubernetes denied permission to read or patch Argo CD Application demo in argocd.")
45
+ expect(reasons.suspend).toBe("Kubernetes denied permission to read Argo CD Application demo in argocd.")
46
+ })
47
+ it('disables an unsupported action with its reason, outside the role permissions', () => {
48
+ const reason = "no source reference found in Kustomization apps/web."
49
+ const data = { actions: { reconcile: { allowed: true }, 'sync-with-source': { unsupported: true, reason } } }
50
+ expect(gitOpsDisabledReasons('supported', data, false)['sync-with-source']).toBe(reason)
51
+ expect(gitOpsDisabledReasons('supported', data, false).reconcile).toBeUndefined()
52
+ })
53
+ it('names both missing grants on a Flux target the role can neither read nor patch', () => {
54
+ const denied = [{ ...kustomization, verb: 'get' }, { ...kustomization, verb: 'patch' }]
55
+ expect(gitOpsActionPermissions('supported', { actions: { reconcile: { allowed: false, denied } } }, false)?.reconcile.denied).toEqual(denied)
56
+ expect(gitOpsDisabledReasons('supported', { actions: { reconcile: { allowed: false, denied } } }, false).reconcile).toBe("Kubernetes denied permission to read or patch Flux Kustomization web in apps.")
57
+ })
58
+ it('preserves existing controls for older Radar', () => {
59
+ expect(gitOpsDisabledReasons('unsupported', undefined, false)).toEqual({})
60
+ expect(gitOpsDisabledReasons('unknown', undefined, true)).toEqual({})
61
+ })
62
+ it('allows loading and failed checks without prior data', () => {
63
+ expect(gitOpsDisabledReasons('supported', undefined, false)).toEqual({})
64
+ })
65
+ it('allows local reconcile while denying a cross-namespace source action', () => {
66
+ const reasons = gitOpsDisabledReasons('supported', { actions: {
67
+ reconcile: { allowed: true },
68
+ 'sync-with-source': { allowed: false, denied: [{ ...gitRepository, verb: 'patch' }] },
69
+ } }, false)
70
+ expect(reasons.reconcile).toBeUndefined()
71
+ expect(reasons['sync-with-source']).toContain('sources/repo')
72
+ })
73
+ })
74
+
75
+ it('names every source in a denied HelmChart chain with its own verbs', () => {
76
+ const reason = gitOpsDisabledReasons('supported', { actions: { 'sync-with-source': {
77
+ allowed: false, denied: [
78
+ { ...gitRepository, verb: 'get' },
79
+ { ...gitRepository, verb: 'patch' },
80
+ { group: 'source.toolkit.fluxcd.io', resource: 'helmcharts', kind: 'HelmChart', namespace: 'charts', name: 'shared', source: true, verb: 'patch' },
81
+ ],
82
+ } } }, false)['sync-with-source']
83
+ expect(reason).toBe("Kubernetes denied permission to read or patch source GitRepository sources/repo or patch source HelmChart charts/shared.")
84
+ })
85
+
86
+ it.each(['buckets', 'helmcharts'])('probes %s only in its exact Flux API group', kind => {
87
+ expect(isGitOpsActionTarget(kind, 'source.toolkit.fluxcd.io')).toBe(true)
88
+ expect(isGitOpsActionTarget(kind, 'vendor.source.toolkit.fluxcd.io')).toBe(false)
89
+ expect(isGitOpsActionTarget(kind, 'helm.toolkit.fluxcd.io')).toBe(false)
90
+ })
@@ -0,0 +1,51 @@
1
+ import { getGitOpsTool } from '@skyhook-io/k8s-ui'
2
+ import { gitOpsDenialMessage, type GitOpsPermission } from '@skyhook-io/k8s-ui/utils/gitops-permissions'
3
+ import type { RadarFeatureSupport } from './radarFeatures'
4
+
5
+ /**
6
+ * Four answer forms: {allowed:true}, {allowed:false, denied:[…]},
7
+ * {reason} (unknown after a failed or expired check; permit an attempt),
8
+ * or {unsupported:true, reason}.
9
+ */
10
+ export interface GitOpsActionCapability {
11
+ allowed?: boolean
12
+ /** Operations checked and denied; a denied read can hide later Flux source hops, so this may omit missing grants. */
13
+ denied?: GitOpsPermission[]
14
+ /** The action can't run on this object whatever the caller's role. */
15
+ unsupported?: boolean
16
+ reason?: string
17
+ }
18
+
19
+ export interface GitOpsActionCapabilities {
20
+ /** Selective sync uses `sync`, hard refresh uses `refresh`, resource validation uses `validate`, and the Flux source chain uses `sync-with-source`. */
21
+ actions: Record<string, GitOpsActionCapability>
22
+ }
23
+
24
+ const GITOPS_ACTION_KINDS = ['applications', 'gitrepositories', 'ocirepositories', 'helmrepositories', 'buckets', 'helmcharts', 'kustomizations', 'helmreleases', 'alerts']
25
+
26
+ export function isGitOpsActionTarget(kind: string, group: string | undefined): boolean {
27
+ return GITOPS_ACTION_KINDS.includes(kind) && getGitOpsTool(kind, group) !== null
28
+ }
29
+
30
+ /** The per-action permissions to gate on; none for a Radar without the endpoint. */
31
+ export function gitOpsActionPermissions(
32
+ support: RadarFeatureSupport,
33
+ data: GitOpsActionCapabilities | undefined,
34
+ unsupported: boolean,
35
+ ): Record<string, GitOpsActionCapability> | undefined {
36
+ if (support === 'unsupported' || unsupported) return undefined
37
+ return data?.actions
38
+ }
39
+
40
+ export function gitOpsDisabledReasons(
41
+ support: RadarFeatureSupport,
42
+ data: GitOpsActionCapabilities | undefined,
43
+ unsupported: boolean,
44
+ ): Record<string, string | undefined> {
45
+ const permissions = gitOpsActionPermissions(support, data, unsupported)
46
+ return Object.fromEntries(Object.entries(permissions ?? {}).map(([action, capability]) => [action,
47
+ capability.allowed === false
48
+ ? gitOpsDenialMessage(capability.denied ?? [])
49
+ : capability.unsupported ? capability.reason : undefined,
50
+ ]))
51
+ }
@@ -1,6 +1,6 @@
1
1
  import { afterEach, describe, expect, it, vi } from 'vitest'
2
2
  import { ApiError, fetchJSON } from './client'
3
- import { CHI_UNKNOWN_ROUTE_BODY, httpStatusMessage, isUnknownRouteResponse, nonJsonErrorMessage, readErrorResponse } from './httpErrors'
3
+ import { CHI_UNKNOWN_ROUTE_BODY, GitOpsActionError, httpStatusMessage, isUnknownRouteResponse, nonJsonErrorMessage, readErrorResponse } from './httpErrors'
4
4
 
5
5
  const TEXT = 'text/plain; charset=utf-8'
6
6
 
@@ -93,3 +93,32 @@ describe('fetchJSON error fallback', () => {
93
93
  expect(error.unknownRoute).toBe(false)
94
94
  })
95
95
  })
96
+
97
+ describe('GitOpsActionError', () => {
98
+ it.each(['rbac_denied', 'admission_denied'])('shows the server summary and retains the original %s response', error_code => {
99
+ const note = 'Reconcile already requested for HelmRepository charts/repo.'
100
+ const raw = `upstream error. ${note}`
101
+ const error = new GitOpsActionError({ error: raw, error_code, summary: 'Request rejected', note }, 403)
102
+ expect(error.message).toBe(`Request rejected\n${note}`)
103
+ expect(error.rawDetail).toBe(raw)
104
+ })
105
+
106
+ it('adds request context only to the notification', () => {
107
+ const error = new GitOpsActionError({
108
+ error: 'original webhook error',
109
+ error_code: 'admission_denied',
110
+ summary: 'Request for HelmChart charts/shared rejected by admission webhook freeze',
111
+ note: 'Reconcile already requested for HelmRepository charts/repo.',
112
+ }, 403, 'apps/storefront on prod')
113
+ expect(error.notificationDetail).toBe(`apps/storefront on prod\n${error.message}`)
114
+ expect(error.rawDetail).toBe('original webhook error')
115
+ expect(error.message).not.toContain('apps/storefront')
116
+ })
117
+
118
+ it('preserves a plain 403 from an older connected Radar without guessing its cause', () => {
119
+ const message = 'an upstream request was forbidden'
120
+ const error = new GitOpsActionError({ error: message }, 403)
121
+ expect(error.message).toBe(message)
122
+ expect(error.rawDetail).toBeUndefined()
123
+ })
124
+ })
@@ -111,3 +111,20 @@ export function markShownInline(error: Error): void {
111
111
  export function isShownInline(error: unknown): boolean {
112
112
  return error instanceof Error && (error as Error & { shownInline?: boolean }).shownInline === true
113
113
  }
114
+
115
+ export class GitOpsActionError extends Error {
116
+ readonly rawDetail?: string
117
+
118
+ constructor(body: ErrorBody, status: number, readonly requestTarget?: string) {
119
+ const raw = body.error || `HTTP ${status}`
120
+ const classified = body.error_code === 'rbac_denied' || body.error_code === 'admission_denied'
121
+ const summary = classified && typeof body.summary === 'string' && body.summary ? body.summary : raw
122
+ super(summary !== raw && body.note ? `${summary}\n${body.note}` : summary)
123
+ this.name = 'GitOpsActionError'
124
+ if (summary !== raw) this.rawDetail = raw
125
+ }
126
+
127
+ get notificationDetail(): string {
128
+ return this.requestTarget ? `${this.requestTarget}\n${this.message}` : this.message
129
+ }
130
+ }
@@ -0,0 +1,85 @@
1
+ import { apiUrl, getAuthHeaders, getCredentialsMode } from './config'
2
+ import { ApiError } from './client'
3
+
4
+ export interface OpenObserveLabelValue {
5
+ label: string
6
+ value: string
7
+ }
8
+
9
+ export interface OpenObserveMatch extends OpenObserveLabelValue {
10
+ by: string
11
+ }
12
+
13
+ export interface OpenObserveConnection {
14
+ baseUrl: string
15
+ org: string
16
+ user: string
17
+ tokenSource: 'saved' | 'env' | 'none'
18
+ tokenEnv?: string
19
+ caCertFile?: string
20
+ clusterLabel?: string
21
+ clusters: { context: string; by: string }[]
22
+ }
23
+
24
+ export interface OpenObserveState {
25
+ connection: OpenObserveConnection | null
26
+ cluster: { uid?: string; error?: string; match?: OpenObserveMatch }
27
+ }
28
+
29
+ export interface OpenObserveSetupRequest {
30
+ useSaved?: boolean
31
+ baseUrl?: string
32
+ org?: string
33
+ user?: string
34
+ token?: string
35
+ caCertFile?: string
36
+ clusterLabel?: string
37
+ confirm?: OpenObserveLabelValue
38
+ /** The cluster the page shows; the server refuses the save when Radar has moved to another. */
39
+ clusterUid?: string
40
+ }
41
+
42
+ export interface OpenObserveSetupNotes {
43
+ collector?: boolean
44
+ missing?: string[]
45
+ warning?: string
46
+ versionWarning?: string
47
+ }
48
+
49
+ export interface OpenObserveSetupResult {
50
+ outcome: 'saved' | 'confirm' | 'not_found'
51
+ match?: OpenObserveMatch
52
+ suggestion?: OpenObserveLabelValue
53
+ reason?: string
54
+ clusterNames?: OpenObserveLabelValue[]
55
+ clusterUid?: string
56
+ notes?: OpenObserveSetupNotes
57
+ }
58
+
59
+ async function request<T>(path: string, method: 'GET' | 'POST' | 'DELETE', body?: unknown, signal?: AbortSignal): Promise<T> {
60
+ const response = await fetch(apiUrl(path), {
61
+ method,
62
+ signal,
63
+ credentials: getCredentialsMode(),
64
+ headers: { 'Content-Type': 'application/json', ...getAuthHeaders() },
65
+ ...(body !== undefined ? { body: JSON.stringify(body) } : {}),
66
+ })
67
+ const data = (await response.json().catch(() => ({}))) as T & { error?: string }
68
+ if (!response.ok) throw new ApiError(data.error || `OpenObserve request failed (${response.status})`, response.status)
69
+ return data
70
+ }
71
+
72
+ export const getOpenObserveState = (signal?: AbortSignal) =>
73
+ request<OpenObserveState>('/integrations/openobserve', 'GET', undefined, signal)
74
+
75
+ export const setupOpenObserve = (body: OpenObserveSetupRequest) =>
76
+ request<OpenObserveSetupResult>('/integrations/openobserve/setup', 'POST', body)
77
+
78
+ export const removeOpenObserveCluster = (clusterUid?: string) =>
79
+ request<OpenObserveState>(
80
+ `/integrations/openobserve/cluster${clusterUid ? `?clusterUid=${encodeURIComponent(clusterUid)}` : ''}`,
81
+ 'DELETE',
82
+ )
83
+
84
+ export const removeOpenObserveConnection = () =>
85
+ request<OpenObserveState>('/integrations/openobserve', 'DELETE')
@@ -0,0 +1,137 @@
1
+ // @vitest-environment jsdom
2
+ import { act } from 'react'
3
+ import { createRoot, type Root } from 'react-dom/client'
4
+ import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
5
+ import { afterEach, beforeEach, expect, it, vi } from 'vitest'
6
+ import { fetchJSON } from './client'
7
+ import { podDebugAccessKey, usePodDebugAccess } from './podDebug'
8
+
9
+ vi.mock('./client', () => ({ fetchJSON: vi.fn(), useRadarFeature: () => ({ support: 'supported' }) }))
10
+
11
+ Object.assign(globalThis, { IS_REACT_ACT_ENVIRONMENT: true })
12
+ let root: Root, client: QueryClient, host: HTMLDivElement
13
+
14
+ function Access({ image }: { image?: string }) {
15
+ const { query, unverifiedImage } = usePodDebugAccess('demo', 'checkout', 'uid-1', !image, false, image)
16
+ return <span data-unverified-image={unverifiedImage}>{query.data?.state}</span>
17
+ }
18
+ function render(image?: string) {
19
+ return act(() => root.render(<QueryClientProvider client={client}><Access image={image}/></QueryClientProvider>))
20
+ }
21
+ beforeEach(() => {
22
+ vi.mocked(fetchJSON).mockReset()
23
+ client = new QueryClient()
24
+ host = document.createElement('div')
25
+ root = createRoot(host)
26
+ })
27
+ afterEach(() => {
28
+ act(() => root.unmount())
29
+ client.clear()
30
+ })
31
+
32
+ it.each(['denied', 'unavailable', 'check_failed'])('rechecks previously %s named access when a namespace grant appears', async state => {
33
+ vi.mocked(fetchJSON).mockResolvedValueOnce({ state }).mockResolvedValueOnce({ state: 'allowed', exec: true, image: 'tools' })
34
+ render()
35
+ await vi.waitFor(() => expect(host.textContent).toBe(state))
36
+ render('tools')
37
+ await vi.waitFor(() => expect(host.textContent).toBe('allowed'))
38
+ expect(fetchJSON).toHaveBeenCalledTimes(2)
39
+ })
40
+
41
+ it('refreshes an unsuccessful HTTP check when a namespace grant appears', async () => {
42
+ vi.mocked(fetchJSON).mockRejectedValueOnce(new Error('offline')).mockResolvedValueOnce({ state: 'allowed', exec: true, image: 'tools' })
43
+ render()
44
+ const key = [...podDebugAccessKey('demo', 'checkout', 'uid-1'), false]
45
+ await vi.waitFor(() => expect(client.getQueryState(key)?.status).toBe('error'))
46
+ render('tools')
47
+ await vi.waitFor(() => expect(host.textContent).toBe('allowed'))
48
+ expect(fetchJSON).toHaveBeenCalledTimes(2)
49
+ })
50
+
51
+ it('still refreshes an unresolved named check after the namespace grant is visible', async () => {
52
+ const failed = { state: 'check_failed', exec: true }
53
+ vi.mocked(fetchJSON).mockResolvedValueOnce(failed).mockResolvedValueOnce(failed).mockResolvedValueOnce({ state: 'allowed', exec: true, image: 'tools' })
54
+ render()
55
+ await vi.waitFor(() => expect(host.textContent).toBe('check_failed'))
56
+ render('tools')
57
+ await vi.waitFor(() => expect(fetchJSON).toHaveBeenCalledTimes(2))
58
+ await act(async () => { await client.invalidateQueries({ queryKey: podDebugAccessKey('demo', 'checkout', 'uid-1') }) })
59
+ await vi.waitFor(() => expect(host.textContent).toBe('allowed'))
60
+ })
61
+
62
+ it('clears only the refusal that preceded a successful retry', async () => {
63
+ vi.mocked(fetchJSON).mockResolvedValue({ state: 'unknown', exec: true, image: 'tools' })
64
+ let completeFirstAttempt: (() => void) | undefined
65
+ function Review() {
66
+ const { unverifiedReview } = usePodDebugAccess('demo', 'checkout', 'uid-1', true)
67
+ return <>
68
+ <button id="start" onClick={() => { completeFirstAttempt = unverifiedReview?.clearRefusal }}/>
69
+ <button id="later" onClick={() => unverifiedReview?.rememberRefusal('A newer refusal')}/>
70
+ <button id="refuse" onClick={() => unverifiedReview?.rememberRefusal('Image denied')}/>
71
+ <button id="succeed" onClick={() => unverifiedReview?.clearRefusal()}/>
72
+ <output>{unverifiedReview?.refused?.message ?? (unverifiedReview ? 'No previous refusal' : '')}</output>
73
+ </>
74
+ }
75
+ act(() => root.render(<QueryClientProvider client={client}><Review/></QueryClientProvider>))
76
+ await vi.waitFor(() => expect(host.textContent).toBe('No previous refusal'))
77
+ act(() => host.querySelector<HTMLButtonElement>('#refuse')!.click())
78
+ await vi.waitFor(() => expect(host.textContent).toBe('Image denied'))
79
+ act(() => host.querySelector<HTMLButtonElement>('#start')!.click())
80
+ act(() => host.querySelector<HTMLButtonElement>('#later')!.click())
81
+ await vi.waitFor(() => expect(host.textContent).toBe('A newer refusal'))
82
+ act(() => completeFirstAttempt!())
83
+ expect(host.textContent).toBe('A newer refusal')
84
+ act(() => host.querySelector<HTMLButtonElement>('#succeed')!.click())
85
+ await vi.waitFor(() => expect(host.textContent).toBe('No previous refusal'))
86
+ })
87
+
88
+ it('keeps a confirmed named denial when the refreshed review still denies access', async () => {
89
+ vi.mocked(fetchJSON).mockResolvedValue({ state: 'denied', exec: true })
90
+ render()
91
+ await vi.waitFor(() => expect(host.textContent).toBe('denied'))
92
+ render('tools')
93
+ await vi.waitFor(() => expect(fetchJSON).toHaveBeenCalledTimes(2))
94
+ render('tools')
95
+ expect(host.textContent).toBe('denied')
96
+ expect(fetchJSON).toHaveBeenCalledTimes(2)
97
+ })
98
+
99
+ it('requires no named check when nothing contradicts the namespace grant on this Pod', () => {
100
+ client.setQueryData([...podDebugAccessKey('demo', 'checkout', 'old-uid'), false], { state: 'denied' })
101
+ render('tools')
102
+ expect(fetchJSON).not.toHaveBeenCalled()
103
+ })
104
+
105
+ it.each([
106
+ [{ state: 'unknown', exec: true, image: 'operator-default' }, 'operator-default'],
107
+ [{ state: 'unknown', exec: true }, undefined],
108
+ [{ state: 'unknown', image: 'operator-default' }, undefined],
109
+ [{ state: 'denied', exec: true, image: 'ignored' }, undefined],
110
+ ] as const)('requires both named exec and an effective image before offering an unverified attempt', async (access, expected) => {
111
+ vi.mocked(fetchJSON).mockResolvedValue(access)
112
+ render()
113
+ await vi.waitFor(() => expect(host.textContent).toBe(access.state))
114
+ expect(host.querySelector('span')?.dataset.unverifiedImage).toBe(expected)
115
+ })
116
+
117
+ it('retains the actual write refusal until named RBAC settles, and requires a deliberate recheck before another review', async () => {
118
+ const undecided = { state: 'unknown', exec: true, image: 'tools' }
119
+ vi.mocked(fetchJSON).mockResolvedValue(undecided)
120
+ function Review() {
121
+ const { query, unverifiedReview, recheckAccess } = usePodDebugAccess('demo', 'checkout', 'uid-1', true)
122
+ return <><output>{query.data?.state} {query.data?.refusedAttempt?.message}</output>
123
+ <button id="refuse" onClick={() => unverifiedReview?.rememberRefusal('Image policy refused the Pod update')}/>
124
+ <button id="check" onClick={() => void recheckAccess()}/>
125
+ <span>{unverifiedReview && (!unverifiedReview.refused || unverifiedReview.refused.rechecked) ? 'review available' : 'no review'}</span></>
126
+ }
127
+ act(() => root.render(<QueryClientProvider client={client}><Review/></QueryClientProvider>))
128
+ await vi.waitFor(() => expect(host.textContent).toContain('review available'))
129
+ act(() => host.querySelector<HTMLButtonElement>('#refuse')!.click())
130
+ await vi.waitFor(() => expect(fetchJSON).toHaveBeenCalledTimes(2))
131
+ await vi.waitFor(() => expect(host.textContent).toContain('Image policy refused the Pod updateno review'))
132
+ act(() => host.querySelector<HTMLButtonElement>('#check')!.click())
133
+ await vi.waitFor(() => expect(host.textContent).toContain('Image policy refused the Pod updatereview available'))
134
+ vi.mocked(fetchJSON).mockResolvedValue({ state: 'denied', exec: true })
135
+ act(() => host.querySelector<HTMLButtonElement>('#check')!.click())
136
+ await vi.waitFor(() => expect(host.textContent).toBe('denied Image policy refused the Pod updateno review'))
137
+ })