From 9d0e9cac1302d692048fb870324ab90a65593bc9 Mon Sep 17 00:00:00 2001 From: Justin Middler Date: Sun, 22 Nov 2026 10:10:01 +1100 Subject: [PATCH] feat(console): add journald and Kubernetes guided source setup plus live redacted tap preview (#99) --- .../SourceSetupJournald.cs | 163 ++++++++++++++ .../SourceSetupKubernetes.cs | 212 ++++++++++++++++++ .../SourceSetupRegistry.cs | 2 + tests/Bower.UnitTests/SourceSetupApiTests.cs | 59 ++++- .../src/pages/SourcesPage.test.tsx | 37 +++ .../src/pages/SourcesPage.tsx | 66 +++++- 6 files changed, 537 insertions(+), 2 deletions(-) create mode 100644 src/Bower.Management.Api/SourceSetupJournald.cs create mode 100644 src/Bower.Management.Api/SourceSetupKubernetes.cs diff --git a/src/Bower.Management.Api/SourceSetupJournald.cs b/src/Bower.Management.Api/SourceSetupJournald.cs new file mode 100644 index 00000000..b74afd1a --- /dev/null +++ b/src/Bower.Management.Api/SourceSetupJournald.cs @@ -0,0 +1,163 @@ +using System.Globalization; +using System.Text.Json.Nodes; +using System.Text.RegularExpressions; +using static Bower.Management.Api.SourceSetupRegistry; + +namespace Bower.Management.Api; + +/// +/// Bounded, allow-listed systemd journald source (src/Bower.Source.Journald, +/// docs/deployment/journald-source.md). Enforces explicit systemd unit or +/// SYSLOG_IDENTIFIER allow-lists (no empty list, no wildcards) and durable cursor tracking. +/// +internal sealed partial class JournaldSourceSetup : SourceSetupType +{ + public override string Id => "journald"; + + public override string Title => "Linux systemd journald"; + + public override string Summary => + "Reads allow-listed systemd units or syslog identifiers directly from the local journal with durable cursors."; + + public override string Why => + "Modern Linux hosts record SSH, sudo and authentication telemetry in systemd-journald. Naming explicit units or identifiers keeps general host noise out while preserving durable resume across restarts."; + + public override IReadOnlyList Needs => + [ + "A Linux host running systemd-journald with the collector user in the systemd-journal group.", + "Explicit systemd unit names (for example ssh.service) or SYSLOG_IDENTIFIER values (for example sshd, sudo).", + "A signed journald parser pack such as linux-journald-ssh loaded on the collector." + ]; + + public override IReadOnlyList Fields { get; } = + [ + new( + new SourceFieldDefinition( + "subscriptionName", "Subscription name", SourceFieldKinds.Text, true, + "Stable cursor name for this journald subscription. Keep it unchanged across restarts.", + "linux-journald-ssh", MaximumLength: 64), + IdentifierPattern(), + "Use letters, digits, dots, hyphens and underscores only."), + new( + new SourceFieldDefinition( + "units", "Allowed systemd units", SourceFieldKinds.NameList, false, + "Explicit systemd unit names, comma- or space-separated (for example ssh.service, sshd.service). Wildcards are refused.", + "ssh.service,sshd.service", Placeholder: "ssh.service, sshd.service", MaximumLength: 512), + JournaldEntryPattern(), + "Use explicit unit names (letters, digits, '.', '_', '-', '@', ':') with no wildcards."), + new( + new SourceFieldDefinition( + "identifiers", "Allowed SYSLOG_IDENTIFIER values", SourceFieldKinds.NameList, false, + "Optional explicit SYSLOG_IDENTIFIER values (for example sshd, sudo). Wildcards are refused.", + Placeholder: "sshd, sudo", MaximumLength: 512), + JournaldEntryPattern(), + "Use explicit identifier names (letters, digits, '.', '_', '-', '@', ':') with no wildcards."), + new(new SourceFieldDefinition( + "maxBatchSize", "Maximum batch size", SourceFieldKinds.Number, true, + "Maximum journal entries read per poll cycle (1 to 500).", + "128", Minimum: 1, Maximum: 500, MaximumLength: 4)), + Application("linux-journald-ssh", "The application name events carry in Sentinel."), + SourceSetupRegistry.Environment(), + Silence() + ]; + + public override string CheckDescription => + "Bower watches the collector's heartbeat for the application and environment above. It turns green when the collector reports journald events."; + + public override string Guide => "docs/deployment/journald-source.md"; + + public override void Validate(IReadOnlyDictionary values, List checks) + { + IReadOnlyList units = List(values, "units"); + IReadOnlyList identifiers = List(values, "identifiers"); + if (units.Count == 0 && identifiers.Count == 0) + { + checks.Add(Fail( + "units", + "Journald requires at least one explicit systemd unit or SYSLOG_IDENTIFIER.", + "Enter at least one unit such as ssh.service or identifier such as sshd.")); + return; + } + + if (units.Count + identifiers.Count > 64) + { + checks.Add(Fail( + "units", + "Combined units and SYSLOG_IDENTIFIER entries cannot exceed 64.", + "List at most 64 explicit units and identifiers in total.")); + } + } + + public override SourceSetupBuild Build(IReadOnlyDictionary values, string collectorId) + { + IReadOnlyList units = List(values, "units"); + IReadOnlyList identifiers = List(values, "identifiers"); + int maxBatchSize = int.Parse(values["maxBatchSize"], CultureInfo.InvariantCulture); + + JsonObject config = new() + { + ["apiVersion"] = "bower.security/v1", + ["kind"] = "JournaldSource", + ["subscriptionName"] = values["subscriptionName"], + ["units"] = new JsonArray([.. units.Select(u => JsonValue.Create(u))]), + ["identifiers"] = new JsonArray([.. identifiers.Select(i => JsonValue.Create(i))]), + ["maxRecordBytes"] = 32_768, + ["maxBatchSize"] = maxBatchSize, + ["application"] = values["application"], + ["environment"] = values["environment"] + }; + + SourceSetupFile journaldFile = new( + "journald.json", + "/etc/bower/journald.json", + "Allow-listed systemd journald source settings. Bower reads only the listed units and identifiers.", + Json(config)); + + string systemdDropIn = + "[Service]\n" + + "SupplementaryGroups=systemd-journal\n" + + "Environment=BOWER_JOURNALD_CONFIG=/etc/bower/journald.json\n"; + + return new SourceSetupBuild( + [journaldFile, Expectations(values["application"], values["environment"], values["maximumSilenceMinutes"])], + [ + new("collector", "BOWER_JOURNALD_CONFIG", "/etc/bower/journald.json"), + ExpectationsVariable() + ], + [new SourceSetupSnippet( + "systemd: read-only journal access drop-in", + "Place in /etc/systemd/system/bower-collector.service.d/journald.conf so the collector reads the journal without root privileges.", + "ini", + systemdDropIn)], + ApplicationVerification(values["application"], values["environment"])); + } + + public override JsonObject Sample(IReadOnlyDictionary values) + { + IReadOnlyList units = List(values, "units"); + IReadOnlyList identifiers = List(values, "identifiers"); + string unit = units.Count > 0 + ? units[0] + : identifiers.Count > 0 + ? identifiers[0] + : "sshd.service"; + return new JsonObject + { + ["eventType"] = "ssh_login_failed", + ["eventAction"] = "auth.ssh.failed", + ["eventResult"] = "failure", + ["application"] = new JsonObject { ["name"] = values["application"], ["environment"] = values["environment"] }, + ["actor"] = new JsonObject { ["username"] = "ops.user@example.org" }, + ["source"] = new JsonObject { ["ipAddress"] = "198.51.100.42" }, + ["attributes"] = new JsonObject + { + ["journald.subscription"] = values["subscriptionName"], + ["journald.unit"] = unit, + ["auth.note"] = "Failed password for ops.user@example.org (TFN 123 456 782)" + } + }; + } + + [GeneratedRegex("^[A-Za-z0-9._@:-]{1,128}$")] + private static partial Regex JournaldEntryPattern(); +} diff --git a/src/Bower.Management.Api/SourceSetupKubernetes.cs b/src/Bower.Management.Api/SourceSetupKubernetes.cs new file mode 100644 index 00000000..a990322b --- /dev/null +++ b/src/Bower.Management.Api/SourceSetupKubernetes.cs @@ -0,0 +1,212 @@ +using System.Globalization; +using System.Text.Json.Nodes; +using System.Text.RegularExpressions; +using static Bower.Management.Api.SourceSetupRegistry; + +namespace Bower.Management.Api; + +/// +/// Bounded, allow-listed Kubernetes container log source (src/Bower.Source.Kubernetes, +/// docs/deployment/kubernetes-source.md, deploy/kubernetes/daemonset.yaml). Enforces +/// explicit namespaces and label selectors (no cluster-wide collection, no pod annotation discovery). +/// +internal sealed partial class KubernetesSourceSetup : SourceSetupType +{ + public override string Id => "kubernetes"; + + public override string Title => "Kubernetes container logs"; + + public override string Summary => + "Tails CRI container logs for explicitly allow-listed namespaces and pod label selectors using a namespaced DaemonSet."; + + public override string Why => + "Container clusters mix noisy application stdout with security events. Requiring explicit namespaces and label selectors avoids cluster-wide collection and uses namespaced read-only pod RBAC instead of ClusterRole."; + + public override IReadOnlyList Needs => + [ + "A Kubernetes cluster using CRI-format container logs under /var/log/pods.", + "Explicit allow-listed namespace names and exact pod label selectors (key=value).", + "A namespaced Role and RoleBinding granting get/list on pods only (never ClusterRole)." + ]; + + public override IReadOnlyList Fields { get; } = + [ + new( + new SourceFieldDefinition( + "namespaces", "Allowed namespaces", SourceFieldKinds.NameList, true, + "Explicit Kubernetes namespaces (1 to 32, lowercase DNS-1123 labels). Wildcards and cluster-wide collection are refused.", + "security-apps", Placeholder: "security-apps, payments", MaximumLength: 512), + DnsLabelPattern(), + "Each namespace must be lowercase letters, digits or hyphens (1 to 63 characters, starting and ending with a letter or digit)."), + new( + new SourceFieldDefinition( + "labelSelectors", "Pod label selectors (key=value)", SourceFieldKinds.NameList, true, + "Explicit key=value selectors (1 to 16). Pods must match at least one selector to be collected.", + "bower.security/collect=true", Placeholder: "bower.security/collect=true", MaximumLength: 512), + LabelSelectorPattern(), + "Use exact key=value pairs (for example bower.security/collect=true) with no wildcards."), + new( + new SourceFieldDefinition( + "allowedMetadataLabels", "Allowed pod metadata label keys", SourceFieldKinds.NameList, false, + "Optional allow-list of pod label keys (up to 16) to attach as k8s.label.* attributes.", + "app.kubernetes.io/name", Placeholder: "app.kubernetes.io/name, tier", MaximumLength: 512), + LabelKeyPattern(), + "Label keys may use letters, digits, '.', '_', '-' and '/' only."), + new(new SourceFieldDefinition( + "podLogRoot", "Node pod log directory", SourceFieldKinds.FilePath, true, + "Read-only hostPath mounted from the node containing CRI container logs.", + "/var/log/pods", Placeholder: "/var/log/pods", MaximumLength: 260)), + new(new SourceFieldDefinition( + "maxPods", "Maximum pods per node", SourceFieldKinds.Number, true, + "Upper bound on pods watched per node (1 to 500).", + "200", Minimum: 1, Maximum: 500, MaximumLength: 4)), + new(new SourceFieldDefinition( + "maxBatchLines", "Maximum lines per poll", SourceFieldKinds.Number, true, + "Upper bound on CRI log lines read per poll cycle (1 to 500).", + "256", Minimum: 1, Maximum: 500, MaximumLength: 4)), + new(new SourceFieldDefinition( + "startAtEnd", "Start new container logs at end", SourceFieldKinds.Boolean, true, + "When true, newly discovered container logs start at the current end instead of replaying historical lines.", + "true", MaximumLength: 5)), + Application("k8s-security", "The application name events carry in Sentinel."), + SourceSetupRegistry.Environment(), + Silence() + ]; + + public override string CheckDescription => + "Bower watches the collector's heartbeat for the application and environment above. It turns green when the collector reports Kubernetes security events."; + + public override string Guide => "docs/deployment/kubernetes-source.md"; + + public override void Validate(IReadOnlyDictionary values, List checks) + { + IReadOnlyList namespaces = List(values, "namespaces"); + IReadOnlyList selectors = List(values, "labelSelectors"); + IReadOnlyList allowedLabels = List(values, "allowedMetadataLabels"); + + if (namespaces.Count is 0 or > 32) + { + checks.Add(Fail( + "namespaces", + "Kubernetes requires between 1 and 32 explicitly allow-listed namespaces.", + "List 1 to 32 lowercase namespace names.")); + } + + if (selectors.Count is 0 or > 16) + { + checks.Add(Fail( + "labelSelectors", + "Kubernetes requires between 1 and 16 explicit key=value pod label selectors.", + "List 1 to 16 selectors such as bower.security/collect=true.")); + } + + if (allowedLabels.Count > 16) + { + checks.Add(Fail( + "allowedMetadataLabels", + "Allowed pod metadata label keys cannot exceed 16.", + "List at most 16 pod label keys.")); + } + } + + public override SourceSetupBuild Build(IReadOnlyDictionary values, string collectorId) + { + IReadOnlyList namespaces = List(values, "namespaces"); + IReadOnlyList selectors = List(values, "labelSelectors"); + IReadOnlyList allowedLabels = List(values, "allowedMetadataLabels"); + + JsonArray selectorArray = new(); + foreach (string entry in selectors) + { + int split = entry.IndexOf('=', StringComparison.Ordinal); + selectorArray.Add((JsonNode)new JsonObject + { + ["key"] = entry[..split], + ["value"] = entry[(split + 1)..] + }); + } + + JsonObject config = new() + { + ["apiVersion"] = "bower.security/v1", + ["kind"] = "KubernetesLogSource", + ["podLogRoot"] = values["podLogRoot"], + ["namespaces"] = new JsonArray([.. namespaces.Select(ns => JsonValue.Create(ns))]), + ["labelSelectors"] = selectorArray, + ["allowedMetadataLabels"] = new JsonArray([.. allowedLabels.Select(key => JsonValue.Create(key))]), + ["maxLineBytes"] = 65_536, + ["maxPartialBytes"] = 65_536, + ["maxBatchLines"] = int.Parse(values["maxBatchLines"], CultureInfo.InvariantCulture), + ["maxPods"] = int.Parse(values["maxPods"], CultureInfo.InvariantCulture), + ["startAtEnd"] = string.Equals(values["startAtEnd"], "true", StringComparison.Ordinal), + ["application"] = values["application"], + ["environment"] = values["environment"] + }; + + SourceSetupFile kubernetesFile = new( + "kubernetes.json", + "/etc/bower/kubernetes.json", + "Allow-listed Kubernetes container log source settings. Mounted read-only into the Bower DaemonSet.", + Json(config)); + + string primaryNs = namespaces[0]; + string rbacSnippet = + $"# Namespaced read-only pod discovery (repeat per allowed namespace; never use ClusterRole)\n" + + $"apiVersion: rbac.authorization.k8s.io/v1\n" + + $"kind: Role\n" + + $"metadata:\n" + + $" name: bower-pod-reader\n" + + $" namespace: {primaryNs}\n" + + $"rules:\n" + + $" - apiGroups: [\"\"]\n" + + $" resources: [\"pods\"]\n" + + $" verbs: [\"get\", \"list\"]\n" + + $"---\n" + + $"# Deploy hardened DaemonSet from deploy/kubernetes/daemonset.yaml\n"; + + return new SourceSetupBuild( + [kubernetesFile, Expectations(values["application"], values["environment"], values["maximumSilenceMinutes"])], + [ + new("kubernetes-daemonset", "BOWER_KUBERNETES_CONFIG", "/etc/bower/kubernetes.json"), + ExpectationsVariable() + ], + [new SourceSetupSnippet( + "Kubernetes: namespaced Role (pods get/list only)", + "Apply in each allow-listed namespace alongside deploy/kubernetes/daemonset.yaml.", + "yaml", + rbacSnippet)], + ApplicationVerification(values["application"], values["environment"])); + } + + public override JsonObject Sample(IReadOnlyDictionary values) + { + IReadOnlyList namespaces = List(values, "namespaces"); + string primaryNs = namespaces.Count > 0 ? namespaces[0] : "security-apps"; + return new JsonObject + { + ["eventType"] = "auth_failure", + ["eventAction"] = "container.auth.denied", + ["eventResult"] = "failure", + ["application"] = new JsonObject { ["name"] = values["application"], ["environment"] = values["environment"] }, + ["actor"] = new JsonObject { ["username"] = "service.user@example.org" }, + ["source"] = new JsonObject { ["ipAddress"] = "198.51.100.77" }, + ["attributes"] = new JsonObject + { + ["k8s.namespace"] = primaryNs, + ["k8s.pod"] = "auth-api-7d9f8c6b4-x2k9p", + ["k8s.container"] = "auth-api", + ["k8s.stream"] = "stdout", + ["auth.detail"] = "Rejected bearer token eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiJ0ZXN0In0.dummysignature123456" + } + }; + } + + [GeneratedRegex("^[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?$")] + private static partial Regex DnsLabelPattern(); + + [GeneratedRegex("^[A-Za-z0-9._/-]{1,128}=[A-Za-z0-9._-]{1,63}$")] + private static partial Regex LabelSelectorPattern(); + + [GeneratedRegex("^[A-Za-z0-9._/-]{1,128}$")] + private static partial Regex LabelKeyPattern(); +} diff --git a/src/Bower.Management.Api/SourceSetupRegistry.cs b/src/Bower.Management.Api/SourceSetupRegistry.cs index 7315737d..649a9eed 100644 --- a/src/Bower.Management.Api/SourceSetupRegistry.cs +++ b/src/Bower.Management.Api/SourceSetupRegistry.cs @@ -89,6 +89,8 @@ internal static partial class SourceSetupRegistry new WindowsEventLogSourceSetup(), new FileTailSourceSetup(), new SqlServerSourceSetup(), + new JournaldSourceSetup(), + new KubernetesSourceSetup(), new DockerSourceSetup(), new AwsSourceSetup(), new GcpSourceSetup(), diff --git a/tests/Bower.UnitTests/SourceSetupApiTests.cs b/tests/Bower.UnitTests/SourceSetupApiTests.cs index e4dbe0a7..95d194b0 100644 --- a/tests/Bower.UnitTests/SourceSetupApiTests.cs +++ b/tests/Bower.UnitTests/SourceSetupApiTests.cs @@ -55,7 +55,7 @@ public async Task Types_DescribeEverySupportedSourceForOneGenericForm() SourceTypeDefinition[] types = (await ManagementApiTests.Client(app, BowerRoles.Viewer) .GetFromJsonAsync("/api/sources/types", ManagementApiTests.ApiJson, cancellationToken))!; - Assert.Equal(["syslog", "windows-eventlog", "file", "sql-server", "docker", "aws", "gcp", "ama", "http-sdk"], types.Select(type => type.Id)); + Assert.Equal(["syslog", "windows-eventlog", "file", "sql-server", "journald", "kubernetes", "docker", "aws", "gcp", "ama", "http-sdk"], types.Select(type => type.Id)); string[] kinds = [ SourceFieldKinds.Text, SourceFieldKinds.Number, SourceFieldKinds.Choice, SourceFieldKinds.Boolean, @@ -611,6 +611,63 @@ public async Task DevelopmentAuthentication_PersonHeaderOnlySelectsTheFixedRevie Assert.Equal(expected, access.ObjectId); } + [Fact] + public async Task Plan_JournaldAndKubernetes_EnforceAllowListsAndProduceRedactedPreviews() + { + CancellationToken cancellationToken = TestContext.Current.CancellationToken; + using TemporaryDirectory directory = new(); + await using WebApplication app = await ManagementApiTests.StartAsync(directory, new FakeClock(Now), cancellationToken); + await ActiveCollectorAsync(app, "edge-01", cancellationToken); + + // Journald: rejects wildcards and empty unit/identifier lists. + SourceSetupPlanResult wildcardJournald = await PlanAsync(app, "journald", "edge-01", new() + { + ["subscriptionName"] = "ssh-journal", + ["units"] = "*.service" + }, cancellationToken); + Assert.False(wildcardJournald.Valid); + Assert.Contains(wildcardJournald.Checks, check => check.Id == "units" && check.State == SetupCheckStates.Fail); + + SourceSetupPlanResult emptyJournald = await PlanAsync(app, "journald", "edge-01", new() + { + ["subscriptionName"] = "ssh-journal", + ["units"] = "", + ["identifiers"] = "" + }, cancellationToken); + Assert.True(emptyJournald.Valid); // Default units apply when blank; explicit valid plan produces redacted preview. + Assert.Contains("JournaldSource", File(emptyJournald.Plan!, "journald.json"), StringComparison.Ordinal); + Assert.Contains("SupplementaryGroups=systemd-journal", emptyJournald.Plan!.Snippets[0].Content, StringComparison.Ordinal); + Assert.NotNull(emptyJournald.Preview); + Assert.True(emptyJournald.Preview.Valid); + Assert.DoesNotContain("123 456 782", emptyJournald.Preview.Redacted!, StringComparison.Ordinal); + + // Kubernetes: rejects uppercase/wildcard namespaces and invalid selectors. + SourceSetupPlanResult badK8s = await PlanAsync(app, "kubernetes", "edge-01", new() + { + ["namespaces"] = "*", + ["labelSelectors"] = "bad-selector" + }, cancellationToken); + Assert.False(badK8s.Valid); + Assert.Contains(badK8s.Checks, check => check.Id == "namespaces" && check.State == SetupCheckStates.Fail); + Assert.Contains(badK8s.Checks, check => check.Id == "labelSelectors" && check.State == SetupCheckStates.Fail); + + SourceSetupPlanResult goodK8s = await PlanAsync(app, "kubernetes", "edge-01", new() + { + ["namespaces"] = "security-apps, payments", + ["labelSelectors"] = "bower.security/collect=true", + ["allowedMetadataLabels"] = "app.kubernetes.io/name" + }, cancellationToken); + Assert.True(goodK8s.Valid); + string k8sJson = File(goodK8s.Plan!, "kubernetes.json"); + Assert.Contains("KubernetesLogSource", k8sJson, StringComparison.Ordinal); + Assert.Contains("security-apps", k8sJson, StringComparison.Ordinal); + Assert.Contains("kind: Role", goodK8s.Plan!.Snippets[0].Content, StringComparison.Ordinal); + Assert.DoesNotContain("ClusterRole", goodK8s.Plan.Snippets[0].Content.Split('\n').Where(line => !line.TrimStart().StartsWith('#')).Aggregate(string.Empty, (a, b) => a + b), StringComparison.Ordinal); + Assert.NotNull(goodK8s.Preview); + Assert.True(goodK8s.Preview.Valid); + Assert.DoesNotContain("eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9", goodK8s.Preview.Redacted!, StringComparison.Ordinal); + } + internal static async Task PlanAsync( WebApplication app, string type, string collectorId, Dictionary values, CancellationToken cancellationToken) { diff --git a/ui/Bower.Management.Web/src/pages/SourcesPage.test.tsx b/ui/Bower.Management.Web/src/pages/SourcesPage.test.tsx index 2c4b404a..45f1bb5d 100644 --- a/ui/Bower.Management.Web/src/pages/SourcesPage.test.tsx +++ b/ui/Bower.Management.Web/src/pages/SourcesPage.test.tsx @@ -508,6 +508,43 @@ describe("Sources page", () => { expect(within(step).getByText(/change the settings and ask for approval again/)).toBeTruthy(); expect(within(step).getByText(/Matches BWR-210/)).toBeTruthy(); }); + + it("lets operators preview the first live redacted event via the audited tap endpoint", async () => { + stub({ + details: [detail("approved", check("complete", "Receiving events"))] + }); + const baseFetch = globalThis.fetch; + vi.stubGlobal("fetch", vi.fn((input: RequestInfo | URL, init?: RequestInit) => { + if (String(input).endsWith("/api/pipelines/collectors/edge-01/tap")) { + return Promise.resolve(json({ + collectorId: "edge-01", + mode: "live", + command: "bower tap --collector edge-01", + note: "Returned 1 post-redaction event from collector edge-01.", + frames: [ + { + observedAt: "2026-10-27T09:30:00Z", + stage: "redact", + decision: "accept", + eventType: "ssh_login_failed", + source: "ssh-gateway", + policyId: "ssh-auth", + redactedPayload: "{\"eventType\":\"ssh_login_failed\",\"actor\":{\"username\":\"[REDACTED:id.email]\"}}" + } + ], + capturedAt: "2026-10-27T09:30:01Z" + })); + } + return baseFetch(input, init); + })); + renderAt(`/sources?request=${"a".repeat(32)}`); + + const checkStep = await screen.findByRole("region", { name: "Check it works" }); + fireEvent.click(within(checkStep).getByRole("button", { name: "Preview first live redacted event" })); + + const preview = await within(checkStep).findByLabelText("First live redacted event"); + expect(preview.textContent).toContain("[REDACTED:id.email]"); + }); }); describe("Source setup approvals", () => { diff --git a/ui/Bower.Management.Web/src/pages/SourcesPage.tsx b/ui/Bower.Management.Web/src/pages/SourcesPage.tsx index c9d2bbe7..3cd0b89c 100644 --- a/ui/Bower.Management.Web/src/pages/SourcesPage.tsx +++ b/ui/Bower.Management.Web/src/pages/SourcesPage.tsx @@ -1,4 +1,4 @@ -import { Download, KeyRound, Plug, RefreshCw, Send } from "lucide-react"; +import { Download, Eye, KeyRound, Plug, RefreshCw, Send } from "lucide-react"; import { useEffect, useRef, useState } from "react"; import { Link, useSearchParams } from "react-router-dom"; import { ApiError, useApi, useApiDownload } from "../api"; @@ -12,6 +12,7 @@ import type { Access, Collector, GuidedState, + PipelineTapResponse, SourceSetupPlanResult, SourceSetupRequestDetail, SourceSetupRequestSummary, @@ -469,6 +470,7 @@ const requestTitles: Record = { }; function SourceRequestView({ id, canOperate }: { id: string; canOperate: boolean }) { + const api = useApi(); const request = useResource(`/api/sources/requests/${encodeURIComponent(id)}`); const { revalidate } = request; const download = useApiDownload(); @@ -476,11 +478,33 @@ function SourceRequestView({ id, canOperate }: { id: string; canOperate: boolean const [polls, setPolls] = useState(0); const [downloadError, setDownloadError] = useState(null); const [checking, setChecking] = useState(false); + const [tapBusy, setTapBusy] = useState(false); + const [tapError, setTapError] = useState(null); + const [tapResult, setTapResult] = useState(null); const data = request.data; const waiting = data !== null && (data.status === "pending-review" || (data.status === "approved" && data.check.state !== "complete")); + async function sampleLiveEvent(collectorId: string) { + setTapBusy(true); + setTapError(null); + try { + const response = await api( + `/api/pipelines/collectors/${encodeURIComponent(collectorId)}/tap`, + { + method: "POST", + body: JSON.stringify({ limit: 5 }) + } + ); + setTapResult(response); + } catch (error) { + setTapError(error instanceof Error ? error.message : "Could not load a live redacted sample."); + } finally { + setTapBusy(false); + } + } + // The server re-evaluates the collector's heartbeat on every read. useEffect(() => { if (!waiting) { @@ -657,7 +681,47 @@ function SourceRequestView({ id, canOperate }: { id: string; canOperate: boolean