diff --git a/src/Bower.Collector/CollectorJson.cs b/src/Bower.Collector/CollectorJson.cs index be99f721..4544d25f 100644 --- a/src/Bower.Collector/CollectorJson.cs +++ b/src/Bower.Collector/CollectorJson.cs @@ -243,6 +243,14 @@ internal sealed record CollectorHeartbeat( /// Last start's unclean-shutdown and recovery check (additive). Metadata only. [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] public CrashRecoveryStatus? Recovery { get; init; } + + /// Selection counters since process start for the console visual pipeline view. Metadata only. + [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] + public PipelineMetricsSnapshot? Pipeline { get; init; } + + /// Top busiest sources (capped) for the console visual pipeline view. Metadata only. + [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] + public IReadOnlyList? Activity { get; init; } } /// diff --git a/src/Bower.Collector/Jobs/ManagementHeartbeatJob.cs b/src/Bower.Collector/Jobs/ManagementHeartbeatJob.cs index f90ae2ec..4750a08d 100644 --- a/src/Bower.Collector/Jobs/ManagementHeartbeatJob.cs +++ b/src/Bower.Collector/Jobs/ManagementHeartbeatJob.cs @@ -190,7 +190,9 @@ private async Task ReportAsync(CancellationToken cancellationToken) Storage = storage, WecRuntime = wecSnapshots.Count > 0 ? wecSnapshots : null, OldestDeadLetterAgeSeconds = oldestDeadLetterAge, - Recovery = crashRecovery?.Last + Recovery = crashRecovery?.Last, + Pipeline = telemetry?.Snapshot(), + Activity = telemetry?.BusiestSources(25) }, CollectorJsonContext.Default.CollectorHeartbeat)); // One budget for the whole exchange, body included: a stalled body cannot hold the diff --git a/src/Bower.Management.Api/ManagementApplication.cs b/src/Bower.Management.Api/ManagementApplication.cs index 4d929043..8952c336 100644 --- a/src/Bower.Management.Api/ManagementApplication.cs +++ b/src/Bower.Management.Api/ManagementApplication.cs @@ -345,6 +345,7 @@ await store.FleetAsync(clock.GetUtcNow(), cancellationToken)) .RequireAuthorization("View"); OfflineSiteEndpoints.Map(api); + PipelineLiveEndpoints.Map(api); api.MapGet( "/collectors", diff --git a/src/Bower.Management.Api/ManagementJson.cs b/src/Bower.Management.Api/ManagementJson.cs index 148aa324..87c3735d 100644 --- a/src/Bower.Management.Api/ManagementJson.cs +++ b/src/Bower.Management.Api/ManagementJson.cs @@ -104,6 +104,13 @@ public sealed record PipelineValidationResponse( [JsonSerializable(typeof(PolicyFormRequest))] [JsonSerializable(typeof(PolicyFormResult))] [JsonSerializable(typeof(string))] +[JsonSerializable(typeof(PipelineReport))] +[JsonSerializable(typeof(SourceActivityReport[]))] +[JsonSerializable(typeof(CollectorPipelineFlow))] +[JsonSerializable(typeof(List))] +[JsonSerializable(typeof(IReadOnlyList))] +[JsonSerializable(typeof(PipelineTapRequest))] +[JsonSerializable(typeof(PipelineTapResponse))] [JsonSerializable(typeof(Dictionary))] [JsonSerializable(typeof(Microsoft.AspNetCore.Mvc.ProblemDetails))] [JsonSerializable(typeof(HttpValidationProblemDetails))] diff --git a/src/Bower.Management.Api/ManagementModels.cs b/src/Bower.Management.Api/ManagementModels.cs index 1b688f77..a39ef6dd 100644 --- a/src/Bower.Management.Api/ManagementModels.cs +++ b/src/Bower.Management.Api/ManagementModels.cs @@ -66,7 +66,9 @@ public sealed record CollectorHeartbeat( CanaryReport? LastCanary = null, IReadOnlyList? CommandCapabilities = null, IReadOnlyList? CommandResults = null, - RedactionReport? Redactions = null) + RedactionReport? Redactions = null, + PipelineReport? Pipeline = null, + IReadOnlyList? Activity = null) { /// A body without schemaVersion is a v1 heartbeat. [System.Text.Json.Serialization.JsonIgnore] diff --git a/src/Bower.Management.Api/ManagementStore.Pipelines.cs b/src/Bower.Management.Api/ManagementStore.Pipelines.cs new file mode 100644 index 00000000..b645d376 --- /dev/null +++ b/src/Bower.Management.Api/ManagementStore.Pipelines.cs @@ -0,0 +1,272 @@ +using System.Globalization; +using System.Text.Json; +using Microsoft.Data.Sqlite; + +namespace Bower.Management.Api; + +public sealed partial class ManagementStore +{ + public const int MaximumActivitySources = 25; + public const int MaximumPipelineRows = 64; + + private static Task InitializePipelinesAsync(SqliteConnection connection, CancellationToken cancellationToken) => + ExecuteAsync( + connection, + """ + CREATE TABLE IF NOT EXISTS collector_pipeline_snapshots ( + collector_id TEXT PRIMARY KEY REFERENCES collectors(id) ON DELETE CASCADE, + captured_at TEXT NOT NULL, + pipeline_json TEXT NULL, + activity_json TEXT NULL + ); + """, + cancellationToken); + + private static async Task SavePipelineSnapshotAsync( + SqliteConnection connection, + SqliteTransaction transaction, + string collectorId, + PipelineReport? pipeline, + IReadOnlyList? activity, + DateTimeOffset now, + CancellationToken cancellationToken) + { + if (pipeline is null && activity is null) + { + return; + } + + string? pipelineJson = pipeline is null + ? null + : JsonSerializer.Serialize( + pipeline with { Rows = pipeline.Rows?.Take(MaximumPipelineRows).ToArray() }, + ManagementJsonContext.Default.PipelineReport); + string? activityJson = activity is null + ? null + : JsonSerializer.Serialize( + activity.Take(MaximumActivitySources).ToArray(), + ManagementJsonContext.Default.SourceActivityReportArray); + + await CommandAsync( + connection, + transaction, + """ + INSERT INTO collector_pipeline_snapshots (collector_id, captured_at, pipeline_json, activity_json) + VALUES ($collector, $captured, $pipeline, $activity) + ON CONFLICT(collector_id) DO UPDATE SET + captured_at = excluded.captured_at, + pipeline_json = COALESCE(excluded.pipeline_json, collector_pipeline_snapshots.pipeline_json), + activity_json = COALESCE(excluded.activity_json, collector_pipeline_snapshots.activity_json); + """, + [ + ("$collector", collectorId), + ("$captured", Format(now)), + ("$pipeline", pipelineJson), + ("$activity", activityJson) + ], + cancellationToken); + } + + public async Task> ListLivePipelinesAsync( + DateTimeOffset now, + CancellationToken cancellationToken) + { + IReadOnlyList collectors = await ListAsync(null, cancellationToken); + await using SqliteConnection connection = await OpenAsync(cancellationToken); + + Dictionary snapshots = new(StringComparer.Ordinal); + await using (SqliteCommand command = connection.CreateCommand()) + { + command.CommandText = "SELECT collector_id, pipeline_json, activity_json FROM collector_pipeline_snapshots;"; + await using SqliteDataReader reader = await command.ExecuteReaderAsync(cancellationToken); + while (await reader.ReadAsync(cancellationToken)) + { + string id = reader.GetString(0); + PipelineReport? pipeline = reader.IsDBNull(1) + ? null + : JsonSerializer.Deserialize(reader.GetString(1), ManagementJsonContext.Default.PipelineReport); + SourceActivityReport[] activity = reader.IsDBNull(2) + ? [] + : JsonSerializer.Deserialize(reader.GetString(2), ManagementJsonContext.Default.SourceActivityReportArray) ?? []; + snapshots[id] = (pipeline, activity); + } + } + + Dictionary> redactionsByCollector = new(StringComparer.Ordinal); + await using (SqliteCommand command = connection.CreateCommand()) + { + command.CommandText = + """ + SELECT collector_id, type, events + FROM collector_redaction_totals + WHERE events > 0 + ORDER BY events DESC, type ASC; + """; + await using SqliteDataReader reader = await command.ExecuteReaderAsync(cancellationToken); + while (await reader.ReadAsync(cancellationToken)) + { + string collectorId = reader.GetString(0); + string type = reader.GetString(1); + long events = reader.GetInt64(2); + if (!redactionsByCollector.TryGetValue(collectorId, out List? list)) + { + list = []; + redactionsByCollector[collectorId] = list; + } + + list.Add(new RedactionSummaryItem(type, RedactionLabels.Label(RedactionLabels.Group(type)), events)); + } + } + + List flows = []; + foreach (CollectorRecord raw in collectors) + { + CollectorRecord record = CollectorConnectivity.With(raw, now); + snapshots.TryGetValue(record.Id, out (PipelineReport? Pipeline, SourceActivityReport[] Activity) snap); + redactionsByCollector.TryGetValue(record.Id, out List? redactions); + flows.Add(BuildPipelineFlow(record, snap.Pipeline, snap.Activity ?? [], redactions ?? [])); + } + + return flows; + } + + public async Task RecordPipelineTapAuditAsync( + string collectorId, + string actorObjectId, + string actorName, + DateTimeOffset now, + CancellationToken cancellationToken) + { + await using SqliteConnection connection = await OpenAsync(cancellationToken); + await using SqliteTransaction transaction = + (SqliteTransaction)await connection.BeginTransactionAsync(cancellationToken); + await InsertAuditAsync( + connection, + transaction, + "pipeline.tap-sampled", + collectorId, + actorObjectId, + actorName, + now, + cancellationToken); + await transaction.CommitAsync(cancellationToken); + } + + private static CollectorPipelineFlow BuildPipelineFlow( + CollectorRecord collector, + PipelineReport? pipeline, + SourceActivityReport[] activity, + List redactions) + { + long eventsIn = pipeline?.EventsIn ?? 0; + long eventsQueued = pipeline?.EventsQueued ?? 0; + long suppressed = pipeline?.Suppressed ?? 0; + long duplicates = pipeline?.Duplicates ?? 0; + long bytesIn = pipeline?.BytesIn ?? 0; + long bytesQueued = pipeline?.BytesQueued ?? 0; + long rejected = Math.Max(0, eventsIn - eventsQueued - suppressed - duplicates); + int? reductionPercent = eventsIn > 0 + ? (int)Math.Clamp(Math.Round((eventsIn - eventsQueued) * 100.0 / eventsIn), 0, 100) + : null; + long totalRedactions = redactions.Sum(item => item.Events); + + int degradedSources = collector.Sources.Count(source => + !string.Equals(source.Status, "healthy", StringComparison.OrdinalIgnoreCase) + && !string.Equals(source.Status, "pending", StringComparison.OrdinalIgnoreCase)); + string collectLight = degradedSources > 0 + ? "amber" + : collector.Sources.Count > 0 ? "green" : "amber"; + string collectHeadline = collector.Sources.Count == 1 + ? "1 source configured" + : $"{collector.Sources.Count} sources configured"; + string collectDetail = degradedSources > 0 + ? $"{degradedSources} source(s) quiet or degraded" + : eventsIn > 0 + ? $"{eventsIn.ToString("N0", CultureInfo.InvariantCulture)} candidate event(s) seen since start" + : "Listening for events"; + + bool privacyDrifted = collector.PrivacyProfileInSync == false; + string redactLight = privacyDrifted ? "amber" : "green"; + string redactHeadline = totalRedactions > 0 + ? $"{totalRedactions.ToString("N0", CultureInfo.InvariantCulture)} finding(s) protected" + : "Active before queue"; + string redactDetail = privacyDrifted + ? "Privacy profile differs from assigned version" + : string.Equals(collector.ReportedPrivacyProfileHash, "default", StringComparison.OrdinalIgnoreCase) + ? "Built-in Australian privacy rules active" + : "Assigned privacy profile in sync"; + + bool policyDrifted = collector.PolicyInSync == false; + string selectLight = policyDrifted ? "amber" : "green"; + string selectHeadline = eventsIn > 0 + ? $"{eventsQueued.ToString("N0", CultureInfo.InvariantCulture)} kept of {eventsIn.ToString("N0", CultureInfo.InvariantCulture)}" + : "Default-deny policy active"; + string selectDetail = reductionPercent is { } pct && eventsIn > 0 + ? $"{pct}% noise filtered ({suppressed} suppressed, {rejected} dropped/quarantined)" + : policyDrifted + ? "Policy bundle differs from desired hash" + : "Policy bundle in sync"; + + string queueLight = collector.DeadLettered > 0 + ? "red" + : collector.QueueDepth > 1000 ? "amber" : "green"; + string queueHeadline = collector.QueueDepth == 0 + ? "Queue drained" + : $"{collector.QueueDepth.ToString("N0", CultureInfo.InvariantCulture)} waiting"; + string queueDetail = collector.DeadLettered > 0 + ? $"{collector.DeadLettered.ToString("N0", CultureInfo.InvariantCulture)} dead-lettered event(s) need review" + : collector.OldestUndeliveredAgeSeconds is { } age and > 0 + ? $"Oldest waiting event is {age}s old" + : "SQLite WAL durable queue healthy"; + + string deliveryLower = collector.DeliveryStatus.ToLowerInvariant(); + string deliverLight = deliveryLower is "healthy" or "waiting" or "idle" + ? "green" + : deliveryLower is "degraded" or "retrying" or "paused" + ? "amber" + : "red"; + string deliverHeadline = collector.Outputs.Count > 0 + ? string.Join(", ", collector.Outputs.Select(output => output.Type)) + : collector.DeliveryStatus; + string deliverDetail = collector.LastSuccessfulDeliveryAt is { } lastAck + ? $"Status: {collector.DeliveryStatus} · last ack {lastAck:u}" + : $"Status: {collector.DeliveryStatus}"; + + PipelineFlowStage[] stages = + [ + new("collect", "Collect", collectLight, collectHeadline, collectDetail), + new("redact", "Redact", redactLight, redactHeadline, redactDetail), + new("select", "Select", selectLight, selectHeadline, selectDetail), + new("queue", "Queue", queueLight, queueHeadline, queueDetail), + new("deliver", "Deliver", deliverLight, deliverHeadline, deliverDetail) + ]; + + return new CollectorPipelineFlow( + collector.Id, + collector.MachineName, + collector.Environment, + collector.Connectivity ?? "unknown", + collector.LastSeenAt, + collector.PolicyHash, + collector.ReportedPrivacyProfileHash ?? "default", + eventsIn, + eventsQueued, + suppressed, + rejected, + duplicates, + bytesIn, + bytesQueued, + reductionPercent, + collector.QueueDepth, + collector.DeadLettered, + collector.OldestUndeliveredAgeSeconds, + collector.DeliveryStatus, + collector.LastSuccessfulDeliveryAt, + stages, + collector.Sources, + collector.Outputs, + activity, + redactions, + pipeline?.Rows ?? []); + } +} diff --git a/src/Bower.Management.Api/ManagementStore.cs b/src/Bower.Management.Api/ManagementStore.cs index c4f02106..71ccf73f 100644 --- a/src/Bower.Management.Api/ManagementStore.cs +++ b/src/Bower.Management.Api/ManagementStore.cs @@ -143,6 +143,7 @@ await AddColumnIfMissingAsync( await InitializeHomeAsync(connection, cancellationToken); await InitializeSourceSetupAsync(connection, cancellationToken); await InitializeOfflineSitesAsync(connection, cancellationToken); + await InitializePipelinesAsync(connection, cancellationToken); } public async Task RegisterAsync( @@ -335,6 +336,8 @@ await ReplaceReportsAsync( await UpdateHeartbeatV2Async( connection, transaction, collectorId, heartbeat, deliveryStatus, now, cancellationToken); await RecordRedactionsAsync(connection, transaction, collectorId, heartbeat.Redactions, now, cancellationToken); + await SavePipelineSnapshotAsync( + connection, transaction, collectorId, heartbeat.Pipeline, heartbeat.Activity, now, cancellationToken); (IReadOnlyList commands, IReadOnlyList acknowledged) = heartbeat.IsV2 ? await ExchangeCommandsAsync( diff --git a/src/Bower.Management.Api/PipelineLiveEndpoints.cs b/src/Bower.Management.Api/PipelineLiveEndpoints.cs new file mode 100644 index 00000000..eff7ec47 --- /dev/null +++ b/src/Bower.Management.Api/PipelineLiveEndpoints.cs @@ -0,0 +1,115 @@ +using System.Security.Claims; +using System.Text; + +namespace Bower.Management.Api; + +internal static class PipelineLiveEndpoints +{ + public static void Map(RouteGroupBuilder api) + { + api.MapGet( + "/pipelines/live", + async (ManagementStore store, TimeProvider clock, CancellationToken cancellationToken) => + Results.Ok(await store.ListLivePipelinesAsync(clock.GetUtcNow(), cancellationToken))) + .RequireAuthorization("View"); + + // Operator-only redacted sample tap. Enforced server-side; Viewers receive 403. + // Never connects to user-supplied URLs and always audits each tap request. + api.MapPost( + "/pipelines/collectors/{id}/tap", + async ( + string id, + PipelineTapRequest? request, + ClaimsPrincipal user, + ManagementStore store, + TimeProvider clock, + HttpContext httpContext, + CancellationToken cancellationToken) => + { + CollectorRecord? collector = await store.GetAsync(id, cancellationToken); + if (collector is null) + { + return Results.NotFound(); + } + + int limit = Math.Clamp(request?.Limit ?? 10, 1, 25); + string? source = SanitizeFilter(request?.Source); + string? eventType = SanitizeFilter(request?.EventType); + PipelineTapRequest normalized = new(source, eventType, limit); + + DateTimeOffset now = clock.GetUtcNow(); + string actorId = user.FindFirstValue("oid") ?? user.Identity?.Name ?? "unknown"; + string actorName = user.FindFirstValue("name") ?? user.Identity?.Name ?? actorId; + await store.RecordPipelineTapAuditAsync(id, actorId, actorName, now, cancellationToken); + + string command = BuildCliCommand(normalized); + ICollectorTapClient? tapClient = httpContext.RequestServices.GetService(); + if (tapClient is not null) + { + IReadOnlyList? frames = await tapClient.TrySampleAsync(id, normalized, cancellationToken); + if (frames is not null) + { + return Results.Ok(new PipelineTapResponse( + id, + "live", + command, + "Post-redaction frames sampled from the allow-listed collector tap endpoint. Raw payloads are never shown.", + frames.Take(limit).ToArray(), + now)); + } + } + + return Results.Ok(new PipelineTapResponse( + id, + "cli", + command, + "Collectors communicate outbound only, so management does not open inbound connections to them. Run this command on the collector host (or configure an allow-listed tap relay) to inspect live redacted frames.", + [], + now)); + }) + .RequireAuthorization("Operate"); + } + + private static string? SanitizeFilter(string? value) + { + if (string.IsNullOrWhiteSpace(value)) + { + return null; + } + + string trimmed = value.Trim(); + if (trimmed.Length > 128) + { + trimmed = trimmed[..128]; + } + + StringBuilder safe = new(trimmed.Length); + foreach (char ch in trimmed) + { + if (char.IsLetterOrDigit(ch) || ch is '.' or '_' or '-' or '/' or ':') + { + safe.Append(ch); + } + } + + return safe.Length > 0 ? safe.ToString() : null; + } + + private static string BuildCliCommand(PipelineTapRequest request) + { + StringBuilder sb = new("bower tap --url http://127.0.0.1:4319 --limit "); + sb.Append(request.Limit ?? 10); + sb.Append(" --duration 15"); + if (!string.IsNullOrWhiteSpace(request.Source)) + { + sb.Append(" --source ").Append(request.Source); + } + + if (!string.IsNullOrWhiteSpace(request.EventType)) + { + sb.Append(" --event-type ").Append(request.EventType); + } + + return sb.ToString(); + } +} diff --git a/src/Bower.Management.Api/PipelineLiveModels.cs b/src/Bower.Management.Api/PipelineLiveModels.cs new file mode 100644 index 00000000..794e6056 --- /dev/null +++ b/src/Bower.Management.Api/PipelineLiveModels.cs @@ -0,0 +1,111 @@ +namespace Bower.Management.Api; + +/// Selection counters reported by a collector on heartbeat v2+. Metadata only. +public sealed record PipelineReport( + DateTimeOffset StartedAt, + long EventsIn, + long EventsQueued, + long Duplicates, + long Suppressed, + long BytesIn, + long BytesQueued, + IReadOnlyList? Rows = null); + +/// Per-stage / per-policy counter row from . Metadata only. +public sealed record PipelineRowReport( + string Stage, + string PolicyId, + string Action, + long Events, + long Queued, + long Duplicates, + long Suppressed, + long BytesIn, + long BytesQueued); + +/// One busy source reported by a collector (equivalent to bower top). Metadata only. +public sealed record SourceActivityReport( + string Application, + string Environment, + DateTimeOffset LastSeenAt, + long EventCount); + +/// One stage in the 5-stage visual pipeline view (Collect → Redact → Select → Queue → Deliver). +public sealed record PipelineFlowStage( + string Id, + string Title, + string Light, + string Headline, + string Detail); + +/// Live visual pipeline summary for one collector, computed server-side from heartbeat metadata. +public sealed record CollectorPipelineFlow( + string CollectorId, + string MachineName, + string Site, + string Connectivity, + DateTimeOffset LastSeenAt, + string PolicyHash, + string PrivacyProfileHash, + long EventsIn, + long EventsQueued, + long EventsSuppressed, + long EventsRejected, + long Duplicates, + long BytesIn, + long BytesQueued, + int? ReductionPercent, + long QueueDepth, + long DeadLettered, + long? OldestUndeliveredAgeSeconds, + string DeliveryStatus, + DateTimeOffset? LastSuccessfulDeliveryAt, + IReadOnlyList Stages, + IReadOnlyList Sources, + IReadOnlyList Outputs, + IReadOnlyList TopSources, + IReadOnlyList Redactions, + IReadOnlyList PolicyBreakdown); + +/// Redaction total for one detector type on a collector. Metadata only. +public sealed record RedactionSummaryItem(string Type, string Label, long Events); + +/// Request body for POST /api/pipelines/collectors/{id}/tap. +public sealed record PipelineTapRequest(string? Source = null, string? EventType = null, int? Limit = null); + +/// One already-redacted tap frame returned to an operator. +public sealed record PipelineTapFrame( + DateTimeOffset ObservedAt, + string Stage, + string Decision, + string? EventType, + string? Source, + string? PolicyId, + string? RedactedPayload); + +/// +/// Response for POST /api/pipelines/collectors/{id}/tap. In outbound-only deployments +/// returns mode: "cli" with the exact bower tap command to run locally on the +/// collector host; when an allow-listed tap client is configured returns mode: "live" +/// with bounded, already-redacted frames. +/// +public sealed record PipelineTapResponse( + string CollectorId, + string Mode, + string Command, + string Note, + IReadOnlyList Frames, + DateTimeOffset CapturedAt); + +/// +/// Optional server-side client for fetching bounded, post-redaction tap frames from an +/// administrator-allowlisted collector endpoint. Default deployments keep collectors outbound-only +/// and do not configure a direct tap client. +/// +public interface ICollectorTapClient +{ + Task?> TrySampleAsync( + string collectorId, + PipelineTapRequest request, + CancellationToken cancellationToken); +} diff --git a/src/Bower.Management.Api/SourceSetupRegistry.cs b/src/Bower.Management.Api/SourceSetupRegistry.cs index 1d5d1b4e..7315737d 100644 --- a/src/Bower.Management.Api/SourceSetupRegistry.cs +++ b/src/Bower.Management.Api/SourceSetupRegistry.cs @@ -88,6 +88,7 @@ internal static partial class SourceSetupRegistry new SyslogSourceSetup(), new WindowsEventLogSourceSetup(), new FileTailSourceSetup(), + new SqlServerSourceSetup(), new DockerSourceSetup(), new AwsSourceSetup(), new GcpSourceSetup(), diff --git a/src/Bower.Management.Api/SourceSetupSqlServer.cs b/src/Bower.Management.Api/SourceSetupSqlServer.cs new file mode 100644 index 00000000..3288f3da --- /dev/null +++ b/src/Bower.Management.Api/SourceSetupSqlServer.cs @@ -0,0 +1,184 @@ +using System.Globalization; +using System.Text.Json.Nodes; +using System.Text.RegularExpressions; +using static Bower.Management.Api.SourceSetupRegistry; + +namespace Bower.Management.Api; + +/// +/// Read-only SQL Server security audit table polling (src/Bower.Source.SqlServer, +/// docs/operations/queue-v5-durability.md). Enforces read-only ApplicationIntent, +/// safe SQL identifiers, bounded batch allocation and a secret reference (never an +/// inline password). +/// +internal sealed partial class SqlServerSourceSetup : SourceSetupType +{ + private static readonly SourceFieldOption[] CursorKinds = + [ + new("Incrementing", "Incrementing sequence ID (recommended for identity columns)"), + new("Timestamp", "Timestamp with bounded overlap sweep (for late-committing rows)"), + new("Composite", "Composite (EventTime + Sequence)") + ]; + + private static readonly string[] TimestampOnly = ["Timestamp"]; + + public override string Id => "sql-server"; + + public override string Title => "SQL Server audit table"; + + public override string Summary => + "Polls a read-only SQL Server audit table with durable keyset cursors and forwards security events to the collector."; + + public override string Why => + "Line-of-business databases often record privilege changes, failed sign-ins and sensitive exports in an audit table. Bower reads bounded batches with ApplicationIntent=ReadOnly and never modifies the database."; + + public override IReadOnlyList Needs => + [ + "A read-only SQL Server login granted SELECT on the audit table only.", + "A connection string stored in a protected file or Key Vault secret (with ApplicationIntent=ReadOnly and Encrypt=True).", + "An approved collector with producer scopes allowing this application's events.", + "A monotonic sequence column and event timestamp column on the audit table." + ]; + + public override IReadOnlyList Fields { get; } = + [ + new( + new SourceFieldDefinition( + "sourceId", "Source identifier", SourceFieldKinds.Text, true, + "Stable cursor name for this SQL Server table. Keep it unchanged across restarts so the cursor resumes.", + "sql-audit-primary", MaximumLength: 128), + IdentifierPattern(), + "Use letters, digits, dots, hyphens and underscores only."), + new( + new SourceFieldDefinition( + "schema", "SQL schema", SourceFieldKinds.Text, true, + "Schema owning the audit table (letters, digits and underscores; starts with a letter or underscore).", + "dbo", MaximumLength: 128), + SqlIdentifierPattern(), + "SQL identifiers must start with a letter or underscore and contain only letters, digits or underscores."), + new( + new SourceFieldDefinition( + "table", "Audit table", SourceFieldKinds.Text, true, + "Read-only audit table name.", Placeholder: "SecurityAuditLog", MaximumLength: 128), + SqlIdentifierPattern(), + "SQL identifiers must start with a letter or underscore and contain only letters, digits or underscores."), + new(new SourceFieldDefinition( + "cursorKind", "Cursor strategy", SourceFieldKinds.Choice, true, + "Incrementing is fastest for identity columns; Timestamp adds a bounded overlap sweep for late-committing transactions.", + "Incrementing", Options: CursorKinds, MaximumLength: 16)), + new(new SourceFieldDefinition( + "timestampOverlapSeconds", "Overlap sweep window (seconds)", SourceFieldKinds.Number, true, + "How far back to sweep for late-committing rows (0 to 86400 seconds).", + "300", Minimum: 0, Maximum: 86_400, MaximumLength: 5, + ShownWhenField: "cursorKind", ShownWhenValues: TimestampOnly)), + new(new SourceFieldDefinition( + "pollIntervalSeconds", "Poll interval (seconds)", SourceFieldKinds.Number, true, + "How often to query for new audit rows (5 to 3600 seconds).", + "30", Minimum: 5, Maximum: 3_600, MaximumLength: 4)), + new(new SourceFieldDefinition( + "batchSize", "Batch size", SourceFieldKinds.Number, true, + "Maximum rows read per poll (1 to 10000; bounded to 64 MiB total with record limit).", + "500", Minimum: 1, Maximum: 10_000, MaximumLength: 5)), + new(new SourceFieldDefinition( + "connectionStringRef", "Connection string secret reference", SourceFieldKinds.SecretReference, true, + "File path on the collector host or Azure Key Vault secret URL holding the ReadOnly connection string. Never paste passwords here.", + Placeholder: "/run/secrets/bower-sql-readonly", MaximumLength: 260, KeyVaultAllowed: true)), + Application("sql-audit", "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 SQL Server audit events."; + + public override string Guide => "docs/operations/queue-v5-durability.md"; + + public override void Validate(IReadOnlyDictionary values, List checks) + { + if (values["cursorKind"] == "Timestamp" + && Optional(values, "timestampOverlapSeconds") is { } overlapText + && int.TryParse(overlapText, CultureInfo.InvariantCulture, out int overlap) + && overlap == 0) + { + checks.Add(Warn( + "timestampOverlapSeconds", + "Timestamp cursor has zero overlap; rows committed out of timestamp order may be skipped.", + "Set a bounded overlap window such as 300 seconds when transactions can commit out of order.")); + } + } + + public override SourceSetupBuild Build(IReadOnlyDictionary values, string collectorId) + { + string cursorKind = values["cursorKind"]; + int pollSeconds = int.Parse(values["pollIntervalSeconds"], CultureInfo.InvariantCulture); + int batchSize = int.Parse(values["batchSize"], CultureInfo.InvariantCulture); + int overlapSeconds = cursorKind == "Timestamp" && Optional(values, "timestampOverlapSeconds") is { } rawOverlap + ? int.Parse(rawOverlap, CultureInfo.InvariantCulture) + : 0; + + JsonObject config = new() + { + ["apiVersion"] = "bower.security/v1", + ["kind"] = "SqlServerSource", + ["sourceId"] = values["sourceId"], + ["schema"] = values["schema"], + ["table"] = values["table"], + ["cursorKind"] = cursorKind, + ["pollIntervalSeconds"] = pollSeconds, + ["batchSize"] = batchSize, + ["timestampOverlapSeconds"] = overlapSeconds, + ["maximumRecordBytes"] = 65_536, + ["oversizedRecords"] = "OmitValues", + ["application"] = values["application"], + ["environment"] = values["environment"], + ["connectionStringRef"] = values["connectionStringRef"] + }; + + SourceSetupFile sqlFile = new( + "sql-server.json", + "/etc/bower/sql-server.json", + "Read-only SQL Server audit poller settings. Connection string stays in the referenced secret.", + Json(config)); + + string grantSnippet = + $"-- Least-privilege read-only access for Bower (run on target SQL Server database):\n" + + $"CREATE USER [bower_reader] FROM LOGIN [bower_reader];\n" + + $"GRANT SELECT ON [{values["schema"]}].[{values["table"]}] TO [bower_reader];\n" + + $"-- Connection string in {values["connectionStringRef"]} must include:\n" + + $"-- ApplicationIntent=ReadOnly;Encrypt=True;TrustServerCertificate=False\n"; + + return new SourceSetupBuild( + [sqlFile, Expectations(values["application"], values["environment"], values["maximumSilenceMinutes"])], + [ + new("sql-source", "BOWER_SQLSERVER_CONFIG", "/etc/bower/sql-server.json"), + new("sql-source", "BOWER_SQLSERVER_CONNECTION_STRING_REF", values["connectionStringRef"]), + ExpectationsVariable() + ], + [new SourceSetupSnippet( + "SQL Server: least-privilege read-only grant", + "Grant SELECT on the audit table only. Bower never writes to the source database.", + "sql", + grantSnippet)], + ApplicationVerification(values["application"], values["environment"])); + } + + public override JsonObject Sample(IReadOnlyDictionary values) => new() + { + ["eventType"] = "role_membership_changed", + ["eventAction"] = "sql.audit.role_update", + ["eventResult"] = "success", + ["application"] = new JsonObject { ["name"] = values["application"], ["environment"] = values["environment"] }, + ["actor"] = new JsonObject { ["username"] = "db.admin@example.org" }, + ["source"] = new JsonObject { ["ipAddress"] = "198.51.100.19" }, + ["attributes"] = new JsonObject + { + ["sql.sourceId"] = values["sourceId"], + ["sql.table"] = $"{values["schema"]}.{values["table"]}", + ["sql.cursorKind"] = values["cursorKind"], + ["audit.note"] = "Updated role for user TFN 123 456 782" + } + }; + + [GeneratedRegex("^[A-Za-z_][A-Za-z0-9_]*$")] + private static partial Regex SqlIdentifierPattern(); +} diff --git a/tests/Bower.UnitTests/PipelineLiveAndSqlSetupTests.cs b/tests/Bower.UnitTests/PipelineLiveAndSqlSetupTests.cs new file mode 100644 index 00000000..9f335eae --- /dev/null +++ b/tests/Bower.UnitTests/PipelineLiveAndSqlSetupTests.cs @@ -0,0 +1,188 @@ +using System.Net; +using System.Net.Http.Json; +using Bower.Management.Api; +using Microsoft.AspNetCore.Builder; +using Microsoft.Extensions.DependencyInjection; + +namespace Bower.UnitTests; + +/// +/// Live visual pipeline telemetry (#101) and SQL Server guided source setup (#99): +/// heartbeat pipeline/activity counters, /api/pipelines/live, Operator-only audited tap, +/// and SQL Server plan validation + redacted preview. +/// +[Collection(SerialHostTests.Name)] +public sealed class PipelineLiveAndSqlSetupTests +{ + private static readonly DateTimeOffset Now = new(2026, 11, 22, 8, 0, 0, TimeSpan.Zero); + + [Fact] + public async Task LivePipelines_SurfacesFiveStagesTopSourcesAndRedactions_AndTapEnforcesOperatorRbac() + { + CancellationToken cancellation = TestContext.Current.CancellationToken; + using TemporaryDirectory directory = new(); + await using WebApplication app = await ManagementApiTests.StartAsync( + directory, + services => services.AddSingleton(new StubTapClient()), + null, + cancellation); + + HttpClient collector = ManagementApiTests.Client(app, BowerRoles.Collector, "sp-edge-01"); + HttpClient approver = ManagementApiTests.Client(app, BowerRoles.Approver, "approver-oid"); + HttpClient viewer = ManagementApiTests.Client(app, BowerRoles.Viewer, "viewer-oid"); + HttpClient oper = ManagementApiTests.Client(app, BowerRoles.Operator, "operator-oid"); + + // Register & approve collector. + using HttpResponseMessage reg = await collector.PostAsJsonAsync( + "/api/collectors/register", + new CollectorRegistration( + "edge-01", + "edge-01.corp.example", + "production", + "1.0.1", + "sha256:cfg", + "sha256:pol", + [new SourceReport("local-http", "local-http", "healthy", null, null)], + [new OutputReport("azure-logs-ingestion", "azure-logs-ingestion", "healthy", null, null)]), + cancellation); + Assert.Equal(HttpStatusCode.Accepted, reg.StatusCode); + + using HttpResponseMessage approved = await approver.PostAsJsonAsync( + "/api/approvals/edge-01/approve", + new ApprovalRequest("Production edge collector"), + cancellation); + Assert.Equal(HttpStatusCode.OK, approved.StatusCode); + + // Send heartbeat v2 with Pipeline, Activity and Redactions metadata. + CollectorHeartbeat heartbeat = new( + "1.0.1", + "sha256:cfg", + "sha256:pol", + QueueDepth: 6, + DeliveryStatus: "healthy", + Sources: [new SourceReport("local-http", "local-http", "healthy", 0, Now)], + Outputs: [new OutputReport("azure-logs-ingestion", "azure-logs-ingestion", "healthy", Now, null)], + DeadLettered: 0, + PrivacyProfileHash: "default", + SchemaVersion: 2, + HeartbeatIntervalSeconds: 60, + OldestUndeliveredAgeSeconds: 15, + LastSuccessfulDeliveryAt: Now, + Redactions: new RedactionReport(Now.AddHours(-1), [new RedactionReportCount("au.tfn", 4)]), + Pipeline: new PipelineReport( + Now.AddHours(-1), + EventsIn: 500, + EventsQueued: 100, + Duplicates: 5, + Suppressed: 45, + BytesIn: 250_000, + BytesQueued: 50_000, + Rows: [new PipelineRowReport("policy", "BWR-POL-AUTH-FAILURE", "accept", 100, 100, 0, 0, 50_000, 50_000)]), + Activity: [new SourceActivityReport("portal", "production", Now, 100)]); + + using HttpResponseMessage hb = await collector.PostAsJsonAsync("/api/collectors/edge-01/heartbeat", heartbeat, cancellation); + Assert.Equal(HttpStatusCode.OK, hb.StatusCode); + + // Viewer can inspect GET /api/pipelines/live. + List flows = (await viewer.GetFromJsonAsync>( + "/api/pipelines/live", ManagementApiTests.ApiJson, cancellation))!; + CollectorPipelineFlow flow = Assert.Single(flows); + Assert.Equal("edge-01", flow.CollectorId); + Assert.Equal(5, flow.Stages.Count); + Assert.Equal(["collect", "redact", "select", "queue", "deliver"], flow.Stages.Select(s => s.Id)); + Assert.Equal(80, flow.ReductionPercent); + Assert.Equal("portal", Assert.Single(flow.TopSources).Application); + Assert.Equal(4, Assert.Single(flow.Redactions).Events); + + // Viewer is forbidden from POST /api/pipelines/collectors/edge-01/tap. + using HttpResponseMessage viewerTap = await viewer.PostAsJsonAsync( + "/api/pipelines/collectors/edge-01/tap", new PipelineTapRequest(Limit: 5), cancellation); + Assert.Equal(HttpStatusCode.Forbidden, viewerTap.StatusCode); + + // Operator succeeds, receives redacted frames, and writes an audit row. + using HttpResponseMessage opTap = await oper.PostAsJsonAsync( + "/api/pipelines/collectors/edge-01/tap", new PipelineTapRequest(Source: "portal", Limit: 5), cancellation); + Assert.Equal(HttpStatusCode.OK, opTap.StatusCode); + PipelineTapResponse tapBody = (await opTap.Content.ReadFromJsonAsync(ManagementApiTests.ApiJson, cancellation))!; + Assert.Equal("live", tapBody.Mode); + Assert.Single(tapBody.Frames); + Assert.Contains("--source portal", tapBody.Command, StringComparison.Ordinal); + + List audits = (await viewer.GetFromJsonAsync>( + "/api/audit", ManagementApiTests.ApiJson, cancellation))!; + Assert.Contains(audits, row => row.Action == "pipeline.tap-sampled" && row.TargetId == "edge-01"); + } + + [Fact] + public async Task SqlServerGuidedSource_ValidatesSecretRefAndBuildsReadOnlyPlanAndRedactedPreview() + { + CancellationToken cancellation = TestContext.Current.CancellationToken; + using TemporaryDirectory directory = new(); + await using WebApplication app = await ManagementApiTests.StartAsync(directory, cancellation); + HttpClient collector = ManagementApiTests.Client(app, BowerRoles.Collector, "sp-sql-01"); + HttpClient approver = ManagementApiTests.Client(app, BowerRoles.Approver, "approver-oid"); + HttpClient oper = ManagementApiTests.Client(app, BowerRoles.Operator, "operator-oid"); + + await collector.PostAsJsonAsync( + "/api/collectors/register", + new CollectorRegistration("sql-01", "sql-01.corp.example", "production", "1.0.1", "sha256:c", "sha256:p", [], []), + cancellation); + await approver.PostAsJsonAsync("/api/approvals/sql-01/approve", new ApprovalRequest("SQL collector"), cancellation); + + Dictionary validValues = new() + { + ["sourceId"] = "sql-audit-primary", + ["schema"] = "dbo", + ["table"] = "SecurityAuditLog", + ["cursorKind"] = "Timestamp", + ["timestampOverlapSeconds"] = "300", + ["pollIntervalSeconds"] = "30", + ["batchSize"] = "500", + ["connectionStringRef"] = "/run/secrets/bower-sql-readonly", + ["application"] = "core-db", + ["environment"] = "production", + ["maximumSilenceMinutes"] = "60" + }; + + using HttpResponseMessage ok = await oper.PostAsJsonAsync( + "/api/sources/plan", new SourceSetupDraft("sql-server", "sql-01", validValues), cancellation); + Assert.Equal(HttpStatusCode.OK, ok.StatusCode); + SourceSetupPlanResult planResult = (await ok.Content.ReadFromJsonAsync(ManagementApiTests.ApiJson, cancellation))!; + Assert.True(planResult.Valid); + Assert.NotNull(planResult.Plan); + Assert.Contains(planResult.Plan!.Files, f => f.Name == "sql-server.json" && f.Content.Contains("SecurityAuditLog", StringComparison.Ordinal)); + Assert.Contains(planResult.Plan.Snippets, s => s.Content.Contains("GRANT SELECT ON [dbo].[SecurityAuditLog]", StringComparison.Ordinal)); + Assert.NotNull(planResult.Preview); + Assert.True(planResult.Preview!.Valid); + // Synthetic sample contains a TFN which must be redacted before returning to the browser. + Assert.DoesNotContain("123 456 782", planResult.Preview.Redacted!, StringComparison.Ordinal); + + // Reject inline password / raw connection string instead of secret reference. + Dictionary badValues = new(validValues) + { + ["connectionStringRef"] = "Server=sql01;Database=Audit;User Id=sa;Password=SuperSecret123!;" + }; + using HttpResponseMessage bad = await oper.PostAsJsonAsync( + "/api/sources/plan", new SourceSetupDraft("sql-server", "sql-01", badValues), cancellation); + SourceSetupPlanResult badResult = (await bad.Content.ReadFromJsonAsync(ManagementApiTests.ApiJson, cancellation))!; + Assert.False(badResult.Valid); + } + + private sealed class StubTapClient : ICollectorTapClient + { + public Task?> TrySampleAsync( + string collectorId, + PipelineTapRequest request, + CancellationToken cancellationToken) => + Task.FromResult?>([ + new PipelineTapFrame( + Now, + "policy", + "redact-and-accept", + "authentication_failure", + "portal/production", + "BWR-POL-AUTH-FAILURE", + "{\"eventType\":\"authentication_failure\",\"actor\":{\"username\":\"[MASKED]\"}}") + ]); + } +} diff --git a/tests/Bower.UnitTests/SourceSetupApiTests.cs b/tests/Bower.UnitTests/SourceSetupApiTests.cs index 25d6b239..e4dbe0a7 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", "docker", "aws", "gcp", "ama", "http-sdk"], types.Select(type => type.Id)); + Assert.Equal(["syslog", "windows-eventlog", "file", "sql-server", "docker", "aws", "gcp", "ama", "http-sdk"], types.Select(type => type.Id)); string[] kinds = [ SourceFieldKinds.Text, SourceFieldKinds.Number, SourceFieldKinds.Choice, SourceFieldKinds.Boolean, diff --git a/ui/Bower.Management.Web/src/components/PipelineFlowDiagram.tsx b/ui/Bower.Management.Web/src/components/PipelineFlowDiagram.tsx new file mode 100644 index 00000000..f8c06c6a --- /dev/null +++ b/ui/Bower.Management.Web/src/components/PipelineFlowDiagram.tsx @@ -0,0 +1,369 @@ +import { Activity, ArrowRight, Eye, RefreshCw } from "lucide-react"; +import { useState } from "react"; +import { useApi } from "../api"; +import { EmptyState, ResourceState } from "./ui"; +import { useResource } from "../hooks/useResource"; +import { formatDate, shortHash } from "../lib/format"; +import type { CollectorPipelineFlow, PipelineTapResponse } from "../types"; + +export function PipelineFlowDiagram({ canOperate }: { canOperate: boolean }) { + const [refresh, setRefresh] = useState(0); + const flows = useResource("/api/pipelines/live", refresh); + const [selectedCollectorId, setSelectedCollectorId] = useState(""); + const [selectedStageId, setSelectedStageId] = useState("collect"); + const [tapResult, setTapResult] = useState(null); + const [tapBusy, setTapBusy] = useState(false); + const [tapError, setTapError] = useState(null); + const api = useApi(); + + async function runTap(collectorId: string) { + setTapBusy(true); + setTapError(null); + try { + const response = await api( + `/api/pipelines/collectors/${encodeURIComponent(collectorId)}/tap`, + { + method: "POST", + body: JSON.stringify({ limit: 10 }) + } + ); + setTapResult(response); + } catch (error) { + setTapError(error instanceof Error ? error.message : "Could not sample events."); + } finally { + setTapBusy(false); + } + } + + return ( +
+
+
+

Live pipeline flow

+

+ Collect → Redact → Select → Queue → Deliver, backed by collector heartbeat counters and top sources. +

+
+ +
+ +
+ + {(items) => { + if (!items.length) { + return ( + +
+
+ ); +} diff --git a/ui/Bower.Management.Web/src/pages/PipelinesPage.test.tsx b/ui/Bower.Management.Web/src/pages/PipelinesPage.test.tsx new file mode 100644 index 00000000..aa49eda2 --- /dev/null +++ b/ui/Bower.Management.Web/src/pages/PipelinesPage.test.tsx @@ -0,0 +1,120 @@ +import { cleanup, fireEvent, render, screen } from "@testing-library/react"; +import { MemoryRouter } from "react-router-dom"; +import { afterEach, describe, expect, it, vi } from "vitest"; +import { AuthenticationProvider } from "../auth"; +import { PipelinesPage } from "./PipelinesPage"; +import type { CollectorPipelineFlow } from "../types"; + +const sampleFlow: CollectorPipelineFlow = { + collectorId: "edge-01", + machineName: "edge-01.corp.example", + site: "production", + connectivity: "online", + lastSeenAt: "2026-11-22T07:00:00Z", + policyHash: "sha256:abcdef0123456789", + privacyProfileHash: "sha256:1234567890abcdef", + eventsIn: 1000, + eventsQueued: 120, + eventsSuppressed: 80, + eventsRejected: 800, + duplicates: 0, + bytesIn: 500000, + bytesQueued: 60000, + reductionPercent: 88, + queueDepth: 4, + deadLettered: 0, + oldestUndeliveredAgeSeconds: 12, + deliveryStatus: "healthy", + lastSuccessfulDeliveryAt: "2026-11-22T06:59:45Z", + stages: [ + { id: "collect", title: "Collect", light: "green", headline: "2 sources configured", detail: "1,000 candidate event(s) seen" }, + { id: "redact", title: "Redact", light: "green", headline: "5 finding(s) protected", detail: "Assigned privacy profile in sync" }, + { id: "select", title: "Select", light: "green", headline: "120 kept of 1,000", detail: "88% noise filtered" }, + { id: "queue", title: "Queue", light: "green", headline: "4 waiting", detail: "Oldest waiting event is 12s old" }, + { id: "deliver", title: "Deliver", light: "green", headline: "azure-logs-ingestion", detail: "Status: healthy" } + ], + sources: [{ id: "local-http", type: "local-http", status: "healthy", lagSeconds: null, lastEventAt: null }], + outputs: [{ id: "azure-logs-ingestion", type: "azure-logs-ingestion", status: "healthy", lastAcknowledgedAt: null, lastErrorCode: null }], + topSources: [{ application: "portal", environment: "production", lastSeenAt: "2026-11-22T06:59:50Z", eventCount: 120 }], + redactions: [{ type: "au.tfn", label: "Tax file numbers", events: 5 }], + policyBreakdown: [ + { stage: "policy", policyId: "BWR-POL-AUTH-FAILURE", action: "accept", events: 120, queued: 120, duplicates: 0, suppressed: 0, bytesIn: 60000, bytesQueued: 60000 } + ] +}; + +function stubApi(roles: string[]) { + const fetchMock = vi.fn(async (input: RequestInfo | URL, init?: RequestInit) => { + const path = new URL(String(input), "http://localhost").pathname; + if (path === "/api/access/me") { + return json({ objectId: "u1", displayName: "Alex", roles, developmentAuthentication: true }); + } + if (path === "/api/pipelines/live") { + return json([sampleFlow]); + } + if (path === "/api/pipelines/templates") { + return json([]); + } + if (path === "/api/pipelines/collectors/edge-01/tap" && init?.method === "POST") { + return json({ + collectorId: "edge-01", + mode: "cli", + command: "bower tap --url http://127.0.0.1:4319 --limit 10 --duration 15", + note: "Collectors communicate outbound only.", + frames: [], + capturedAt: "2026-11-22T07:01:00Z" + }); + } + return json({ error: `Unexpected ${path}` }, 500); + }); + vi.stubGlobal("fetch", fetchMock); + return fetchMock; +} + +function json(body: unknown, status = 200) { + return new Response(JSON.stringify(body), { + status, + headers: { "Content-Type": "application/json" } + }); +} + +describe("PipelinesPage visual flow", () => { + afterEach(() => { + cleanup(); + vi.unstubAllGlobals(); + }); + + it("renders all five stages, top sources, redactions, and operator tap", async () => { + stubApi(["Bower.Operator"]); + render( + + + + + + ); + + expect(await screen.findByText("Live pipeline flow")).toBeTruthy(); + expect(screen.getByText("88%")).toBeTruthy(); + expect(screen.getByText("portal")).toBeTruthy(); + + fireEvent.click(screen.getByRole("button", { name: /^Redact/i })); + expect(screen.getByText(/Tax file numbers/)).toBeTruthy(); + + fireEvent.click(screen.getByRole("button", { name: /Sample redacted events/i })); + expect(await screen.findByText(/bower tap --url/)).toBeTruthy(); + }); + + it("hides the tap button for Viewers", async () => { + stubApi(["Bower.Viewer"]); + render( + + + + + + ); + + expect(await screen.findByText("Live pipeline flow")).toBeTruthy(); + expect(screen.queryByRole("button", { name: /Sample redacted events/i })).toBeNull(); + }); +}); diff --git a/ui/Bower.Management.Web/src/pages/PipelinesPage.tsx b/ui/Bower.Management.Web/src/pages/PipelinesPage.tsx index cb4e202b..20bf1372 100644 --- a/ui/Bower.Management.Web/src/pages/PipelinesPage.tsx +++ b/ui/Bower.Management.Web/src/pages/PipelinesPage.tsx @@ -1,4 +1,5 @@ import { GitBranch } from "lucide-react"; +import { PipelineFlowDiagram } from "../components/PipelineFlowDiagram"; import { Page, EmptyState, ResourceState } from "../components/ui"; import { useResource } from "../hooks/useResource"; import type { Access, PipelineTemplate } from "../types"; @@ -13,11 +14,14 @@ export function PipelinesPage() { return ( - {canEdit ? :

- Viewing only. An operator can generate and preview parser configuration. You can read the available templates below. -

} + +
+ {canEdit ? :

+ Viewing only. An operator can sample redacted events and generate parser configuration. You can inspect live pipeline counters and read the available templates below. +

} +
{(templates) => templates.length ? ( diff --git a/ui/Bower.Management.Web/src/styles.css b/ui/Bower.Management.Web/src/styles.css index 41370d0a..95b6d36d 100644 --- a/ui/Bower.Management.Web/src/styles.css +++ b/ui/Bower.Management.Web/src/styles.css @@ -2356,3 +2356,102 @@ input[type="checkbox"]:focus-visible { font-weight: 400; line-height: 1.5; } + +.pipeline-toolbar { + display: flex; + flex-wrap: wrap; + align-items: flex-end; + justify-content: space-between; + gap: var(--space-4); + margin-block-end: var(--space-4); +} + +.pipeline-summary-chips { + display: flex; + flex-wrap: wrap; + gap: var(--space-4); + font-size: var(--text-sm); + color: var(--color-ink-secondary); +} + +.pipeline-flow { + display: flex; + flex-wrap: wrap; + align-items: stretch; + gap: var(--space-2); + list-style: none; + margin: 0; + padding: 0; +} + +.pipeline-flow__item { + display: flex; + align-items: center; + flex: 1 1 11rem; + gap: var(--space-2); +} + +.pipeline-flow__arrow { + flex: 0 0 auto; + color: var(--color-ink-muted); +} + +.pipeline-stage { + display: grid; + gap: var(--space-1); + flex: 1 1 auto; + text-align: left; + padding: var(--space-3); + border: 1px solid var(--color-rule); + border-inline-start-width: 4px; + border-radius: var(--radius-sm); + background: var(--color-surface); + color: var(--color-ink); + cursor: pointer; +} + +.pipeline-stage--green { border-inline-start-color: var(--color-positive); } +.pipeline-stage--amber { border-inline-start-color: var(--color-warning); } +.pipeline-stage--red { border-inline-start-color: var(--color-danger); } + +.pipeline-stage--selected { + outline: 2px solid var(--color-accent); + outline-offset: 1px; + background: var(--color-surface-muted); +} + +.pipeline-stage__title { + font-size: var(--text-xs); + text-transform: uppercase; + letter-spacing: 0.04em; + color: var(--color-ink-muted); +} + +.pipeline-stage__headline { + font-size: var(--text-sm); +} + +.pipeline-stage__detail { + font-size: var(--text-xs); + color: var(--color-ink-secondary); +} + +.pipeline-stage-panel { + margin-block-start: var(--space-4); + padding: var(--space-4); + border: 1px solid var(--color-rule); + border-radius: var(--radius-sm); + background: var(--color-surface-muted); +} + +.pipeline-tap-bar { + display: flex; + flex-wrap: wrap; + align-items: center; + gap: var(--space-3); + margin-block-start: var(--space-4); +} + +.pipeline-tap-result { + margin-block-start: var(--space-3); +} diff --git a/ui/Bower.Management.Web/src/types.ts b/ui/Bower.Management.Web/src/types.ts index fe2f94b9..ad952f50 100644 --- a/ui/Bower.Management.Web/src/types.ts +++ b/ui/Bower.Management.Web/src/types.ts @@ -642,3 +642,84 @@ export interface SourceSetupRequestDetail extends SourceSetupRequestSummary { values: Record; plan: SourceSetupPlan; } + +export interface PipelineFlowStage { + id: string; + title: string; + light: "green" | "amber" | "red"; + headline: string; + detail: string; +} + +export interface SourceActivityReport { + application: string; + environment: string; + lastSeenAt: string; + eventCount: number; +} + +export interface RedactionSummaryItem { + type: string; + label: string; + events: number; +} + +export interface PipelineRowReport { + stage: string; + policyId: string; + action: string; + events: number; + queued: number; + duplicates: number; + suppressed: number; + bytesIn: number; + bytesQueued: number; +} + +export interface CollectorPipelineFlow { + collectorId: string; + machineName: string; + site: string; + connectivity: string; + lastSeenAt: string; + policyHash: string; + privacyProfileHash: string; + eventsIn: number; + eventsQueued: number; + eventsSuppressed: number; + eventsRejected: number; + duplicates: number; + bytesIn: number; + bytesQueued: number; + reductionPercent: number | null; + queueDepth: number; + deadLettered: number; + oldestUndeliveredAgeSeconds: number | null; + deliveryStatus: string; + lastSuccessfulDeliveryAt: string | null; + stages: PipelineFlowStage[]; + sources: SourceReport[]; + outputs: OutputReport[]; + topSources: SourceActivityReport[]; + redactions: RedactionSummaryItem[]; + policyBreakdown: PipelineRowReport[]; +} + +export interface PipelineTapFrame { + observedAt: string; + stage: string; + decision: string; + eventType: string | null; + source: string | null; + policyId: string | null; + redactedPayload: string | null; +} + +export interface PipelineTapResponse { + collectorId: string; + mode: "live" | "cli"; + command: string; + note: string; + frames: PipelineTapFrame[]; + capturedAt: string; +}