From bc92c24133036ef0b37db6cf0e2ec14ef3fc9297 Mon Sep 17 00:00:00 2001 From: Justin Middler Date: Sun, 22 Nov 2026 09:08:13 +1100 Subject: [PATCH] feat(console): add plain-language alert catalogue, deduplicated notifications, and audited mutes (#103) --- docs/security/threat-model.md | 8 + src/Bower.Management.Api/AlertCatalogue.cs | 69 ++++ src/Bower.Management.Api/AlertEndpoints.cs | 87 +++++ src/Bower.Management.Api/AlertModels.cs | 49 +++ .../AlertNotificationService.cs | 225 ++++++++++++ src/Bower.Management.Api/HomeModels.cs | 13 +- .../Jobs/AlertNotificationJob.cs | 85 +++++ .../ManagementApplication.cs | 14 + src/Bower.Management.Api/ManagementJson.cs | 6 + .../ManagementStore.Alerts.cs | 334 ++++++++++++++++++ .../ManagementStore.Home.cs | 26 +- src/Bower.Management.Api/ManagementStore.cs | 1 + .../Bower.UnitTests/AlertNotificationTests.cs | 223 ++++++++++++ tests/Bower.UnitTests/ManagementApiTests.cs | 2 +- .../src/pages/AlertsMute.test.tsx | 116 ++++++ .../src/pages/HomePage.tsx | 152 +++++++- ui/Bower.Management.Web/src/types.ts | 4 + 17 files changed, 1408 insertions(+), 6 deletions(-) create mode 100644 src/Bower.Management.Api/AlertCatalogue.cs create mode 100644 src/Bower.Management.Api/AlertEndpoints.cs create mode 100644 src/Bower.Management.Api/AlertModels.cs create mode 100644 src/Bower.Management.Api/AlertNotificationService.cs create mode 100644 src/Bower.Management.Api/Jobs/AlertNotificationJob.cs create mode 100644 src/Bower.Management.Api/ManagementStore.Alerts.cs create mode 100644 tests/Bower.UnitTests/AlertNotificationTests.cs create mode 100644 ui/Bower.Management.Web/src/pages/AlertsMute.test.tsx diff --git a/docs/security/threat-model.md b/docs/security/threat-model.md index a8a68619..0c560df7 100644 --- a/docs/security/threat-model.md +++ b/docs/security/threat-model.md @@ -266,6 +266,14 @@ evidence. (never raw sample inputs or sensitive strings). Pack installs require two-person approval (the requester cannot approve) and write desired-policy hashes plus audit rows atomically; every collector still verifies pack signatures independently on load. +- Alert notifications and mutes (`AlertNotificationJob`, `/api/alerts/*`): outbound Teams + webhook URLs (`BOWER_ALERT_TEAMS_WEBHOOK_FILE`, HTTPS required) and SMTP passwords + (`BOWER_ALERT_EMAIL_PASSWORD_FILE`) are loaded strictly from server-side files and are + never persisted in the management database or returned over HTTP. Notification bodies + carry fixed plain-language condition wording, affected counts, suggested fixes and a + console link requiring Entra sign-in — never raw event payloads or collector secrets. + Alert mutes require the `Operate` role with a mandatory reason and bounded expiry, and + every mute, unmute and dispatched notification writes an audit row. - Management API abuse: Entra-only endpoints (except token enrolment and the enrolled-collector credential, above), per-principal rate limiting, HSTS on HTTPS, restricted CORS headers and methods, and fixed error messages that never diff --git a/src/Bower.Management.Api/AlertCatalogue.cs b/src/Bower.Management.Api/AlertCatalogue.cs new file mode 100644 index 00000000..ae9e78a1 --- /dev/null +++ b/src/Bower.Management.Api/AlertCatalogue.cs @@ -0,0 +1,69 @@ +namespace Bower.Management.Api; + +/// +/// Deterministic mapping from internal health condition IDs and collector EventIds to plain +/// wording and suggested fixes. Single source of truth for alert validation and catalogue reads. +/// +public static class AlertCatalogue +{ + public static readonly IReadOnlyList Entries = + [ + new("offline", HomeStates.Red, "Collector offline", + "A collector has not checked in for more than 15 minutes.", + "Check that the machine is switched on and can reach Bower.", "/collectors", ["2101"]), + new("history-changed", HomeStates.Red, "Event history changed unexpectedly", + "A collector reported a queue ledger sequence or hash that regressed.", + "Treat this as a possible tampering sign: check the machine and the Audit page.", "/audit", ["1600"]), + new("not-sending", HomeStates.Red, "Delivery stopped", + "A collector has not been able to send events for more than 15 minutes.", + "Open Collectors to see which machine is affected and check its connection to Azure.", "/collectors", ["1008"]), + new("stale", HomeStates.Amber, "Collector check-in delayed", + "A collector has not checked in for a few minutes.", + "This usually clears by itself. If it lasts, check the machine.", "/collectors", ["2101"]), + new("queue-full", HomeStates.Amber, "Queue or disk capacity reached", + "A collector has a full queue or critically low free disk space and is refusing new events.", + "Free disk space on the machine, or let it catch up once its connection to Azure works.", "/collectors", ["1500", "1501"]), + new("send-trouble", HomeStates.Amber, "Delivery trouble", + "A collector had trouble sending events to its destination.", + "Bower keeps trying. If it lasts more than 15 minutes, check the machine's connection to Azure.", "/collectors", ["1008"]), + new("pending", HomeStates.Amber, "Collector awaiting approval", + "A new collector has asked to join the fleet.", + "Review the request on the Approvals page.", "/approvals", []), + new("suspended", HomeStates.Amber, "Collector paused", + "A collector has been suspended by an administrator or inactivity policy.", + "Ask a Bower administrator to check why and reinstate it if it is still needed.", "/collectors", []), + new("set-aside", HomeStates.Amber, "Events set aside in dead-letter queue", + "Events could not be delivered after retries and were set aside.", + "Open Collectors to see which machine has them.", "/collectors", ["1510", "1511"]), + new("backlog", HomeStates.Amber, "Delivery backlog", + "Queued events have been waiting more than 15 minutes to be sent.", + "Check the machine's connection to Azure.", "/collectors", ["1008"]), + new("quiet-source", HomeStates.Amber, "Expected source went quiet", + "An expected application or event source stopped sending events within its allowance.", + "Check that the app is running and still sends events to Bower.", "/collectors", ["1110", "1120"]), + new("policy-not-applied", HomeStates.Amber, "Policy rules out of sync", + "A collector has not switched to its assigned event rules yet.", + "Open Collectors to see which rules it is using.", "/collectors", ["1702"]), + new("privacy-not-applied", HomeStates.Amber, "Privacy profile out of sync", + "A collector has not applied its assigned privacy profile yet.", + "Open Privacy profiles to check the rollout.", "/privacy-profiles", ["1702"]), + new("job-failed", HomeStates.Amber, "Maintenance job failed", + "A collector maintenance job failed on its last run.", + "Open the collector's details to see which job; it runs again on its schedule.", "/collectors", ["1302"]), + new("no-collectors", HomeStates.Amber, "No collectors connected", + "No collectors are connected to management yet.", + "Follow the Setup page to connect your first collector.", "/setup", []), + new(HomeProofStates.NotProven, HomeStates.Amber, "Sentinel delivery not yet proven", + "No recent test event has been verified in Microsoft Sentinel by query.", + "Send a test event from the Setup page.", "/setup", []), + new(HomeProofStates.Simulated, HomeStates.Amber, "Simulated delivery only", + "The last test event ran in simulated mode and was not verified in Microsoft Sentinel.", + "Send a real test event from the Setup page once Sentinel credentials are configured.", "/setup", []) + ]; + + private static readonly HashSet KnownIds = + Entries.Select(entry => entry.ConditionId).ToHashSet(StringComparer.Ordinal); + + public static bool IsKnownCondition(string? conditionId) => + !string.IsNullOrWhiteSpace(conditionId) && KnownIds.Contains(conditionId); +} diff --git a/src/Bower.Management.Api/AlertEndpoints.cs b/src/Bower.Management.Api/AlertEndpoints.cs new file mode 100644 index 00000000..47a78f7d --- /dev/null +++ b/src/Bower.Management.Api/AlertEndpoints.cs @@ -0,0 +1,87 @@ +using System.Security.Claims; +using Microsoft.AspNetCore.Mvc; + +namespace Bower.Management.Api; + +/// +/// Plain-language alert catalogue, notification channel status, and audited mute/unmute endpoints. +/// +internal static class AlertEndpoints +{ + private const long BodyLimit = 16 * 1024; + + public static void Map(RouteGroupBuilder api) + { + api.MapGet("/alerts/catalogue", () => Results.Ok(AlertCatalogue.Entries)) + .RequireAuthorization("View"); + + api.MapGet("/alerts/channels", (AlertNotificationOptions options) => Results.Ok(options.Status())) + .RequireAuthorization("View"); + + api.MapGet( + "/alerts/mutes", + async (ManagementStore store, TimeProvider clock, CancellationToken cancellationToken) => + Results.Ok(await store.ListActiveMutesAsync(clock.GetUtcNow(), cancellationToken))) + .RequireAuthorization("View"); + + api.MapPost( + "/alerts/mute", + async ( + AlertMuteRequest request, + ClaimsPrincipal user, + ManagementStore store, + TimeProvider clock, + CancellationToken cancellationToken) => + { + string conditionId = request.ConditionId?.Trim() ?? string.Empty; + int duration = request.DurationMinutes ?? ManagementStore.DefaultMuteMinutes; + try + { + AlertMuteRecord created = await store.MuteAlertAsync( + conditionId, + request.CollectorId, + duration, + request.Reason, + ManagementApplication.ObjectId(user), + ManagementApplication.DisplayName(user), + clock.GetUtcNow(), + cancellationToken); + return Results.Created($"/api/alerts/mutes/{created.Id}", created); + } + catch (ArgumentOutOfRangeException exception) + { + return Results.BadRequest(new ErrorResponse(exception.Message)); + } + catch (ArgumentException exception) + { + return Results.BadRequest(new ErrorResponse(exception.Message)); + } + }) + .WithMetadata(new RequestSizeLimitAttribute(BodyLimit)) + .RequireAuthorization("Operate"); + + api.MapPost( + "/alerts/mutes/{id}/unmute", + async ( + string id, + ClaimsPrincipal user, + ManagementStore store, + TimeProvider clock, + CancellationToken cancellationToken) => + { + if (string.IsNullOrWhiteSpace(id) || id.Length != 32 || !id.All(Uri.IsHexDigit)) + { + return Results.NotFound(); + } + + AlertMuteRecord? updated = await store.UnmuteAlertAsync( + id, + ManagementApplication.ObjectId(user), + ManagementApplication.DisplayName(user), + clock.GetUtcNow(), + cancellationToken); + return updated is null ? Results.NotFound() : Results.Ok(updated); + }) + .RequireAuthorization("Operate"); + } +} diff --git a/src/Bower.Management.Api/AlertModels.cs b/src/Bower.Management.Api/AlertModels.cs new file mode 100644 index 00000000..e4f937fe --- /dev/null +++ b/src/Bower.Management.Api/AlertModels.cs @@ -0,0 +1,49 @@ +namespace Bower.Management.Api; + +/// One entry in the plain-language alert catalogue mapping internal codes to operator fixes. +public sealed record AlertCatalogueEntry( + string ConditionId, + string Severity, + string Title, + string PlainDescription, + string SuggestedFix, + string Page, + IReadOnlyList RelatedEventIds); + +/// Request to mute one alert condition (fleet-wide or for one collector) with a required reason. +public sealed record AlertMuteRequest( + string? ConditionId, + string? CollectorId, + int? DurationMinutes, + string? Reason); + +/// An active or historical audited alert mute. +public sealed record AlertMuteRecord( + string Id, + string ConditionId, + string? CollectorId, + string Reason, + string MutedByObjectId, + string MutedByName, + DateTimeOffset MutedAt, + DateTimeOffset ExpiresAt, + DateTimeOffset? UnmutedAt, + string? UnmutedByName); + +/// Metadata-only status of configured notification channels (never URLs, paths or secrets). +public sealed record AlertChannelStatus( + bool TeamsConfigured, + bool EmailConfigured, + bool ConsoleUrlConfigured, + int DedupWindowMinutes); + +/// Metadata-only outbound notification payload. Never contains raw event content or secrets. +public sealed record AlertNotificationMessage( + string DedupKey, + string ConditionId, + string Severity, + string Summary, + string SuggestedFix, + int AffectedCount, + string? ConsoleAlertsUrl, + DateTimeOffset DetectedAt); diff --git a/src/Bower.Management.Api/AlertNotificationService.cs b/src/Bower.Management.Api/AlertNotificationService.cs new file mode 100644 index 00000000..bec31927 --- /dev/null +++ b/src/Bower.Management.Api/AlertNotificationService.cs @@ -0,0 +1,225 @@ +using System.Net; +using System.Net.Mail; +using System.Text; +using System.Text.Json; + +namespace Bower.Management.Api; + +/// +/// Server-side notification channel configuration. Secrets (Teams webhook URL, SMTP password) +/// come strictly from files on disk and are never stored in the database or returned via HTTP. +/// +public sealed class AlertNotificationOptions +{ + public const string TeamsWebhookFileSetting = "BOWER_ALERT_TEAMS_WEBHOOK_FILE"; + public const string EmailHostSetting = "BOWER_ALERT_EMAIL_HOST"; + public const string EmailPortSetting = "BOWER_ALERT_EMAIL_PORT"; + public const string EmailFromSetting = "BOWER_ALERT_EMAIL_FROM"; + public const string EmailToSetting = "BOWER_ALERT_EMAIL_TO"; + public const string EmailUsernameSetting = "BOWER_ALERT_EMAIL_USERNAME"; + public const string EmailPasswordFileSetting = "BOWER_ALERT_EMAIL_PASSWORD_FILE"; + public const string EmailUseTlsSetting = "BOWER_ALERT_EMAIL_USE_TLS"; + public const string ConsoleUrlSetting = "BOWER_ALERT_CONSOLE_URL"; + public const string DedupMinutesSetting = "BOWER_ALERT_DEDUP_MINUTES"; + + public Uri? TeamsWebhookUri { get; init; } + public string? EmailHost { get; init; } + public int EmailPort { get; init; } = 587; + public string? EmailFrom { get; init; } + public IReadOnlyList EmailRecipients { get; init; } = []; + public string? EmailUsername { get; init; } + public string? EmailPassword { get; init; } + public bool EmailUseTls { get; init; } = true; + public Uri? ConsoleBaseUrl { get; init; } + public TimeSpan DedupWindow { get; init; } = TimeSpan.FromMinutes(60); + + public bool TeamsConfigured => TeamsWebhookUri is not null; + + public bool EmailConfigured => + !string.IsNullOrWhiteSpace(EmailHost) + && !string.IsNullOrWhiteSpace(EmailFrom) + && EmailRecipients.Count > 0; + + public AlertChannelStatus Status() => new( + TeamsConfigured, + EmailConfigured, + ConsoleBaseUrl is not null, + (int)Math.Round(DedupWindow.TotalMinutes)); + + public static AlertNotificationOptions FromConfiguration(IConfiguration configuration) + { + Uri? webhook = ReadHttpsUriFile(configuration[TeamsWebhookFileSetting], TeamsWebhookFileSetting); + Uri? consoleUrl = ReadOptionalConsoleUrl(configuration[ConsoleUrlSetting]); + int dedupMinutes = configuration.GetValue(DedupMinutesSetting, 60); + if (dedupMinutes is < 5 or > 1440) + { + throw new InvalidOperationException($"{DedupMinutesSetting} must be between 5 and 1440."); + } + + string? host = Blank(configuration[EmailHostSetting]); + int port = configuration.GetValue(EmailPortSetting, 587); + if (port is < 1 or > 65535) + { + throw new InvalidOperationException($"{EmailPortSetting} must be between 1 and 65535."); + } + + string? from = Blank(configuration[EmailFromSetting]); + string[] recipients = (configuration[EmailToSetting] ?? string.Empty) + .Split([',', ';'], StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries); + string? username = Blank(configuration[EmailUsernameSetting]); + string? passwordFile = Blank(configuration[EmailPasswordFileSetting]); + string? password = passwordFile is null ? null : File.ReadAllText(passwordFile).Trim(); + bool useTls = configuration.GetValue(EmailUseTlsSetting, true); + + return new AlertNotificationOptions + { + TeamsWebhookUri = webhook, + EmailHost = host, + EmailPort = port, + EmailFrom = from, + EmailRecipients = recipients, + EmailUsername = username, + EmailPassword = password, + EmailUseTls = useTls, + ConsoleBaseUrl = consoleUrl, + DedupWindow = TimeSpan.FromMinutes(dedupMinutes) + }; + } + + private static Uri? ReadHttpsUriFile(string? path, string settingName) + { + if (string.IsNullOrWhiteSpace(path)) + { + return null; + } + + string raw = File.ReadAllText(path.Trim()).Trim(); + if (!Uri.TryCreate(raw, UriKind.Absolute, out Uri? uri) + || !string.Equals(uri.Scheme, Uri.UriSchemeHttps, StringComparison.OrdinalIgnoreCase)) + { + throw new InvalidOperationException($"{settingName} must contain an absolute https:// URL."); + } + + return uri; + } + + private static Uri? ReadOptionalConsoleUrl(string? raw) + { + if (string.IsNullOrWhiteSpace(raw)) + { + return null; + } + + if (!Uri.TryCreate(raw.Trim(), UriKind.Absolute, out Uri? uri) + || !string.Equals(uri.Scheme, Uri.UriSchemeHttps, StringComparison.OrdinalIgnoreCase)) + { + throw new InvalidOperationException($"{ConsoleUrlSetting} must be an absolute https:// URL."); + } + + return uri; + } + + private static string? Blank(string? value) => string.IsNullOrWhiteSpace(value) ? null : value.Trim(); +} + +/// Outbound plain-language alert notification channel. +public interface IAlertNotificationChannel +{ + string Name { get; } + bool IsConfigured { get; } + Task SendAsync(AlertNotificationMessage message, CancellationToken cancellationToken); +} + +/// Posts metadata-only plain-language alerts to a Microsoft Teams webhook over HTTPS. +public sealed class TeamsWebhookAlertChannel( + AlertNotificationOptions options, + IHttpClientFactory httpClientFactory) : IAlertNotificationChannel +{ + public const string HttpClientName = "bower-alert-teams"; + + public string Name => "teams"; + public bool IsConfigured => options.TeamsConfigured; + + public async Task SendAsync(AlertNotificationMessage message, CancellationToken cancellationToken) + { + if (options.TeamsWebhookUri is null) + { + return; + } + + string title = $"Bower alert ({message.Severity.ToUpperInvariant()}): {message.ConditionId}"; + StringBuilder text = new(); + text.Append(message.Summary).Append("\n\nSuggested fix: ").Append(message.SuggestedFix); + if (message.ConsoleAlertsUrl is not null) + { + text.Append("\n\nConsole (sign-in required): ").Append(message.ConsoleAlertsUrl); + } + + TeamsWebhookPayload payload = new(title, text.ToString()); + string json = JsonSerializer.Serialize(payload, ManagementJsonContext.Default.TeamsWebhookPayload); + using HttpClient client = httpClientFactory.CreateClient(HttpClientName); + using HttpRequestMessage request = new(HttpMethod.Post, options.TeamsWebhookUri) + { + Content = new StringContent(json, Encoding.UTF8, "application/json") + }; + using HttpResponseMessage response = await client.SendAsync(request, cancellationToken); + response.EnsureSuccessStatusCode(); + } +} + +public sealed record TeamsWebhookPayload(string Title, string Text); + +/// Sends metadata-only plain-language alerts via SMTP email (zero extra dependencies). +public sealed class SmtpEmailAlertChannel(AlertNotificationOptions options) : IAlertNotificationChannel +{ + public string Name => "email"; + public bool IsConfigured => options.EmailConfigured; + + public async Task SendAsync(AlertNotificationMessage message, CancellationToken cancellationToken) + { + if (!options.EmailConfigured) + { + return; + } + + using MailMessage mail = new() + { + From = new MailAddress(options.EmailFrom!), + Subject = $"[Bower {message.Severity.ToUpperInvariant()}] {message.Summary}", + Body = BuildBody(message), + IsBodyHtml = false + }; + foreach (string recipient in options.EmailRecipients) + { + mail.To.Add(recipient); + } + + using SmtpClient smtp = new(options.EmailHost!, options.EmailPort) + { + EnableSsl = options.EmailUseTls + }; + if (options.EmailUsername is not null && options.EmailPassword is not null) + { + smtp.Credentials = new NetworkCredential(options.EmailUsername, options.EmailPassword); + } + + await smtp.SendMailAsync(mail, cancellationToken); + } + + private static string BuildBody(AlertNotificationMessage message) + { + StringBuilder builder = new(); + builder.AppendLine("Bower fleet alert (metadata only; no event content is included)."); + builder.AppendLine(); + builder.Append("Condition: ").AppendLine(message.ConditionId); + builder.Append("Severity: ").AppendLine(message.Severity); + builder.Append("Summary: ").AppendLine(message.Summary); + builder.Append("Suggested fix: ").AppendLine(message.SuggestedFix); + if (message.ConsoleAlertsUrl is not null) + { + builder.Append("Open console (sign-in required): ").AppendLine(message.ConsoleAlertsUrl); + } + + return builder.ToString(); + } +} diff --git a/src/Bower.Management.Api/HomeModels.cs b/src/Bower.Management.Api/HomeModels.cs index 4e7021e5..a9c56765 100644 --- a/src/Bower.Management.Api/HomeModels.cs +++ b/src/Bower.Management.Api/HomeModels.cs @@ -1,3 +1,5 @@ +using System.Text.Json.Serialization; + namespace Bower.Management.Api; /// @@ -30,7 +32,16 @@ public static class HomeProofStates public sealed record HomeFix(string Action, string Page); /// One thing that needs attention. Fixed Bower text, never raw collector or Azure detail. -public sealed record HomeAttention(string Id, string State, string Message, HomeFix Fix, int Count); +public sealed record HomeAttention( + string Id, + string State, + string Message, + HomeFix Fix, + int Count, + [property: JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingDefault)] bool Muted = false, + [property: JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] string? MuteId = null, + [property: JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] DateTimeOffset? MutedUntil = null, + [property: JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] string? MuteReason = null); /// /// One collector group (environment): the worst condition decides the state and the reason. diff --git a/src/Bower.Management.Api/Jobs/AlertNotificationJob.cs b/src/Bower.Management.Api/Jobs/AlertNotificationJob.cs new file mode 100644 index 00000000..264f027b --- /dev/null +++ b/src/Bower.Management.Api/Jobs/AlertNotificationJob.cs @@ -0,0 +1,85 @@ +namespace Bower.Management.Api.Jobs; + +/// +/// Evaluates active plain-language fleet alerts, skips audited mutes, deduplicates repeated +/// alerts within , marks resolved alerts, +/// and dispatches metadata-only notifications to configured channels (Teams webhook / email). +/// +public sealed partial class AlertNotificationJob( + ManagementStore store, + AlertNotificationOptions options, + IEnumerable channels, + TimeProvider clock, + ILogger logger) +{ + public const string Id = "alert-notifications"; + public const int RetryAttempts = 1; + + public async Task RunAsync(CancellationToken cancellationToken) + { + DateTimeOffset now = clock.GetUtcNow(); + IAlertNotificationChannel[] configuredChannels = channels.Where(channel => channel.IsConfigured).ToArray(); + HomeRecord home = await store.HomeAsync(now, cancellationToken); + + HashSet activeKeys = new(StringComparer.Ordinal); + int sent = 0; + + foreach (HomeAttention attention in home.Attention) + { + string dedupKey = $"{attention.Id}:{attention.State}"; + activeKeys.Add(dedupKey); + + if (attention.Muted || configuredChannels.Length == 0) + { + continue; + } + + if (!await store.ShouldSendAlertNotificationAsync(dedupKey, options.DedupWindow, now, cancellationToken)) + { + continue; + } + + string? alertsUrl = options.ConsoleBaseUrl is null + ? null + : new Uri(options.ConsoleBaseUrl, "/alerts").ToString(); + AlertNotificationMessage message = new( + dedupKey, + attention.Id, + attention.State, + attention.Message, + attention.Fix.Action, + attention.Count, + alertsUrl, + now); + + bool deliveredAny = false; + foreach (IAlertNotificationChannel channel in configuredChannels) + { + try + { + await channel.SendAsync(message, cancellationToken); + deliveredAny = true; + } + catch (Exception exception) when (exception is not OperationCanceledException) + { + LogChannelFailure(logger, channel.Name, attention.Id, exception.GetType().Name); + } + } + + if (deliveredAny) + { + await store.RecordAlertNotificationSentAsync(dedupKey, attention.Id, attention.State, now, cancellationToken); + sent++; + } + } + + await store.ResolveClearedAlertNotificationsAsync(activeKeys, now, cancellationToken); + return sent; + } + + [LoggerMessage( + EventId = 2110, + Level = LogLevel.Warning, + Message = "Alert notification channel {Channel} failed for condition {ConditionId} with {ExceptionType}.")] + private static partial void LogChannelFailure(ILogger logger, string channel, string conditionId, string exceptionType); +} diff --git a/src/Bower.Management.Api/ManagementApplication.cs b/src/Bower.Management.Api/ManagementApplication.cs index 5b5f176e..2dfeae89 100644 --- a/src/Bower.Management.Api/ManagementApplication.cs +++ b/src/Bower.Management.Api/ManagementApplication.cs @@ -197,9 +197,16 @@ public static WebApplication Build( builder.Services.AddSingleton(); builder.Services.AddSingleton(); + builder.Services.AddSingleton(AlertNotificationOptions.FromConfiguration(builder.Configuration)); + builder.Services.AddHttpClient(TeamsWebhookAlertChannel.HttpClientName, client => + client.Timeout = TimeSpan.FromSeconds(15)); + builder.Services.AddSingleton(); + builder.Services.AddSingleton(); + builder.Services.AddBowerBackgroundJobs("bower-management", workerCount: 1); builder.Services.AddTransient(); builder.Services.AddTransient(); + builder.Services.AddTransient(); configure?.Invoke(builder); @@ -295,6 +302,11 @@ await store.InterruptSetupCanaryRunsAsync( (job, token) => job.RunAsync(token), Cron.Daily(2), CollectorInactivityJob.RetryAttempts); + jobs.AddOrUpdate( + AlertNotificationJob.Id, + (job, token) => job.RunAsync(token), + "*/5 * * * *", + AlertNotificationJob.RetryAttempts); } private static void MapApi(RouteGroupBuilder api, bool developmentAuthentication) @@ -330,6 +342,8 @@ private static void MapApi(RouteGroupBuilder api, bool developmentAuthentication await store.HomeAsync(clock.GetUtcNow(), cancellationToken)) .RequireAuthorization("View"); + AlertEndpoints.Map(api); + // Plain-English fleet view: one state, reason and fix per collector, computed here. api.MapGet( "/fleet", diff --git a/src/Bower.Management.Api/ManagementJson.cs b/src/Bower.Management.Api/ManagementJson.cs index 8015cc85..cc8acd64 100644 --- a/src/Bower.Management.Api/ManagementJson.cs +++ b/src/Bower.Management.Api/ManagementJson.cs @@ -116,6 +116,12 @@ public sealed record PipelineValidationResponse( [JsonSerializable(typeof(PackPopulationDiff))] [JsonSerializable(typeof(PackInstallRequestRecord))] [JsonSerializable(typeof(List))] +[JsonSerializable(typeof(IReadOnlyList))] +[JsonSerializable(typeof(AlertMuteRequest))] +[JsonSerializable(typeof(AlertMuteRecord))] +[JsonSerializable(typeof(List))] +[JsonSerializable(typeof(AlertChannelStatus))] +[JsonSerializable(typeof(TeamsWebhookPayload))] [JsonSerializable(typeof(Dictionary))] [JsonSerializable(typeof(Microsoft.AspNetCore.Mvc.ProblemDetails))] [JsonSerializable(typeof(HttpValidationProblemDetails))] diff --git a/src/Bower.Management.Api/ManagementStore.Alerts.cs b/src/Bower.Management.Api/ManagementStore.Alerts.cs new file mode 100644 index 00000000..ca704ed6 --- /dev/null +++ b/src/Bower.Management.Api/ManagementStore.Alerts.cs @@ -0,0 +1,334 @@ +using System.Globalization; +using System.Security.Cryptography; +using Microsoft.Data.Sqlite; + +namespace Bower.Management.Api; + +/// +/// Audited alert mutes and outbound notification deduplication state. +/// Every mute and unmute writes an audit row in the same SQLite transaction. +/// +public sealed partial class ManagementStore +{ + public const int MinimumMuteMinutes = 15; + public const int MaximumMuteMinutes = 43_200; // 30 days + public const int DefaultMuteMinutes = 240; // 4 hours + private const string AlertMuteTargetType = "alert-mute"; + + private static Task InitializeAlertsAsync(SqliteConnection connection, CancellationToken cancellationToken) => + ExecuteAsync( + connection, + """ + CREATE TABLE IF NOT EXISTS alert_mutes ( + id TEXT PRIMARY KEY, + condition_id TEXT NOT NULL, + collector_id TEXT NULL, + reason TEXT NOT NULL, + muted_by_object_id TEXT NOT NULL, + muted_by_name TEXT NOT NULL, + muted_at TEXT NOT NULL, + expires_at TEXT NOT NULL, + unmuted_at TEXT NULL, + unmuted_by_object_id TEXT NULL, + unmuted_by_name TEXT NULL + ); + CREATE INDEX IF NOT EXISTS ix_alert_mutes_active + ON alert_mutes(condition_id, expires_at); + + CREATE TABLE IF NOT EXISTS alert_notification_state ( + dedup_key TEXT PRIMARY KEY, + condition_id TEXT NOT NULL, + severity TEXT NOT NULL, + last_sent_at TEXT NOT NULL, + resolved_at TEXT NULL, + send_count INTEGER NOT NULL DEFAULT 1 + ); + """, + cancellationToken); + + internal async Task MuteAlertAsync( + string conditionId, + string? collectorId, + int durationMinutes, + string? reason, + string actorObjectId, + string actorName, + DateTimeOffset now, + CancellationToken cancellationToken) + { + if (!AlertCatalogue.IsKnownCondition(conditionId)) + { + throw new ArgumentException("Unknown alert condition.", nameof(conditionId)); + } + + if (durationMinutes is < MinimumMuteMinutes or > MaximumMuteMinutes) + { + throw new ArgumentOutOfRangeException( + nameof(durationMinutes), + $"Mute duration must be between {MinimumMuteMinutes} and {MaximumMuteMinutes} minutes."); + } + + string trimmedReason = RequireText(reason, nameof(reason)); + string? trimmedCollector = string.IsNullOrWhiteSpace(collectorId) ? null : collectorId.Trim(); + if (trimmedCollector is { Length: > 128 }) + { + throw new ArgumentException("Collector id is too long.", nameof(collectorId)); + } + + string id = Convert.ToHexStringLower(RandomNumberGenerator.GetBytes(16)); + DateTimeOffset expiresAt = now.AddMinutes(durationMinutes); + + await using SqliteConnection connection = await OpenAsync(cancellationToken); + await using SqliteTransaction transaction = connection.BeginTransaction(deferred: false); + + await CommandAsync( + connection, + transaction, + """ + INSERT INTO alert_mutes ( + id, condition_id, collector_id, reason, + muted_by_object_id, muted_by_name, muted_at, expires_at) + VALUES ($id, $condition, $collector, $reason, $actor, $actor_name, $now, $expires); + """, + [ + ("$id", id), + ("$condition", conditionId), + ("$collector", trimmedCollector), + ("$reason", trimmedReason), + ("$actor", actorObjectId), + ("$actor_name", actorName), + ("$now", Format(now)), + ("$expires", Format(expiresAt)) + ], + cancellationToken); + + await InsertAuditAsync( + connection, + transaction, + "alert.muted", + trimmedCollector is null ? conditionId : $"{conditionId}:{trimmedCollector}", + actorObjectId, + actorName, + now, + cancellationToken, + AlertMuteTargetType); + + await transaction.CommitAsync(cancellationToken); + return new AlertMuteRecord( + id, conditionId, trimmedCollector, trimmedReason, actorObjectId, actorName, now, expiresAt, null, null); + } + + internal async Task UnmuteAlertAsync( + string id, + string actorObjectId, + string actorName, + DateTimeOffset now, + CancellationToken cancellationToken) + { + await using SqliteConnection connection = await OpenAsync(cancellationToken); + await using SqliteTransaction transaction = connection.BeginTransaction(deferred: false); + + AlertMuteRecord? existing = await ReadAlertMuteAsync(connection, transaction, id, cancellationToken); + if (existing is null) + { + return null; + } + + if (existing.UnmutedAt is null) + { + await CommandAsync( + connection, + transaction, + """ + UPDATE alert_mutes + SET unmuted_at = $now, + unmuted_by_object_id = $actor, + unmuted_by_name = $actor_name + WHERE id = $id; + """, + [ + ("$now", Format(now)), + ("$actor", actorObjectId), + ("$actor_name", actorName), + ("$id", id) + ], + cancellationToken); + + await InsertAuditAsync( + connection, + transaction, + "alert.unmuted", + existing.CollectorId is null ? existing.ConditionId : $"{existing.ConditionId}:{existing.CollectorId}", + actorObjectId, + actorName, + now, + cancellationToken, + AlertMuteTargetType); + } + + await transaction.CommitAsync(cancellationToken); + return existing with { UnmutedAt = existing.UnmutedAt ?? now, UnmutedByName = existing.UnmutedByName ?? actorName }; + } + + internal async Task> ListActiveMutesAsync( + DateTimeOffset now, + CancellationToken cancellationToken) + { + await using SqliteConnection connection = await OpenAsync(cancellationToken); + await using SqliteCommand command = connection.CreateCommand(); + command.CommandText = """ + SELECT * FROM alert_mutes + WHERE unmuted_at IS NULL AND expires_at > $now + ORDER BY muted_at DESC; + """; + command.Parameters.AddWithValue("$now", Format(now)); + List mutes = []; + await using SqliteDataReader reader = await command.ExecuteReaderAsync(cancellationToken); + while (await reader.ReadAsync(cancellationToken)) + { + mutes.Add(MapAlertMute(reader)); + } + + return mutes; + } + + internal async Task ShouldSendAlertNotificationAsync( + string dedupKey, + TimeSpan dedupWindow, + DateTimeOffset now, + CancellationToken cancellationToken) + { + await using SqliteConnection connection = await OpenAsync(cancellationToken); + await using SqliteCommand command = connection.CreateCommand(); + command.CommandText = """ + SELECT last_sent_at, resolved_at FROM alert_notification_state + WHERE dedup_key = $key; + """; + command.Parameters.AddWithValue("$key", dedupKey); + await using SqliteDataReader reader = await command.ExecuteReaderAsync(cancellationToken); + if (!await reader.ReadAsync(cancellationToken)) + { + return true; + } + + // If the condition previously cleared and returned, notify again immediately. + if (!reader.IsDBNull(1)) + { + return true; + } + + DateTimeOffset lastSent = Parse(reader.GetString(0)); + return now - lastSent >= dedupWindow; + } + + internal async Task RecordAlertNotificationSentAsync( + string dedupKey, + string conditionId, + string severity, + DateTimeOffset now, + CancellationToken cancellationToken) + { + await using SqliteConnection connection = await OpenAsync(cancellationToken); + await using SqliteTransaction transaction = connection.BeginTransaction(deferred: false); + await CommandAsync( + connection, + transaction, + """ + INSERT INTO alert_notification_state (dedup_key, condition_id, severity, last_sent_at, resolved_at, send_count) + VALUES ($key, $condition, $severity, $now, NULL, 1) + ON CONFLICT(dedup_key) DO UPDATE SET + severity = excluded.severity, + last_sent_at = excluded.last_sent_at, + resolved_at = NULL, + send_count = alert_notification_state.send_count + 1; + """, + [ + ("$key", dedupKey), + ("$condition", conditionId), + ("$severity", severity), + ("$now", Format(now)) + ], + cancellationToken); + + await InsertAuditAsync( + connection, + transaction, + "alert.notification-sent", + dedupKey, + "system", + "Bower Alert Notifier", + now, + cancellationToken, + "alert-notification"); + + await transaction.CommitAsync(cancellationToken); + } + + internal async Task ResolveClearedAlertNotificationsAsync( + IReadOnlySet activeDedupKeys, + DateTimeOffset now, + CancellationToken cancellationToken) + { + await using SqliteConnection connection = await OpenAsync(cancellationToken); + await using SqliteTransaction transaction = connection.BeginTransaction(deferred: false); + List openKeys = []; + await using (SqliteCommand select = connection.CreateCommand()) + { + select.Transaction = transaction; + select.CommandText = "SELECT dedup_key FROM alert_notification_state WHERE resolved_at IS NULL;"; + await using SqliteDataReader reader = await select.ExecuteReaderAsync(cancellationToken); + while (await reader.ReadAsync(cancellationToken)) + { + string key = reader.GetString(0); + if (!activeDedupKeys.Contains(key)) + { + openKeys.Add(key); + } + } + } + + foreach (string key in openKeys) + { + await CommandAsync( + connection, + transaction, + "UPDATE alert_notification_state SET resolved_at = $now WHERE dedup_key = $key;", + [("$now", Format(now)), ("$key", key)], + cancellationToken); + } + + await transaction.CommitAsync(cancellationToken); + } + + private static async Task ReadAlertMuteAsync( + SqliteConnection connection, + SqliteTransaction transaction, + string id, + CancellationToken cancellationToken) + { + await using SqliteCommand command = connection.CreateCommand(); + command.Transaction = transaction; + command.CommandText = "SELECT * FROM alert_mutes WHERE id = $id;"; + command.Parameters.AddWithValue("$id", id); + await using SqliteDataReader reader = await command.ExecuteReaderAsync(cancellationToken); + return await reader.ReadAsync(cancellationToken) ? MapAlertMute(reader) : null; + } + + private static AlertMuteRecord MapAlertMute(SqliteDataReader reader) + { + int colOrd = reader.GetOrdinal("collector_id"); + int unmutedAtOrd = reader.GetOrdinal("unmuted_at"); + int unmutedByOrd = reader.GetOrdinal("unmuted_by_name"); + return new AlertMuteRecord( + reader.GetString(reader.GetOrdinal("id")), + reader.GetString(reader.GetOrdinal("condition_id")), + reader.IsDBNull(colOrd) ? null : reader.GetString(colOrd), + reader.GetString(reader.GetOrdinal("reason")), + reader.GetString(reader.GetOrdinal("muted_by_object_id")), + reader.GetString(reader.GetOrdinal("muted_by_name")), + Parse(reader.GetString(reader.GetOrdinal("muted_at"))), + Parse(reader.GetString(reader.GetOrdinal("expires_at"))), + reader.IsDBNull(unmutedAtOrd) ? null : Parse(reader.GetString(unmutedAtOrd)), + reader.IsDBNull(unmutedByOrd) ? null : reader.GetString(unmutedByOrd)); + } +} diff --git a/src/Bower.Management.Api/ManagementStore.Home.cs b/src/Bower.Management.Api/ManagementStore.Home.cs index ffc3eaa6..c228773f 100644 --- a/src/Bower.Management.Api/ManagementStore.Home.cs +++ b/src/Bower.Management.Api/ManagementStore.Home.cs @@ -195,7 +195,31 @@ public async Task HomeAsync(DateTimeOffset now, CancellationToken ca } } - return HomeStatus.Evaluate(collectors, latest, verified, counts, reporting, since, now); + HomeRecord home = HomeStatus.Evaluate(collectors, latest, verified, counts, reporting, since, now); + List activeMutes = await ListActiveMutesAsync(now, cancellationToken); + if (activeMutes.Count == 0 || home.Attention.Count == 0) + { + return home; + } + + HomeAttention[] annotated = home.Attention + .Select(item => + { + AlertMuteRecord? mute = activeMutes.FirstOrDefault(m => + string.Equals(m.ConditionId, item.Id, StringComparison.Ordinal) + && m.CollectorId is null); + return mute is null + ? item + : item with + { + Muted = true, + MuteId = mute.Id, + MutedUntil = mute.ExpiresAt, + MuteReason = mute.Reason + }; + }) + .ToArray(); + return home with { Attention = annotated }; } private static bool ValidRedactions(RedactionReport? report) => diff --git a/src/Bower.Management.Api/ManagementStore.cs b/src/Bower.Management.Api/ManagementStore.cs index efbdd5a0..51be3533 100644 --- a/src/Bower.Management.Api/ManagementStore.cs +++ b/src/Bower.Management.Api/ManagementStore.cs @@ -145,6 +145,7 @@ await AddColumnIfMissingAsync( await InitializeOfflineSitesAsync(connection, cancellationToken); await InitializePipelinesAsync(connection, cancellationToken); await InitializePackInstallsAsync(connection, cancellationToken); + await InitializeAlertsAsync(connection, cancellationToken); } public async Task RegisterAsync( diff --git a/tests/Bower.UnitTests/AlertNotificationTests.cs b/tests/Bower.UnitTests/AlertNotificationTests.cs new file mode 100644 index 00000000..a12b4df4 --- /dev/null +++ b/tests/Bower.UnitTests/AlertNotificationTests.cs @@ -0,0 +1,223 @@ +using System.Net; +using System.Net.Http.Json; +using System.Security.Claims; +using System.Text.Encodings.Web; +using Bower.Management.Api; +using Bower.Management.Api.Jobs; +using Microsoft.AspNetCore.Authentication; +using Microsoft.AspNetCore.Builder; +using Microsoft.AspNetCore.Hosting; +using Microsoft.AspNetCore.TestHost; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Logging; +using Microsoft.Extensions.Options; +using Xunit; + +namespace Bower.UnitTests; + +public sealed class AlertNotificationTests +{ + [Fact] + public async Task Notifications_Deduplicate_RespectAuditedMutes_AndRecoverWhenCleared() + { + CancellationToken ct = TestContext.Current.CancellationToken; + using SqliteTemporaryDirectory temp = new(); + MutableClock clock = new(new DateTimeOffset(2026, 11, 22, 0, 0, 0, TimeSpan.Zero)); + RecordingChannel channel = new(); + + await using WebApplication app = await StartManagementAsync(temp.Path, clock, channel, ct); + using HttpClient client = app.GetTestClient(); + + // 1. Alert catalogue covers every health condition and channel status never leaks secrets. + using HttpRequestMessage catReq = Request(HttpMethod.Get, "/api/alerts/catalogue", "v1", "Viewer", BowerRoles.Viewer); + HttpResponseMessage catResp = await client.SendAsync(catReq, ct); + Assert.Equal(HttpStatusCode.OK, catResp.StatusCode); + IReadOnlyList catalogue = + (await catResp.Content.ReadFromJsonAsync(ManagementJsonContext.Default.IReadOnlyListAlertCatalogueEntry, ct))!; + Assert.Contains(catalogue, e => e.ConditionId == "offline"); + Assert.Contains(catalogue, e => e.ConditionId == "queue-full"); + Assert.Contains(catalogue, e => e.ConditionId == "job-failed"); + + // Register & approve an offline collector (last seen > 15m ago once clock advances). + using (HttpRequestMessage reg = Request(HttpMethod.Post, "/api/collectors/register", "sp-1", "col-1", BowerRoles.Collector)) + { + reg.Content = JsonContent.Create( + new CollectorRegistration("col-1", "host-1", "prod", "1.0.1", "cfg", "pol", [], []), + ManagementJsonContext.Default.CollectorRegistration); + Assert.Equal(HttpStatusCode.Accepted, (await client.SendAsync(reg, ct)).StatusCode); + } + + using (HttpRequestMessage appr = Request(HttpMethod.Post, "/api/approvals/col-1/approve", "adm-1", "Admin", BowerRoles.Administrator)) + { + appr.Content = JsonContent.Create(new ApprovalRequest("Approved"), ManagementJsonContext.Default.ApprovalRequest); + Assert.Equal(HttpStatusCode.OK, (await client.SendAsync(appr, ct)).StatusCode); + } + + // Advance 20 minutes -> collector is offline (red alert) + not-proven (amber). + clock.Advance(TimeSpan.FromMinutes(20)); + + AlertNotificationJob job = app.Services.GetRequiredService(); + + // First run sends notifications for active alerts. + int firstSent = await job.RunAsync(ct); + Assert.True(firstSent >= 1); + Assert.Contains(channel.Sent, m => m.ConditionId == "offline" && m.ConsoleAlertsUrl == "https://console.example/alerts"); + + // Second run 5 minutes later -> deduplicated (0 sent). + clock.Advance(TimeSpan.FromMinutes(5)); + int secondSent = await job.RunAsync(ct); + Assert.Equal(0, secondSent); + + // Viewer cannot mute (403). + using (HttpRequestMessage viewerMute = Request(HttpMethod.Post, "/api/alerts/mute", "v1", "Viewer", BowerRoles.Viewer)) + { + viewerMute.Content = JsonContent.Create( + new AlertMuteRequest("offline", null, 240, "Viewer attempt"), + ManagementJsonContext.Default.AlertMuteRequest); + Assert.Equal(HttpStatusCode.Forbidden, (await client.SendAsync(viewerMute, ct)).StatusCode); + } + + // Operator mutes "offline" -> audited + reflected in /api/home + suppresses notification after dedup window. + using HttpRequestMessage muteReq = Request(HttpMethod.Post, "/api/alerts/mute", "op-1", "Alex Operator", BowerRoles.Operator); + muteReq.Content = JsonContent.Create( + new AlertMuteRequest("offline", null, 240, "Planned patching window"), + ManagementJsonContext.Default.AlertMuteRequest); + HttpResponseMessage muteResp = await client.SendAsync(muteReq, ct); + Assert.Equal(HttpStatusCode.Created, muteResp.StatusCode); + AlertMuteRecord mute = (await muteResp.Content.ReadFromJsonAsync(ManagementJsonContext.Default.AlertMuteRecord, ct))!; + + using (HttpRequestMessage homeReq = Request(HttpMethod.Get, "/api/home", "v1", "Viewer", BowerRoles.Viewer)) + { + HomeRecord home = (await (await client.SendAsync(homeReq, ct)) + .Content.ReadFromJsonAsync(ManagementJsonContext.Default.HomeRecord, ct))!; + HomeAttention offlineAttention = Assert.Single(home.Attention, a => a.Id == "offline"); + Assert.True(offlineAttention.Muted); + Assert.Equal(mute.Id, offlineAttention.MuteId); + Assert.Equal("Planned patching window", offlineAttention.MuteReason); + } + + // Advance past dedup window (70m) while still within 240m mute -> "offline" MUST NOT re-send! + int offlineCountBefore = channel.Sent.Count(m => m.ConditionId == "offline"); + clock.Advance(TimeSpan.FromMinutes(70)); + await job.RunAsync(ct); + Assert.Equal(offlineCountBefore, channel.Sent.Count(m => m.ConditionId == "offline")); + + // Unmute -> audited, and next run sends "offline" again since dedup window elapsed. + using (HttpRequestMessage unmuteReq = Request(HttpMethod.Post, $"/api/alerts/mutes/{mute.Id}/unmute", "op-1", "Alex Operator", BowerRoles.Operator)) + { + Assert.Equal(HttpStatusCode.OK, (await client.SendAsync(unmuteReq, ct)).StatusCode); + } + + await job.RunAsync(ct); + Assert.Equal(offlineCountBefore + 1, channel.Sent.Count(m => m.ConditionId == "offline")); + + // Verify audit trail contains alert.muted, alert.unmuted, and alert.notification-sent. + using HttpRequestMessage auditReq = Request(HttpMethod.Get, "/api/audit", "v1", "Viewer", BowerRoles.Viewer); + List audits = (await (await client.SendAsync(auditReq, ct)) + .Content.ReadFromJsonAsync(ManagementJsonContext.Default.ListAuditRecord, ct))!; + Assert.Contains(audits, a => a.Action == "alert.muted" && a.TargetId == "offline"); + Assert.Contains(audits, a => a.Action == "alert.unmuted" && a.TargetId == "offline"); + Assert.Contains(audits, a => a.Action == "alert.notification-sent" && a.TargetId == "offline:red"); + } + + private sealed class RecordingChannel : IAlertNotificationChannel + { + public List Sent { get; } = []; + public string Name => "recording"; + public bool IsConfigured => true; + + public Task SendAsync(AlertNotificationMessage message, CancellationToken cancellationToken) + { + Sent.Add(message); + return Task.CompletedTask; + } + } + + private sealed class MutableClock(DateTimeOffset initial) : TimeProvider + { + private DateTimeOffset _now = initial; + public void Advance(TimeSpan delta) => _now += delta; + public override DateTimeOffset GetUtcNow() => _now; + } + + private static async Task StartManagementAsync( + string root, + TimeProvider clock, + IAlertNotificationChannel testChannel, + CancellationToken cancellationToken) + { + WebApplication app = ManagementApplication.Build( + [ + "--Bower:Entra:TenantId=tenant-test", + "--Bower:Entra:Audience=api://bower-test", + $"--BOWER_MANAGEMENT_DB_PATH={Path.Combine(root, "management.db")}", + "--BOWER_ALERT_CONSOLE_URL=https://console.example", + "--BOWER_ALERT_DEDUP_MINUTES=60" + ], + builder => + { + builder.WebHost.UseTestServer(); + builder.Services.AddSingleton(clock); + builder.Services.AddSingleton(testChannel); + builder.Services.AddAuthentication(options => + { + options.DefaultAuthenticateScheme = "AlertTest"; + options.DefaultChallengeScheme = "AlertTest"; + options.DefaultScheme = "AlertTest"; + }).AddScheme("AlertTest", _ => { }); + }); + await ManagementApplication.InitializeAsync(app, cancellationToken); + await app.StartAsync(cancellationToken); + return app; + } + + private sealed class AlertTestAuthHandler( + IOptionsMonitor options, + ILoggerFactory logger, + UrlEncoder encoder) + : AuthenticationHandler(options, logger, encoder) + { + protected override Task HandleAuthenticateAsync() + { + string? oid = Request.Headers["X-Test-Oid"].FirstOrDefault(); + if (string.IsNullOrEmpty(oid)) + { + return Task.FromResult(AuthenticateResult.NoResult()); + } + + List claims = + [ + new("oid", oid), + new("name", Request.Headers["X-Test-Name"].FirstOrDefault() ?? oid) + ]; + foreach (string? role in Request.Headers["X-Test-Role"]) + { + if (!string.IsNullOrWhiteSpace(role)) + { + claims.Add(new("roles", role)); + } + } + + ClaimsPrincipal principal = new(new ClaimsIdentity(claims, Scheme.Name, "name", "roles")); + return Task.FromResult(AuthenticateResult.Success(new AuthenticationTicket(principal, Scheme.Name))); + } + } + + private static HttpRequestMessage Request( + HttpMethod method, + string path, + string objectId, + string name, + params string[] roles) + { + HttpRequestMessage message = new(method, path); + message.Headers.Add("X-Test-Oid", objectId); + message.Headers.Add("X-Test-Name", name); + foreach (string role in roles) + { + message.Headers.Add("X-Test-Role", role); + } + + return message; + } +} diff --git a/tests/Bower.UnitTests/ManagementApiTests.cs b/tests/Bower.UnitTests/ManagementApiTests.cs index dc9d9a04..f9be5941 100644 --- a/tests/Bower.UnitTests/ManagementApiTests.cs +++ b/tests/Bower.UnitTests/ManagementApiTests.cs @@ -45,7 +45,7 @@ public async Task Jobs_ListsRecurringManagementJobsForViewers() BackgroundJobStatus[]? jobs = await Client(app, BowerRoles.Viewer) .GetFromJsonAsync("/api/jobs", cancellationToken); - Assert.Equal(["collector-inactivity", "collector-staleness"], jobs!.Select(job => job.Id)); + Assert.Equal(["alert-notifications", "collector-inactivity", "collector-staleness"], jobs!.Select(job => job.Id)); Assert.Equal("*/5 * * * *", jobs!.Single(job => job.Id == "collector-staleness").Schedule); } diff --git a/ui/Bower.Management.Web/src/pages/AlertsMute.test.tsx b/ui/Bower.Management.Web/src/pages/AlertsMute.test.tsx new file mode 100644 index 00000000..072e24b7 --- /dev/null +++ b/ui/Bower.Management.Web/src/pages/AlertsMute.test.tsx @@ -0,0 +1,116 @@ +import { cleanup, fireEvent, render, screen, waitFor } from "@testing-library/react"; +import { MemoryRouter } from "react-router-dom"; +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; +import { App } from "../App"; +import { AuthenticationProvider } from "../auth"; +import type { Home } from "../types"; + +describe("Alerts page mute controls", () => { + beforeEach(() => { + localStorage.setItem("bower-theme", "light"); + }); + + afterEach(() => { + cleanup(); + vi.unstubAllGlobals(); + localStorage.clear(); + }); + + it("allows an Operator to mute and unmute an active alert with an audited reason", async () => { + let muted = false; + 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 new Response( + JSON.stringify({ + objectId: "op-1", + displayName: "Alex Operator", + roles: ["Bower.Operator"], + developmentAuthentication: true + }), + { status: 200 } + ); + } + if (path === "/api/alerts/mute" && init?.method === "POST") { + muted = true; + return new Response(JSON.stringify({ id: "0123456789abcdef0123456789abcdef" }), { status: 201 }); + } + if (path === "/api/alerts/mutes/0123456789abcdef0123456789abcdef/unmute" && init?.method === "POST") { + muted = false; + return new Response(JSON.stringify({ id: "0123456789abcdef0123456789abcdef" }), { status: 200 }); + } + if (path === "/api/home") { + const home: Home = { + generatedAt: "2026-11-22T00:00:00Z", + state: "red", + flow: { + state: "red", + summary: "No. Your collector is not sending events right now.", + sending: 0, + enrolled: 1, + lastAcceptedAt: null, + proof: { + state: "verified", + message: "Proven: Bower found a test event in Microsoft Sentinel.", + at: "2026-11-22T00:00:00Z", + fix: null + } + }, + protection: { + since: "2026-11-16T00:00:00Z", + summary: "Bower removed sensitive details.", + byType: [], + collectorsReporting: 1, + collectorsNotReporting: 0 + }, + attention: [ + { + id: "offline", + state: "red", + message: "1 collector has not checked in for more than 15 minutes.", + fix: { action: "Check that the machine is switched on and can reach Bower.", page: "/collectors" }, + count: 1, + muted, + muteId: muted ? "0123456789abcdef0123456789abcdef" : null, + mutedUntil: muted ? "2026-11-22T04:00:00Z" : null, + muteReason: muted ? "Planned host maintenance" : null + } + ], + groups: [], + groupsTotal: 0 + }; + return new Response(JSON.stringify(home), { status: 200 }); + } + return new Response("Not found", { status: 404 }); + }); + vi.stubGlobal("fetch", fetchMock); + + render( + + + + + + ); + + await waitFor(() => { + expect(screen.getByRole("button", { name: "Mute alert" })).toBeTruthy(); + }); + + fireEvent.click(screen.getByRole("button", { name: "Mute alert" })); + fireEvent.change(screen.getByLabelText("Reason for muting (audited)"), { + target: { value: "Planned host maintenance" } + }); + fireEvent.click(screen.getByRole("button", { name: "Confirm mute" })); + + await waitFor(() => { + expect(screen.getByText(/Mute reason: Planned host maintenance/i)).toBeTruthy(); + expect(screen.getByRole("button", { name: "Unmute notifications" })).toBeTruthy(); + }); + + fireEvent.click(screen.getByRole("button", { name: "Unmute notifications" })); + await waitFor(() => { + expect(screen.getByRole("button", { name: "Mute alert" })).toBeTruthy(); + }); + }); +}); diff --git a/ui/Bower.Management.Web/src/pages/HomePage.tsx b/ui/Bower.Management.Web/src/pages/HomePage.tsx index e54343a9..a207e49b 100644 --- a/ui/Bower.Management.Web/src/pages/HomePage.tsx +++ b/ui/Bower.Management.Web/src/pages/HomePage.tsx @@ -1,12 +1,13 @@ -import { CheckCircle2, CircleDashed, Clock3, ShieldCheck, TriangleAlert } from "lucide-react"; -import { useEffect } from "react"; +import { BellOff, CheckCircle2, CircleDashed, Clock3, ShieldCheck, TriangleAlert } from "lucide-react"; +import { useEffect, useState } from "react"; import { Link } from "react-router-dom"; +import { useApi } from "../api"; import { GlossaryText } from "../components/glossary"; import { TrafficLight } from "../components/guided"; import { EmptyState, Page, ResourceState } from "../components/ui"; import { useResource } from "../hooks/useResource"; import { formatDate } from "../lib/format"; -import type { Home, HomeFix, HomeSentinelProof } from "../types"; +import type { Access, Home, HomeAttention, HomeFix, HomeSentinelProof } from "../types"; /** The home view refreshes in place, like the setup wizard's progress. */ const refreshMilliseconds = 60_000; @@ -25,13 +26,72 @@ const pageNames: Record = { * attention. Every state and sentence is computed by the API from real management state. */ export function HomePage({ view = "home" }: { view?: "home" | "alerts" | "reports" }) { + const api = useApi(); const { data, loading, error, refreshError, revalidate } = useResource("/api/home"); + const access = useResource("/api/access/me"); + const [mutingId, setMutingId] = useState(null); + const [muteDuration, setMuteDuration] = useState(240); + const [muteReason, setMuteReason] = useState(""); + const [muteBusy, setMuteBusy] = useState(false); + const [muteError, setMuteError] = useState(null); + + const canOperate = + access.data?.roles.some( + (role) => + role === "Bower.Operator" || + role === "Bower.Approver" || + role === "Bower.Administrator" + ) ?? false; useEffect(() => { const timer = window.setInterval(() => void revalidate(), refreshMilliseconds); return () => window.clearInterval(timer); }, [revalidate]); + async function submitMute(conditionId: string) { + if (!muteReason.trim()) { + setMuteError("Enter a reason before muting this alert."); + return; + } + setMuteBusy(true); + setMuteError(null); + try { + await api("/api/alerts/mute", { + method: "POST", + body: JSON.stringify({ + conditionId, + durationMinutes: muteDuration, + reason: muteReason.trim() + }) + }); + setMutingId(null); + setMuteReason(""); + await revalidate(); + } catch (err) { + setMuteError(err instanceof Error ? err.message : "Could not mute alert."); + } finally { + setMuteBusy(false); + } + } + + async function unmute(item: HomeAttention) { + if (!item.muteId) { + return; + } + setMuteBusy(true); + setMuteError(null); + try { + await api(`/api/alerts/mutes/${encodeURIComponent(item.muteId)}/unmute`, { + method: "POST" + }); + await revalidate(); + } catch (err) { + setMuteError(err instanceof Error ? err.message : "Could not unmute alert."); + } finally { + setMuteBusy(false); + } + } + return ( What needs my attention? + {muteError && ( +
+ {muteError} +
+ )} {home.attention.length ? (
    {home.attention.map((item) => ( @@ -106,8 +171,89 @@ export function HomePage({ view = "home" }: { view?: "home" | "alerts" | "report

    + {item.muted && ( + <> + {" "} + + + + )}

    + {item.muted && item.muteReason && ( +

    Mute reason: {item.muteReason}

    + )} + {view === "alerts" && canOperate && ( +
    + {item.muted && item.muteId ? ( + + ) : mutingId === item.id ? ( +
    { + event.preventDefault(); + void submitMute(item.id); + }} + > + + + + setMuteReason(event.target.value)} + /> +
    + + +
    +
    + ) : ( + + )} +
    + )}
    ))} diff --git a/ui/Bower.Management.Web/src/types.ts b/ui/Bower.Management.Web/src/types.ts index e28e26a9..fececf5f 100644 --- a/ui/Bower.Management.Web/src/types.ts +++ b/ui/Bower.Management.Web/src/types.ts @@ -442,6 +442,10 @@ export interface HomeAttention { message: string; fix: HomeFix; count: number; + muted?: boolean; + muteId?: string | null; + mutedUntil?: string | null; + muteReason?: string | null; } /** One collector group (environment); the worst condition gives the state and the reason. */