@skyhook-io/radar-app 1.21.3 → 1.21.5

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 (42) hide show
  1. package/package.json +1 -1
  2. package/src/App.tsx +3 -0
  3. package/src/api/client.ts +42 -2
  4. package/src/api/radarFeatures.ts +2 -0
  5. package/src/api/vulnerabilities.export.test.ts +44 -0
  6. package/src/api/vulnerabilities.ts +73 -4
  7. package/src/components/applications/ApplicationsView.tsx +38 -8
  8. package/src/components/applications/ArgoSyncDetails.tsx +32 -0
  9. package/src/components/applications/RenderedChanges.test.tsx +179 -0
  10. package/src/components/applications/RenderedChanges.tsx +233 -0
  11. package/src/components/audit/AuditView.tsx +2 -1
  12. package/src/components/audit/VulnerabilitiesView.test.tsx +177 -0
  13. package/src/components/audit/VulnerabilitiesView.tsx +197 -48
  14. package/src/components/diagnose/investigationEvidence/adapters/helm.test.tsx +30 -0
  15. package/src/components/diagnose/investigationEvidence/adapters/helm.ts +21 -1
  16. package/src/components/diagnose/investigationEvidence/bodies/platform.tsx +9 -0
  17. package/src/components/diagnose/investigationEvidence/types.ts +12 -0
  18. package/src/components/helm/HelmReleaseDrawer.test.ts +27 -0
  19. package/src/components/helm/HelmReleaseDrawer.tsx +24 -3
  20. package/src/components/helm/HelmView.tsx +16 -6
  21. package/src/components/helm/ObservedHelmReleaseDrawer.tsx +3 -0
  22. package/src/components/helm/releaseController.test.tsx +26 -0
  23. package/src/components/helm/releaseController.tsx +98 -0
  24. package/src/components/resources/renderers/K3sHelmChartRenderer.tsx +18 -0
  25. package/src/components/traffic/TrafficGraph.export.test.tsx +57 -0
  26. package/src/components/traffic/TrafficGraph.tsx +11 -20
  27. package/src/components/traffic/TrafficView.layoutUnavailable.test.tsx +1 -0
  28. package/src/components/traffic/TrafficView.tsx +17 -2
  29. package/src/components/traffic/traffic-export.test.ts +51 -0
  30. package/src/components/traffic/traffic-export.ts +114 -0
  31. package/src/components/traffic/trafficFilters.ts +16 -0
  32. package/src/components/vulnerabilities/WorkloadVulnerabilitiesSection.test.tsx +30 -1
  33. package/src/components/vulnerabilities/WorkloadVulnerabilitiesSection.tsx +3 -2
  34. package/src/components/vulnerabilities/parts.test.ts +59 -3
  35. package/src/components/vulnerabilities/parts.tsx +199 -5
  36. package/src/components/workload/WorkloadRevisionsButton.test.tsx +34 -0
  37. package/src/components/workload/WorkloadRevisionsButton.tsx +31 -0
  38. package/src/components/workload/WorkloadView.tsx +11 -3
  39. package/src/hooks/useDesktopDownload.test.tsx +57 -0
  40. package/src/hooks/useDesktopDownload.ts +31 -9
  41. package/src/integrations/resourceHosts.test.tsx +1 -1
  42. package/src/integrations/resourceHosts.tsx +2 -0
@@ -0,0 +1,179 @@
1
+ // @vitest-environment jsdom
2
+ import { act, type ReactNode } from "react";
3
+ import { createRoot } from "react-dom/client";
4
+ import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
5
+ import { ArgoSyncDetails } from "./ArgoSyncDetails";
6
+ import { RenderedChanges } from "./RenderedChanges";
7
+ import type { RenderedFieldChange, RenderedResourceChange } from "../../api/client";
8
+
9
+ const hooks = vi.hoisted(() => ({
10
+ useArgoStatus: vi.fn(), useArgoSyncDiff: vi.fn(), useGitOpsInsights: vi.fn(),
11
+ }));
12
+ vi.mock("../../api/client", () => hooks);
13
+ const source = { type: "gitops", kind: "Application", namespace: "argo", name: "checkout" } as const;
14
+ const git = { repoURL: "https://git.example/repo", historyID: "5", previousRevision: "a".repeat(40) };
15
+ const revision = "b".repeat(40);
16
+ const template = ["spec", "template"];
17
+ const annotation = (key: string, prefix: string[] = []): RenderedFieldChange => ({
18
+ path: [...prefix, "metadata", "annotations", key], before: "old", after: "new",
19
+ });
20
+ const resource = (fields: RenderedFieldChange[]): RenderedResourceChange => ({
21
+ group: "apps", kind: "Deployment", namespace: "prod", name: "checkout", operation: "modified", fields,
22
+ });
23
+
24
+ let container: HTMLDivElement;
25
+ let root: ReturnType<typeof createRoot>;
26
+ beforeEach(() => {
27
+ vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);
28
+ container = document.createElement("div");
29
+ root = createRoot(container);
30
+ hooks.useArgoStatus.mockReturnValue({ data: { connected: true } });
31
+ hooks.useGitOpsInsights.mockReturnValue({});
32
+ });
33
+ afterEach(async () => {
34
+ await act(async () => root.unmount());
35
+ vi.resetAllMocks();
36
+ vi.unstubAllGlobals();
37
+ });
38
+ async function render(node: ReactNode) { await act(async () => root.render(node)); }
39
+ async function open(disclosure: HTMLDetailsElement) {
40
+ await act(async () => { disclosure.open = true; disclosure.dispatchEvent(new Event("toggle")); });
41
+ }
42
+
43
+ describe("rendered resource changes", () => {
44
+ it("shows the requested image and functional changes ahead of exact, inspectable deployment annotations", async () => {
45
+ const image = { path: [...template, "spec", "containers", "[name=checkout]", "image"], before: "checkout:02", after: "checkout:01" };
46
+ const changes = [resource([
47
+ annotation("deployment-id"), annotation("deployment-timestamp", template),
48
+ { ...annotation("build.run.url"), after: "https://ci.example/build/4" },
49
+ annotation("checksum/config", template), image, { path: ["spec", "replicas"], before: 2, after: 3 },
50
+ ])];
51
+ await render(<RenderedChanges diff={{ changes }} />);
52
+ expect(container.textContent).toContain("Image change");
53
+ expect(container.textContent).toContain("checkout:02");
54
+ expect(container.textContent).toContain("checkout:01");
55
+ const imageRow = container.querySelector("tbody tr")!;
56
+ expect(imageRow.querySelector("del")?.textContent).toBe("02");
57
+ expect(imageRow.querySelector("ins")?.textContent).toBe("01");
58
+ expect(container.textContent).toContain("checksum/config");
59
+ expect(container.textContent).toContain("spec.replicas");
60
+ expect(container.textContent).toContain("Deployment metadata (3 changes)");
61
+ expect(container.textContent).not.toContain("deployment-timestamp");
62
+ expect(container.querySelector("a")?.href).toBe("https://ci.example/build/4");
63
+ await open(container.querySelector("details")!);
64
+ expect(container.textContent).toContain("deployment-id");
65
+ expect(container.textContent).toContain("deployment-timestamp");
66
+ });
67
+
68
+ it("preserves the complete values and highlights separated edits and one-sided changes", async () => {
69
+ await render(<RenderedChanges diff={{ changes: [resource([
70
+ { path: ["data", "url"], before: "https://old.example/runs/1042", after: "https://new.example/runs/1041" },
71
+ { path: ["spec", "flag"], before: false },
72
+ ])] }} />);
73
+ const [url, flag] = container.querySelectorAll("tbody tr");
74
+ expect([...url.querySelectorAll("del")].map(mark => mark.textContent)).toEqual(["old", "1042"]);
75
+ expect([...url.querySelectorAll("ins")].map(mark => mark.textContent)).toEqual(["new", "1041"]);
76
+ expect([...url.querySelectorAll("code")].map(code => code.textContent)).toEqual([
77
+ "https://old.example/runs/1042", "https://new.example/runs/1041",
78
+ ]);
79
+ expect(flag.querySelector("del")?.textContent).toBe("false");
80
+ expect(flag.querySelector("ins")).toBeNull();
81
+ });
82
+
83
+ it("groups only repeated version label transitions and preserves all their resource paths", async () => {
84
+ const version = (prefix: string[] = [], before = "v1"): RenderedFieldChange => ({
85
+ path: [...prefix, "metadata", "labels", "app.kubernetes.io/version"], before, after: "v2",
86
+ });
87
+ const changes = [
88
+ resource([
89
+ version(), version(template), { path: ["spec", "replicas"], before: 4, after: 5 },
90
+ { path: ["spec", "selector", "matchLabels", "app.kubernetes.io/version"], before: "v1", after: "v2" },
91
+ ]),
92
+ { ...resource([version()]), kind: "Service", group: "" },
93
+ { ...resource([version([], "v0")]), kind: "ConfigMap", group: "" },
94
+ ];
95
+ await render(<RenderedChanges diff={{ changes }} />);
96
+ expect(container.textContent).toContain("spec.replicas");
97
+ expect(container.textContent).toContain('spec.selector.matchLabels["app.kubernetes.io/version"]');
98
+ expect(container.textContent).toContain("v0");
99
+ const group = [...container.querySelectorAll("details")].find(d => d.querySelector("summary")?.textContent?.includes("Version label"))!;
100
+ expect(group.querySelector("summary")?.textContent).toBe("Version label Previous sync: v1 → Selected sync: v2 on 2 resources");
101
+ await open(group);
102
+ expect(group.querySelectorAll("li")).toHaveLength(3);
103
+ expect(group.textContent).toContain('spec.template.metadata.labels["app.kubernetes.io/version"]');
104
+ expect(group.textContent).toContain("Service prod/checkout");
105
+ });
106
+
107
+ it("names existing containers and distinguishes adding a sidecar from changing an existing image", async () => {
108
+ const path = (name: string) => [...template, "spec", "containers", `[name=${name}]`, "image"];
109
+ await render(<RenderedChanges diff={{ changes: [resource([
110
+ { path: path("checkout"), before: "shop:v1", after: "shop:v2" },
111
+ { path: path("proxy"), after: "envoy:v1" },
112
+ { path: [...template, "spec", "containers", "[order]"], before: ["checkout"], after: ["proxy", "checkout"] },
113
+ ])] }} />);
114
+ const imageRows = container.querySelectorAll("table")[0].querySelectorAll("tbody tr");
115
+ expect(imageRows[0].querySelector("del")?.textContent).toBe("1");
116
+ expect(imageRows[0].querySelector("ins")?.textContent).toBe("2");
117
+ expect(imageRows[1].textContent).toContain("Image added");
118
+ expect(imageRows[1].querySelector("del")).toBeNull();
119
+ expect(imageRows[1].querySelector("ins")?.textContent).toBe("envoy:v1");
120
+ expect(container.textContent).toContain("spec.template.spec.containers[order]");
121
+ });
122
+
123
+ it("keeps ConfigMap data, unrelated CR fields and annotation-like keys out of deployment metadata", async () => {
124
+ const changes = [
125
+ { ...resource([{ path: ["data", "deployment-id"], after: "set" }, { path: ["data", "config"], before: "3", after: 3 }]), kind: "ConfigMap", group: "" },
126
+ { ...resource([annotation("deployment-id", template)]), kind: "Custom", group: "example.io" },
127
+ resource([{ path: ["metadata/annotations", "deployment-id"], before: null }, annotation("deployment-id-extra")]),
128
+ ];
129
+ await render(<RenderedChanges diff={{ changes }} />);
130
+ expect(container.textContent).not.toContain("Deployment metadata (");
131
+ expect(container.textContent).toContain('data["deployment-id"]');
132
+ expect(container.textContent).toContain('"3"');
133
+ expect(container.querySelector("del")?.textContent).toBe('"3"');
134
+ expect(container.textContent).toContain("null");
135
+ });
136
+
137
+ it("groups all three CronJob metadata locations and makes metadata-only and partial results distinct", async () => {
138
+ const resourceChange = { ...resource([
139
+ annotation("deployment-id"), annotation("deployment-timestamp", ["spec", "jobTemplate"]),
140
+ { ...annotation("build.run.url", ["spec", "jobTemplate", "spec", "template"]), after: "javascript:alert(1)" },
141
+ ]), kind: "CronJob", group: "batch" };
142
+ await render(<RenderedChanges diff={{ changes: [resourceChange] }} />);
143
+ expect(container.textContent).toContain("Only deployment metadata changed.");
144
+ expect(container.textContent).toContain("Deployment metadata (3 changes)");
145
+ expect(container.querySelector("a")).toBeNull();
146
+ await render(<RenderedChanges diff={{ changes: [resourceChange], partial: true }} />);
147
+ expect(container.textContent).toContain("Partial comparison");
148
+ expect(container.textContent).not.toContain("Only deployment metadata changed.");
149
+ await render(<RenderedChanges diff={{ changes: [], secretsMasked: true }} />);
150
+ expect(container.textContent).toContain("Secret values are masked");
151
+ expect(container.textContent).toContain("No visible field changes");
152
+ await render(<RenderedChanges diff={{ changes: [resource([annotation("deployment-id", template)])] }} />);
153
+ expect(container.textContent).toContain("Pod template annotations changed and can trigger a rollout.");
154
+ await render(<RenderedChanges diff={{ changes: [resource([annotation("deployment-id")])] }} />);
155
+ expect(container.textContent).not.toContain("can trigger a rollout");
156
+ await render(<RenderedChanges diff={{ changes: [] }} />);
157
+ expect(container.textContent).toContain("No rendered resource changes.");
158
+ });
159
+
160
+ it("offers Argo settings when disconnected, keeps stale or denied results hidden and skips same-revision comparisons", async () => {
161
+ hooks.useArgoStatus.mockReturnValue({ data: { connected: false } });
162
+ await render(<ArgoSyncDetails source={source} git={git} revision={revision} />);
163
+ const settings = vi.fn();
164
+ window.addEventListener("radar:open-settings", settings, { once: true });
165
+ container.querySelector("button")!.click();
166
+ expect(settings.mock.calls[0][0].detail.section).toBe("argocd");
167
+ expect(hooks.useArgoSyncDiff).not.toHaveBeenCalled();
168
+
169
+ hooks.useArgoStatus.mockReturnValue({ data: { connected: true } });
170
+ hooks.useArgoSyncDiff.mockReturnValue({ data: { changes: [] }, isError: true, error: Error("Access denied.") });
171
+ await render(<ArgoSyncDetails source={source} git={git} revision={revision} />);
172
+ expect(hooks.useArgoSyncDiff).toHaveBeenCalledWith("argo", "checkout", "5", git.previousRevision, revision);
173
+ expect(container.textContent).toContain("Access denied");
174
+ expect(container.textContent).not.toContain("No rendered resource changes");
175
+ hooks.useArgoSyncDiff.mockClear();
176
+ await render(<ArgoSyncDetails source={source} git={{ ...git, previousRevision: revision }} revision={revision} />);
177
+ expect(hooks.useArgoSyncDiff).not.toHaveBeenCalled();
178
+ });
179
+ });
@@ -0,0 +1,233 @@
1
+ import { useState, type ReactNode } from "react";
2
+ import { diffArrays } from "diff";
3
+ import { ExternalLink } from "lucide-react";
4
+ import type { RenderedFieldChange, RenderedResourceChange, RenderedSyncDiff } from "../../api/client";
5
+
6
+ const deploymentAnnotations = new Set(["build.run.url", "deployment-id", "deployment-timestamp"]);
7
+ const rolloutWorkloads = new Set(["apps/Deployment", "apps/StatefulSet", "apps/DaemonSet", "argoproj.io/Rollout"]);
8
+ const workloadTemplates = new Set([...rolloutWorkloads, "apps/ReplicaSet", "batch/Job", "/ReplicationController"]);
9
+
10
+ function podTemplate(resource: RenderedResourceChange): string[] | undefined {
11
+ const type = `${resource.group ?? ""}/${resource.kind}`;
12
+ if (type === "/Pod") return [];
13
+ if (type === "batch/CronJob") return ["spec", "jobTemplate", "spec", "template"];
14
+ if (workloadTemplates.has(type)) return ["spec", "template"];
15
+ }
16
+
17
+ function matchesPath(path: string[], expected: string[]) {
18
+ return path.length === expected.length && expected.every((part, i) => part === path[i]);
19
+ }
20
+
21
+ function isResourceMetadata(path: string[], section: "labels" | "annotations", resource: RenderedResourceChange, template: string[] | undefined): boolean {
22
+ if (path.at(-2) !== section || path.at(-3) !== "metadata") return false;
23
+ const prefix = path.slice(0, -3);
24
+ return prefix.length === 0 || (template !== undefined && matchesPath(prefix, template)) ||
25
+ (resource.group === "batch" && resource.kind === "CronJob" && matchesPath(prefix, ["spec", "jobTemplate"]));
26
+ }
27
+
28
+ function isContainerImage(path: string[], template: string[] | undefined): boolean {
29
+ return template !== undefined && path.at(-1) === "image" && /^\[name=.+\]$/.test(path.at(-2) ?? "") &&
30
+ ["containers", "initContainers", "ephemeralContainers"].includes(path.at(-3) ?? "") &&
31
+ matchesPath(path.slice(0, -3), [...template, "spec"]);
32
+ }
33
+
34
+ function fieldPath(path: string[]) {
35
+ return path.map((part, i) => {
36
+ if (part === "[order]" || /^\[(name|mountPath)=.+\]$/.test(part)) return part;
37
+ if (/^\d+$/.test(part)) return `[${part}]`;
38
+ if (!/^[A-Za-z_][A-Za-z_0-9]*$/.test(part)) return `[${JSON.stringify(part)}]`;
39
+ return i ? `.${part}` : part;
40
+ }).join("");
41
+ }
42
+
43
+ function buildURL(value: unknown) {
44
+ if (typeof value !== "string") return;
45
+ try {
46
+ const url = new URL(value);
47
+ if (url.protocol === "https:" && !url.username && !url.password) return url.href;
48
+ } catch { /* Annotation values can be arbitrary strings. */ }
49
+ }
50
+
51
+ function displayValue(value: unknown, other: unknown): string | undefined {
52
+ if (value === undefined) return undefined;
53
+ // Quote strings on a type change so "3" → 3 and "null" → null remain distinguishable.
54
+ if (typeof value === "string" && value !== "" && (other === undefined || typeof other === "string")) return value;
55
+ return JSON.stringify(value, null, 2);
56
+ }
57
+
58
+ function ValueDiff({ before, after, inline = false }: { before: unknown; after: unknown; inline?: boolean }) {
59
+ const previous = displayValue(before, after);
60
+ const selected = displayValue(after, before);
61
+ // Keep numeric runs together: the useful units in image tags and build URLs are version components and IDs.
62
+ const tokens = /\p{L}+|\p{N}+|\s+|[^\s]/gu;
63
+ const parts = typeof before === "string" && typeof after === "string" && previous !== undefined && selected !== undefined &&
64
+ previous.length + selected.length <= 4096
65
+ ? diffArrays(previous.match(tokens) ?? [], selected.match(tokens) ?? [], { maxEditLength: 64 })
66
+ : undefined;
67
+
68
+ function side(text: string | undefined, added: boolean) {
69
+ if (text === undefined) return null;
70
+ const Mark = added ? "ins" : "del";
71
+ const highlight = added ? "bg-[var(--color-success)]/20" : "bg-semantic-error/20";
72
+ const markClass = `${highlight} rounded-sm font-semibold text-theme-text-primary no-underline`;
73
+ const value = <code className="min-w-0 whitespace-pre-wrap break-all text-theme-text-secondary">{parts ? parts.map((part, i) => {
74
+ if (added ? part.removed : part.added) return null;
75
+ const content = part.value.join("");
76
+ return (added ? part.added : part.removed) ? <Mark className={markClass} key={i}>{content}</Mark> : content;
77
+ }) : <Mark className={markClass}>{text}</Mark>}</code>;
78
+ const label = <span className="sr-only">{added ? "Selected sync: " : "Previous sync: "}</span>;
79
+ if (inline) return <>{label}{value}</>;
80
+ return <span className="flex items-baseline gap-2">
81
+ <span aria-hidden="true" className={`w-3 shrink-0 select-none text-center font-mono font-bold ${added ? "text-green-700 dark:text-green-300" : "text-red-700 dark:text-red-300"}`}>{added ? "+" : "−"}</span>
82
+ {label}{value}
83
+ </span>;
84
+ }
85
+
86
+ if (inline) return <>{side(previous, false)} → {side(selected, true)}</>;
87
+ return <div className="space-y-0.5">{side(previous, false)}{side(selected, true)}</div>;
88
+ }
89
+
90
+ function ChangeValues({ fields, images = false }: { fields: RenderedFieldChange[]; images?: boolean }) {
91
+ return <div className="overflow-x-auto rounded border border-theme-border bg-theme-surface">
92
+ <table className="w-full table-fixed text-left text-xs">
93
+ <thead className="border-b border-theme-border text-theme-text-secondary">
94
+ <tr>
95
+ <th scope="col" className="w-1/3 px-3 py-1.5 font-medium sm:w-64">{images ? "Container" : "Field"}</th>
96
+ <th scope="col" className="px-3 py-1.5 font-medium">{images ? "Image change" : "Change"}</th>
97
+ </tr>
98
+ </thead>
99
+ <tbody>{fields.map(field => <tr key={JSON.stringify(field.path)} className="border-b border-theme-border align-top last:border-0">
100
+ <th scope="row" className="break-all px-3 py-2 text-left font-mono font-normal" aria-label={images ? fieldPath(field.path) : undefined}>
101
+ {images ? <>
102
+ {field.path.at(-2)!.slice("[name=".length, -1)}
103
+ <span className="block font-sans text-theme-text-secondary">
104
+ {field.path.at(-3) === "initContainers" && "Init container "}
105
+ {field.path.at(-3) === "ephemeralContainers" && "Ephemeral container "}
106
+ {field.before === undefined && "Image added"}{field.after === undefined && "Image removed"}
107
+ </span>
108
+ </> : fieldPath(field.path)}
109
+ </th>
110
+ <td className="px-3 py-2"><ValueDiff before={field.before} after={field.after} /></td>
111
+ </tr>)}</tbody>
112
+ </table>
113
+ </div>;
114
+ }
115
+
116
+ function Disclosure({ label, children }: { label: ReactNode; children: ReactNode }) {
117
+ const [open, setOpen] = useState(false);
118
+ return <details onToggle={event => setOpen(event.currentTarget.open)}>
119
+ <summary className="cursor-pointer py-1 text-xs font-medium text-theme-text-secondary hover:text-theme-text-primary">{label}</summary>
120
+ {open && <div className="mt-1 space-y-2">{children}</div>}
121
+ </details>;
122
+ }
123
+
124
+ function resourceName(resource: RenderedResourceChange) {
125
+ return [resource.namespace, resource.name].filter(Boolean).join("/");
126
+ }
127
+
128
+ function ResourceTitle({ resource }: { resource: RenderedResourceChange }) {
129
+ return <p className="flex flex-wrap items-baseline gap-x-2">
130
+ <span className="break-all font-medium text-theme-text-primary">{resource.kind} <span className="font-mono">{resourceName(resource)}</span></span>
131
+ {resource.group && <span className="text-xs text-theme-text-tertiary">{resource.group}</span>}
132
+ {resource.operation !== "modified" && <span className="text-xs font-medium">{resource.operation === "added" ? "Added" : "Removed"}</span>}
133
+ </p>;
134
+ }
135
+
136
+ export function RenderedChanges({ diff }: { diff: RenderedSyncDiff }) {
137
+ type VersionChange = { resource: RenderedResourceChange; field: RenderedFieldChange };
138
+ const versions = new Map<string, VersionChange[]>();
139
+ for (const resource of diff.changes) {
140
+ if (resource.operation !== "modified") continue;
141
+ const template = podTemplate(resource);
142
+ for (const field of resource.fields) {
143
+ if (field.path.at(-1) !== "app.kubernetes.io/version" || typeof field.before !== "string" || typeof field.after !== "string" ||
144
+ !isResourceMetadata(field.path, "labels", resource, template)) continue;
145
+ const key = JSON.stringify([field.before, field.after]);
146
+ const entry = { resource, field };
147
+ const changes = versions.get(key);
148
+ if (changes) changes.push(entry);
149
+ else versions.set(key, [entry]);
150
+ }
151
+ }
152
+ const repeatedVersions = [...versions.values()].filter(entries => entries.length > 1);
153
+ const groupedFields = new Set(repeatedVersions.flatMap(entries => entries.map(entry => entry.field)));
154
+ const groups = diff.changes.map(resource => {
155
+ const template = podTemplate(resource);
156
+ const metadata: RenderedFieldChange[] = [], images: RenderedFieldChange[] = [], fields: RenderedFieldChange[] = [];
157
+ for (const field of resource.fields) {
158
+ if (groupedFields.has(field)) continue;
159
+ if (deploymentAnnotations.has(field.path.at(-1) ?? "") && isResourceMetadata(field.path, "annotations", resource, template)) metadata.push(field);
160
+ else if (isContainerImage(field.path, template)) images.push(field);
161
+ else fields.push(field);
162
+ }
163
+ // Show spec/config changes above repeated labels and resource identity fields.
164
+ fields.sort((a, b) => Number(["metadata", "apiVersion", "kind"].includes(a.path[0])) -
165
+ Number(["metadata", "apiVersion", "kind"].includes(b.path[0])));
166
+ return { resource, images, fields, metadata, key: JSON.stringify([resource.group, resource.kind, resource.namespace, resource.name]) };
167
+ });
168
+ const substantive = groups.filter(g => g.fields.length || g.images.length).sort((a, b) => Number(!!b.images.length) - Number(!!a.images.length));
169
+ const metadataOnlyOrEmpty = substantive.length === 0 && repeatedVersions.length === 0;
170
+ const metadataGroups = groups.filter(g => g.metadata.length);
171
+ const metaCount = metadataGroups.reduce((n, g) => n + g.metadata.length, 0);
172
+ const rolloutTemplateChanged = metadataGroups.some(({ resource, metadata }) =>
173
+ rolloutWorkloads.has(`${resource.group}/${resource.kind}`) &&
174
+ metadata.some(field => matchesPath(field.path.slice(0, -3), ["spec", "template"])));
175
+ const builds = new Set<string>();
176
+ for (const group of metadataGroups) for (const field of group.metadata) {
177
+ if (field.path.at(-1) === "build.run.url") {
178
+ const url = buildURL(field.after);
179
+ if (url) builds.add(url);
180
+ }
181
+ }
182
+ return <section aria-label="Rendered changes" className="space-y-3 rounded-lg border border-theme-border bg-theme-surface p-3">
183
+ <div>
184
+ <h3 className="font-semibold text-theme-text-primary">Rendered changes</h3>
185
+ <p className="text-xs text-theme-text-secondary">Desired resources rendered by Argo CD at both Git revisions.</p>
186
+ </div>
187
+ {diff.partial && <p className="text-xs text-amber-700 dark:text-amber-300">Partial comparison. Some resources could not be included.</p>}
188
+ {diff.secretsMasked && <p className="text-xs text-theme-text-secondary">Secret values are masked. Changes to those values may be unavailable.</p>}
189
+ {metadataOnlyOrEmpty && <p>{metaCount
190
+ ? (diff.partial || diff.secretsMasked ? "The visible changes are deployment metadata." : "Only deployment metadata changed.")
191
+ : (diff.partial || diff.secretsMasked ? "No visible field changes." : "No rendered resource changes.")}</p>}
192
+ {metadataOnlyOrEmpty && rolloutTemplateChanged && <p className="text-xs text-theme-text-secondary">
193
+ Pod template annotations changed and can trigger a rollout.
194
+ </p>}
195
+ {substantive.map(({ resource, fields, images, key }, index) => {
196
+ const previewCount = index < 4 ? Math.min(fields.length, 2) : 0;
197
+ const remaining = fields.length - previewCount;
198
+ return <div key={key} className="space-y-1.5">
199
+ <ResourceTitle resource={resource} />
200
+ {!!images.length && <ChangeValues fields={images} images />}
201
+ {previewCount > 0 && <ChangeValues fields={fields.slice(0, previewCount)} />}
202
+ {remaining > 0 && <Disclosure label={`${remaining} ${previewCount || images.length ? "more " : ""}field ${remaining === 1 ? "change" : "changes"}`}>
203
+ <ChangeValues fields={fields.slice(previewCount)} />
204
+ </Disclosure>}
205
+ </div>;
206
+ })}
207
+ {repeatedVersions.map(entries => {
208
+ const { before, after } = entries[0].field;
209
+ const resources = new Set(entries.map(entry => entry.resource)).size;
210
+ return <Disclosure key={JSON.stringify([before, after])} label={<>
211
+ Version label <ValueDiff before={before} after={after} inline /> on {resources} {resources === 1 ? "resource" : "resources"}
212
+ </>}>
213
+ <ul className="space-y-1">
214
+ {entries.map(({ resource, field }) => <li key={JSON.stringify([resource.kind, resource.group, resource.namespace, resource.name, field.path])} className="text-xs">
215
+ <span className="font-medium">{resource.kind} {resourceName(resource)}{resource.group && ` (${resource.group})`}</span>
216
+ {" · "}<code className="break-all">{fieldPath(field.path)}</code>
217
+ </li>)}
218
+ </ul>
219
+ </Disclosure>;
220
+ })}
221
+ {!!metaCount && <div className="border-t border-theme-border pt-2">
222
+ <Disclosure label={`Deployment metadata (${metaCount} ${metaCount === 1 ? "change" : "changes"})`}>
223
+ {metadataGroups.map(({ resource, metadata, key }) => <div className="space-y-1" key={key}>
224
+ <ResourceTitle resource={resource} />
225
+ <ChangeValues fields={metadata} />
226
+ </div>)}
227
+ </Disclosure>
228
+ {[...builds].map(url => <a key={url} href={url} target="_blank" rel="noopener noreferrer" className="mr-3 inline-flex items-center gap-1 text-xs font-medium text-accent-text hover:underline">
229
+ {builds.size === 1 ? "View build run" : url} <ExternalLink aria-hidden className="h-3 w-3" />
230
+ </a>)}
231
+ </div>}
232
+ </section>;
233
+ }
@@ -116,7 +116,7 @@ function BestPracticesView({ namespaces, onNavigateToResource }: AuditViewProps)
116
116
  <button onClick={() => setShowSettings(true)} className="text-xs text-theme-text-tertiary hover:text-theme-text-secondary transition-colors">{ignoredCount} {ignoredCount === 1 ? 'namespace' : 'namespaces'} hidden</button>
117
117
  )}
118
118
  {annotationIgnored > 0 && (
119
- <Tooltip content={`Resources that opted out of a check with the ${data.ignoreChecksAnnotation} annotation`}>
119
+ <Tooltip content={`${data.namespaceIgnoreChecks ? 'Resources or namespaces' : 'Resources'} that opted out of a check with the ${data.ignoreChecksAnnotation} annotation`}>
120
120
  <span className="text-xs text-theme-text-tertiary">{annotationIgnored} {annotationIgnored === 1 ? 'finding' : 'findings'} hidden by annotation</span>
121
121
  </Tooltip>
122
122
  )}
@@ -142,6 +142,7 @@ function BestPracticesView({ namespaces, onNavigateToResource }: AuditViewProps)
142
142
  onHideCheck={canEdit ? hideCheck : undefined}
143
143
  onHideCategory={canEdit ? hideCategory : undefined}
144
144
  ignoreChecksAnnotation={data.ignoreChecksAnnotation}
145
+ namespaceIgnoreChecks={data.namespaceIgnoreChecks}
145
146
  />
146
147
 
147
148
  {showSettings && <AuditSettingsDialog namespaces={namespaces} onClose={() => setShowSettings(false)} />}
@@ -0,0 +1,177 @@
1
+ // @vitest-environment jsdom
2
+ import { act } from 'react'
3
+ import { createRoot, type Root } from 'react-dom/client'
4
+ import { MemoryRouter, useLocation } from 'react-router-dom'
5
+ import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
6
+ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
7
+ import { useVulnerabilities, type VulnerabilitiesResponse, type VulnerabilityWorkloadRef } from '../../api/vulnerabilities'
8
+ import { VulnerabilitiesView } from './VulnerabilitiesView'
9
+
10
+ vi.mock('../../api/client', async (importOriginal) => ({
11
+ ...await importOriginal<typeof import('../../api/client')>(),
12
+ useCapabilities: () => ({ data: { features: {} } }),
13
+ useRadarFeature: () => ({ support: 'unsupported', guard: <T,>(fn: () => T) => fn() }),
14
+ }))
15
+ vi.mock('../../api/apiResources', () => ({ useAPIResources: () => ({ data: [{ group: 'aquasecurity.github.io', name: 'vulnerabilityreports' }] }) }))
16
+ vi.mock('../../context/ConnectionContext', () => ({ useConnection: () => ({ connection: { context: 'test', clusterName: 'test', state: 'connected' } }) }))
17
+ vi.mock('../../hooks/useDesktopDownload', () => ({ useDesktopDownload: () => undefined }))
18
+ vi.mock('./ChecksViewTabs', () => ({ ChecksViewTabs: () => null }))
19
+ vi.mock('../../api/vulnerabilities', async (importOriginal) => ({
20
+ ...await importOriginal<typeof import('../../api/vulnerabilities')>(),
21
+ useVulnerabilities: vi.fn(),
22
+ }))
23
+
24
+ Object.assign(globalThis, { IS_REACT_ACT_ENVIRONMENT: true })
25
+
26
+ const zero = { critical: 0, high: 0, medium: 0, low: 0, unknown: 0 }
27
+ const ref = (name: string, namespace = 'shop'): VulnerabilityWorkloadRef => ({ kind: 'Deployment', group: 'apps', namespace, name, container: 'app' })
28
+ const route = { via: 'LoadBalancer', namespace: 'shop', name: 'web' }
29
+
30
+ function response(view: VulnerabilitiesResponse['view'], withExposure: boolean): VulnerabilitiesResponse {
31
+ const base: VulnerabilitiesResponse = {
32
+ source: 'trivy',
33
+ view,
34
+ summary: { imagesScanned: 1, imagesClean: 0, imagesUnscanned: 0, imagesWithCritical: 1, fixableCriticalHighCves: 1, workloadsWithCriticalOrHigh: 2, workloads: 3, counts: { ...zero, critical: 1 } },
35
+ coverage: { complete: true, gaps: [], inactiveReports: 0 },
36
+ }
37
+ const exposed = withExposure ? { exposed: [{ kind: 'Deployment', group: 'apps', namespace: 'shop', name: 'web', routes: [route] }], exposedTotal: 1 } : {}
38
+ const image = {
39
+ id: 'img', image: 'example.com/shop/app:1', scannedAt: '2026-11-20T12:00:00Z', counts: { ...zero, critical: 1 }, fixable: { ...zero, critical: 1 },
40
+ matching: 1, workloads: [ref('web'), ref('worker')], workloadsTotal: 2, findings: [], findingsTotal: 1,
41
+ report: { kind: 'VulnerabilityReport', namespace: 'shop', name: 'r' }, ...exposed,
42
+ }
43
+ return {
44
+ ...base,
45
+ ...(withExposure ? { exposure: { gaps: [{ code: 'user_forbidden', kinds: { count: 1, names: [{ kind: 'Ingress', group: 'networking.k8s.io' }] }, namespaces: { count: 1, names: ['hidden'] } }] } } : {}),
46
+ images: [image],
47
+ fixes: [{
48
+ package: 'zlib', from: ['1.0'], to: '1.1', severity: 'critical', counts: { ...zero, critical: 1 }, cves: ['CVE-1'], cvesTotal: 1, images: 1, workloads: 2,
49
+ affected: [{ imageId: 'img', image: image.image, installedVersions: ['1.0'], workloads: image.workloads, workloadsTotal: 2 }], ...exposed,
50
+ }],
51
+ workloads: [
52
+ { kind: 'Deployment', group: 'apps', namespace: 'shop', name: 'web', counts: { ...zero, critical: 1 }, fixable: zero, containers: [], ...(withExposure ? { routes: [route, { via: 'Ingress', namespace: 'shop', name: 'web' }] } : {}) },
53
+ { kind: 'Deployment', group: 'apps', namespace: 'hidden', name: 'secret', counts: { ...zero, critical: 1 }, fixable: zero, containers: [] },
54
+ { kind: 'Deployment', group: 'apps', namespace: 'shop', name: 'worker', counts: { ...zero, critical: 1 }, fixable: zero, containers: [] },
55
+ ],
56
+ }
57
+ }
58
+
59
+ let container: HTMLDivElement
60
+ let root: Root
61
+ function Probe() {
62
+ return <output data-testid="location">{useLocation().search}</output>
63
+ }
64
+
65
+ const urlParams = () => new URLSearchParams(container.querySelector('[data-testid="location"]')!.textContent ?? '')
66
+
67
+ function render(path: string, withExposure = true) {
68
+ vi.mocked(useVulnerabilities).mockImplementation((p) => ({
69
+ data: response(p.view, withExposure), isLoading: false, isFetching: false, isPlaceholderData: false, error: null, dataUpdatedAt: 0, refetch: vi.fn(),
70
+ } as unknown as ReturnType<typeof useVulnerabilities>))
71
+ const client = new QueryClient({ defaultOptions: { queries: { retry: false, enabled: false } } })
72
+ act(() => root.render(
73
+ <QueryClientProvider client={client}>
74
+ <MemoryRouter initialEntries={[path]}>
75
+ <VulnerabilitiesView namespaces={[]} onNavigateToResource={vi.fn()} />
76
+ <Probe />
77
+ </MemoryRouter>
78
+ </QueryClientProvider>,
79
+ ))
80
+ }
81
+
82
+ const button = (label: string) => Array.from(container.querySelectorAll('button')).find((b) => b.textContent?.trim() === label)
83
+ const lastParams = () => vi.mocked(useVulnerabilities).mock.calls.at(-1)![0]
84
+ const marks = () => container.querySelectorAll('svg[aria-label^="Exposed via"]')
85
+
86
+ beforeEach(() => {
87
+ container = document.createElement('div')
88
+ document.body.appendChild(container)
89
+ root = createRoot(container)
90
+ vi.mocked(useVulnerabilities).mockReset()
91
+ })
92
+
93
+ afterEach(() => {
94
+ act(() => root.unmount())
95
+ container.remove()
96
+ })
97
+
98
+ describe('VulnerabilitiesView', () => {
99
+ it('opens By fix by default and sets by only for the other views', () => {
100
+ render('/checks/vulnerabilities')
101
+ expect(lastParams().view).toBe('fix')
102
+ expect(button('By fix')?.getAttribute('aria-pressed')).toBe('true')
103
+
104
+ act(() => button('By image')!.click())
105
+ expect(urlParams().get('by')).toBe('image')
106
+ expect(lastParams().view).toBe('image')
107
+
108
+ act(() => button('By fix')!.click())
109
+ expect(urlParams().has('by')).toBe(false)
110
+ expect(lastParams().view).toBe('fix')
111
+ })
112
+
113
+ it('filters to exposed rows through the URL and the request', () => {
114
+ render('/checks/vulnerabilities?by=cve')
115
+ expect(lastParams().exposed).toBe(false)
116
+ act(() => button('Exposed')!.click())
117
+ expect(urlParams().get('exposed')).toBe('1')
118
+ expect(lastParams().exposed).toBe(true)
119
+ act(() => button('Exposed')!.click())
120
+ expect(urlParams().has('exposed')).toBe(false)
121
+ })
122
+
123
+ it('marks only the exposed workload when a row runs in both', () => {
124
+ render('/checks/vulnerabilities?by=image')
125
+ // Collapsed "Running in": web leads with the mark, worker has none.
126
+ expect(marks()).toHaveLength(1)
127
+ const running = marks()[0].closest('span.truncate')!
128
+ expect(running.textContent).toBe('web, worker')
129
+ act(() => container.querySelector<HTMLButtonElement>('button[aria-expanded]')!.click())
130
+ // Expanded: the mark sits beside web's link only.
131
+ const marked = Array.from(marks()).map((m) => m.closest('li')?.textContent ?? '').filter(Boolean)
132
+ expect(marked).toHaveLength(1)
133
+ expect(marked[0]).toContain('web')
134
+ expect(marked[0]).not.toContain('worker')
135
+ })
136
+
137
+ it('counts the exposed workloads beside the mark on rows that span workloads', () => {
138
+ render('/checks/vulnerabilities')
139
+ expect(container.textContent).toContain('1 exposed')
140
+ expect(container.textContent).not.toMatch(/\d+ of \d+ exposed/)
141
+ render('/checks/vulnerabilities', false)
142
+ expect(container.textContent).not.toContain('exposed')
143
+ })
144
+
145
+ it('shows the route, nothing, or Exposure unknown per workload', () => {
146
+ render('/checks/vulnerabilities?by=workload')
147
+ const rows = Array.from(container.querySelectorAll<HTMLButtonElement>('button[aria-expanded]'))
148
+ const cell = (i: number) => rows[i].querySelector('div.grid')!.children[2].textContent
149
+ expect(cell(0)).toBe('LoadBalancer shop/web and 1 more')
150
+ expect(cell(1)).toBe('Exposure unknown')
151
+ expect(cell(2)).toBe('')
152
+ })
153
+
154
+ it('leaves out the chip, sort hint, mark and route column when Radar reports no exposure', () => {
155
+ render('/checks/vulnerabilities', false)
156
+ expect(button('Exposed')).toBeUndefined()
157
+ expect(container.textContent).not.toContain('Severity, then exposure')
158
+ expect(marks()).toHaveLength(0)
159
+
160
+ render('/checks/vulnerabilities?by=workload', false)
161
+ expect(container.textContent).not.toContain('Exposed via')
162
+ expect(container.textContent).not.toContain('Exposure unknown')
163
+ })
164
+
165
+ it('keeps the sort rule in a hint, not a line above the table', () => {
166
+ render('/checks/vulnerabilities')
167
+ expect(container.textContent).toContain('Severity, then exposure')
168
+ expect(container.textContent).not.toContain('Sorted:')
169
+ expect(container.querySelector('[aria-label^="Sort: Most severe first"]')).not.toBeNull()
170
+ })
171
+
172
+ it('names the rebuild caveat on the Upgrade header instead of a line', () => {
173
+ render('/checks/vulnerabilities')
174
+ expect(container.textContent).not.toContain('Upgrading a package')
175
+ })
176
+
177
+ })