From c6dad97759ebf28d904d8f366592f3c9af5b65d1 Mon Sep 17 00:00:00 2001 From: Justin Middler Date: Sun, 22 Nov 2026 08:58:14 +1100 Subject: [PATCH] feat(console): add signed pack gallery and four-eyes group install (#102) --- docs/security/threat-model.md | 9 + .../Bower.Management.Api.csproj | 1 + .../ManagementApplication.cs | 3 + src/Bower.Management.Api/ManagementJson.cs | 5 + .../ManagementStore.PackInstalls.cs | 358 +++++++++++++++++ src/Bower.Management.Api/ManagementStore.cs | 1 + .../PackGalleryEndpoints.cs | 201 ++++++++++ src/Bower.Management.Api/PackGalleryModels.cs | 110 ++++++ .../PackGalleryService.cs | 296 ++++++++++++++ src/Bower.Management.Api/packages.lock.json | 19 + tests/Bower.UnitTests/PackGalleryApiTests.cs | 266 +++++++++++++ tests/Bower.UnitTests/packages.lock.json | 1 + ui/Bower.Management.Web/src/App.tsx | 4 + .../src/pages/ApprovalsPage.tsx | 3 + .../src/pages/PackInstallApprovals.tsx | 169 ++++++++ .../src/pages/PacksPage.test.tsx | 200 ++++++++++ .../src/pages/PacksPage.tsx | 368 ++++++++++++++++++ ui/Bower.Management.Web/src/types.ts | 94 +++++ 18 files changed, 2108 insertions(+) create mode 100644 src/Bower.Management.Api/ManagementStore.PackInstalls.cs create mode 100644 src/Bower.Management.Api/PackGalleryEndpoints.cs create mode 100644 src/Bower.Management.Api/PackGalleryModels.cs create mode 100644 src/Bower.Management.Api/PackGalleryService.cs create mode 100644 tests/Bower.UnitTests/PackGalleryApiTests.cs create mode 100644 ui/Bower.Management.Web/src/pages/PackInstallApprovals.tsx create mode 100644 ui/Bower.Management.Web/src/pages/PacksPage.test.tsx create mode 100644 ui/Bower.Management.Web/src/pages/PacksPage.tsx diff --git a/docs/security/threat-model.md b/docs/security/threat-model.md index 3b90b197..a8a68619 100644 --- a/docs/security/threat-model.md +++ b/docs/security/threat-model.md @@ -257,6 +257,15 @@ evidence. the password comes from a file that is never logged, hashed or reported. An inspecting proxy can read heartbeat metadata and the bearer token in transit, so trust it as you would the management host. It cannot forge commands. +- Console pack gallery (`GET /api/packs`, `POST /api/packs/install-requests`): management + loads `.bowerpack` archives only from the server-configured `BOWER_PACK_GALLERY_DIR` + and verifies every manifest signature and file digest against `BOWER_PACK_TRUSTED_KEYS` + before listing, before accepting an install submission, and again before approval. + Archives without a trusted key or with modified contents are refused with a plain reason + and cannot be submitted or approved; sample results expose pass/fail decisions only + (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. - 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/Bower.Management.Api.csproj b/src/Bower.Management.Api/Bower.Management.Api.csproj index 609b912c..90e02f12 100644 --- a/src/Bower.Management.Api/Bower.Management.Api.csproj +++ b/src/Bower.Management.Api/Bower.Management.Api.csproj @@ -21,6 +21,7 @@ + diff --git a/src/Bower.Management.Api/ManagementApplication.cs b/src/Bower.Management.Api/ManagementApplication.cs index 8952c336..5b5f176e 100644 --- a/src/Bower.Management.Api/ManagementApplication.cs +++ b/src/Bower.Management.Api/ManagementApplication.cs @@ -141,6 +141,8 @@ public static WebApplication Build( builder.Configuration[SourceSetupSigner.KeyFileSetting])); // Optional: without trusted keys offline site bundle imports are refused (503). builder.Services.AddSingleton(OfflineSiteTrustKeys.FromConfiguration(builder.Configuration)); + // Optional: signed pack gallery directory + trusted signing keys (fail closed when keys absent). + builder.Services.AddSingleton(PackGalleryService.FromConfiguration(builder.Configuration)); string[] allowedOrigins = builder.Configuration .GetSection("Bower:AllowedOrigins") @@ -346,6 +348,7 @@ await store.FleetAsync(clock.GetUtcNow(), cancellationToken)) OfflineSiteEndpoints.Map(api); PipelineLiveEndpoints.Map(api); + PackGalleryEndpoints.Map(api); api.MapGet( "/collectors", diff --git a/src/Bower.Management.Api/ManagementJson.cs b/src/Bower.Management.Api/ManagementJson.cs index 87c3735d..8015cc85 100644 --- a/src/Bower.Management.Api/ManagementJson.cs +++ b/src/Bower.Management.Api/ManagementJson.cs @@ -111,6 +111,11 @@ public sealed record PipelineValidationResponse( [JsonSerializable(typeof(IReadOnlyList))] [JsonSerializable(typeof(PipelineTapRequest))] [JsonSerializable(typeof(PipelineTapResponse))] +[JsonSerializable(typeof(PackGalleryResponse))] +[JsonSerializable(typeof(PackInstallSubmission))] +[JsonSerializable(typeof(PackPopulationDiff))] +[JsonSerializable(typeof(PackInstallRequestRecord))] +[JsonSerializable(typeof(List))] [JsonSerializable(typeof(Dictionary))] [JsonSerializable(typeof(Microsoft.AspNetCore.Mvc.ProblemDetails))] [JsonSerializable(typeof(HttpValidationProblemDetails))] diff --git a/src/Bower.Management.Api/ManagementStore.PackInstalls.cs b/src/Bower.Management.Api/ManagementStore.PackInstalls.cs new file mode 100644 index 00000000..ce5fc945 --- /dev/null +++ b/src/Bower.Management.Api/ManagementStore.PackInstalls.cs @@ -0,0 +1,358 @@ +using System.Globalization; +using System.Security.Cryptography; +using System.Text.Json; +using Microsoft.Data.Sqlite; + +namespace Bower.Management.Api; + +/// A pack installation request that cannot move as asked (four-eyes, state, or missing pack). HTTP 409. +public sealed class PackInstallConflictException(string message) : InvalidOperationException(message); + +/// +/// Four-eyes pack installation requests: an operator submits a verified pack install for a +/// collector group (environment) or single collector, and a different approver decides it. +/// Approval applies desired_policy_hash to every eligible collector and writes approval +/// and audit rows in the same transaction. +/// +public sealed partial class ManagementStore +{ + public const int MaximumPendingPackInstalls = 32; + private const string PackInstallTargetType = "pack-install-request"; + + private static Task InitializePackInstallsAsync(SqliteConnection connection, CancellationToken cancellationToken) => + ExecuteAsync( + connection, + """ + CREATE TABLE IF NOT EXISTS pack_install_requests ( + id TEXT PRIMARY KEY, + pack_id TEXT NOT NULL, + pack_version TEXT NOT NULL, + pack_name TEXT NOT NULL, + pack_hash TEXT NOT NULL, + signed_by_key_id TEXT NOT NULL, + target_environment TEXT NULL, + target_collector_id TEXT NULL, + status TEXT NOT NULL, + diff_json TEXT NOT NULL, + reason TEXT NOT NULL, + requested_by_object_id TEXT NOT NULL, + requested_by_name TEXT NOT NULL, + requested_at TEXT NOT NULL, + reviewer_object_id TEXT NULL, + reviewer_name TEXT NULL, + reviewed_at TEXT NULL, + review_reason TEXT NULL + ); + CREATE INDEX IF NOT EXISTS pack_install_requests_status + ON pack_install_requests(status, requested_at); + """, + cancellationToken); + + internal async Task SubmitPackInstallAsync( + string packId, + string packVersion, + string packName, + string packHash, + string signedByKeyId, + string? targetEnvironment, + string? targetCollectorId, + PackPopulationDiff diff, + string? reason, + string actorObjectId, + string actorName, + DateTimeOffset now, + CancellationToken cancellationToken) + { + string trimmed = RequireText(reason, nameof(reason)); + string id = Convert.ToHexStringLower(RandomNumberGenerator.GetBytes(16)); + await using SqliteConnection connection = await OpenAsync(cancellationToken); + await using SqliteTransaction transaction = connection.BeginTransaction(deferred: false); + + string? pendingCount = await ScalarAsync( + connection, + transaction, + "SELECT COUNT(*) FROM pack_install_requests WHERE status = $status;", + ("$status", PackInstallRequestStatus.PendingReview), + cancellationToken); + if (int.Parse(pendingCount ?? "0", CultureInfo.InvariantCulture) >= MaximumPendingPackInstalls) + { + throw new PackInstallConflictException( + $"There are already {MaximumPendingPackInstalls} pack installation requests waiting for approval."); + } + + await CommandAsync( + connection, + transaction, + """ + INSERT INTO pack_install_requests ( + id, pack_id, pack_version, pack_name, pack_hash, signed_by_key_id, + target_environment, target_collector_id, status, diff_json, reason, + requested_by_object_id, requested_by_name, requested_at) + VALUES ( + $id, $pack_id, $pack_version, $pack_name, $pack_hash, $key_id, + $env, $collector, $status, $diff, $reason, + $actor, $actor_name, $now); + """, + [ + ("$id", id), + ("$pack_id", packId), + ("$pack_version", packVersion), + ("$pack_name", packName), + ("$pack_hash", packHash), + ("$key_id", signedByKeyId), + ("$env", targetEnvironment), + ("$collector", targetCollectorId), + ("$status", PackInstallRequestStatus.PendingReview), + ("$diff", JsonSerializer.Serialize(diff, ManagementJsonContext.Default.PackPopulationDiff)), + ("$reason", trimmed), + ("$actor", actorObjectId), + ("$actor_name", actorName), + ("$now", Format(now)) + ], + cancellationToken); + + await InsertAuditAsync( + connection, + transaction, + "pack.install-requested", + id, + actorObjectId, + actorName, + now, + cancellationToken, + PackInstallTargetType); + + await transaction.CommitAsync(cancellationToken); + return (await GetPackInstallAsync(id, cancellationToken))!; + } + + internal async Task ReviewPackInstallAsync( + string id, + bool approve, + Func? verifyBeforeApprove, + string? reason, + string actorObjectId, + string actorName, + DateTimeOffset now, + CancellationToken cancellationToken) + { + string trimmed = RequireText(reason, nameof(reason)); + await using SqliteConnection connection = await OpenAsync(cancellationToken); + await using SqliteTransaction transaction = connection.BeginTransaction(deferred: false); + + PackInstallRequestRecord? existing = await ReadPackInstallAsync(connection, transaction, id, cancellationToken); + if (existing is null) + { + return null; + } + + if (!string.Equals(existing.Status, PackInstallRequestStatus.PendingReview, StringComparison.Ordinal)) + { + throw new PackInstallConflictException("This pack installation request has already been decided."); + } + + if (string.Equals(existing.RequestedByObjectId, actorObjectId, StringComparison.Ordinal)) + { + throw new PackInstallConflictException( + "You requested this pack installation, so a different approver must decide it."); + } + + if (approve && verifyBeforeApprove?.Invoke(existing) is { } refusal) + { + throw new PackInstallConflictException(refusal); + } + + string nextStatus = approve ? PackInstallRequestStatus.Approved : PackInstallRequestStatus.Rejected; + await CommandAsync( + connection, + transaction, + """ + UPDATE pack_install_requests + SET status = $status, + reviewer_object_id = $reviewer, + reviewer_name = $reviewer_name, + reviewed_at = $reviewed_at, + review_reason = $review_reason + WHERE id = $id; + """, + [ + ("$status", nextStatus), + ("$reviewer", actorObjectId), + ("$reviewer_name", actorName), + ("$reviewed_at", Format(now)), + ("$review_reason", trimmed), + ("$id", id) + ], + cancellationToken); + + if (approve) + { + List targetCollectorIds = await ResolveEligiblePackTargetsAsync( + connection, transaction, existing.TargetEnvironment, existing.TargetCollectorId, cancellationToken); + if (targetCollectorIds.Count == 0) + { + throw new PackInstallConflictException( + "No approved or active collectors match the requested target."); + } + + foreach (string collectorId in targetCollectorIds) + { + await CommandAsync( + connection, + transaction, + "UPDATE collectors SET desired_policy_hash = $hash WHERE id = $id;", + [("$hash", existing.PackHash), ("$id", collectorId)], + cancellationToken); + + await CommandAsync( + connection, + transaction, + """ + INSERT INTO approvals ( + id, collector_id, action, reason, actor_object_id, actor_name, occurred_at) + VALUES ($id, $collector, 'pack-installed', $reason, $actor, $name, $occurred); + """, + [ + ("$id", Guid.NewGuid().ToString("N", CultureInfo.InvariantCulture)), + ("$collector", collectorId), + ("$reason", $"Installed {existing.PackId} v{existing.PackVersion}: {trimmed}"), + ("$actor", actorObjectId), + ("$name", actorName), + ("$occurred", Format(now)) + ], + cancellationToken); + + await InsertAuditAsync( + connection, + transaction, + "collector.desired-policy-updated", + collectorId, + actorObjectId, + actorName, + now, + cancellationToken, + initiatedByObjectId: existing.RequestedByObjectId, + initiatedByName: existing.RequestedByName); + } + } + + await InsertAuditAsync( + connection, + transaction, + approve ? "pack.install-approved" : "pack.install-rejected", + id, + actorObjectId, + actorName, + now, + cancellationToken, + PackInstallTargetType, + initiatedByObjectId: existing.RequestedByObjectId, + initiatedByName: existing.RequestedByName); + + await transaction.CommitAsync(cancellationToken); + return await GetPackInstallAsync(id, cancellationToken); + } + + internal async Task> ListPackInstallsAsync(CancellationToken cancellationToken) + { + await using SqliteConnection connection = await OpenAsync(cancellationToken); + await using SqliteCommand command = connection.CreateCommand(); + command.CommandText = "SELECT * FROM pack_install_requests ORDER BY requested_at DESC LIMIT 200;"; + List items = []; + await using SqliteDataReader reader = await command.ExecuteReaderAsync(cancellationToken); + while (await reader.ReadAsync(cancellationToken)) + { + items.Add(MapPackInstall(reader)); + } + + return items; + } + + internal async Task GetPackInstallAsync(string id, CancellationToken cancellationToken) + { + await using SqliteConnection connection = await OpenAsync(cancellationToken); + return await ReadPackInstallAsync(connection, null, id, cancellationToken); + } + + private static async Task ReadPackInstallAsync( + SqliteConnection connection, + SqliteTransaction? transaction, + string id, + CancellationToken cancellationToken) + { + await using SqliteCommand command = connection.CreateCommand(); + command.Transaction = transaction; + command.CommandText = "SELECT * FROM pack_install_requests WHERE id = $id;"; + command.Parameters.AddWithValue("$id", id); + await using SqliteDataReader reader = await command.ExecuteReaderAsync(cancellationToken); + return await reader.ReadAsync(cancellationToken) ? MapPackInstall(reader) : null; + } + + private static async Task> ResolveEligiblePackTargetsAsync( + SqliteConnection connection, + SqliteTransaction transaction, + string? targetEnvironment, + string? targetCollectorId, + CancellationToken cancellationToken) + { + await using SqliteCommand command = connection.CreateCommand(); + command.Transaction = transaction; + if (!string.IsNullOrWhiteSpace(targetCollectorId)) + { + command.CommandText = """ + SELECT id FROM collectors + WHERE id = $id AND status IN ('Approved', 'Active') + ORDER BY id; + """; + command.Parameters.AddWithValue("$id", targetCollectorId); + } + else + { + command.CommandText = """ + SELECT id FROM collectors + WHERE environment = $env AND status IN ('Approved', 'Active') + ORDER BY id; + """; + command.Parameters.AddWithValue("$env", targetEnvironment ?? string.Empty); + } + + List ids = []; + await using SqliteDataReader reader = await command.ExecuteReaderAsync(cancellationToken); + while (await reader.ReadAsync(cancellationToken)) + { + ids.Add(reader.GetString(0)); + } + + return ids; + } + + private static PackInstallRequestRecord MapPackInstall(SqliteDataReader reader) + { + string diffJson = reader.GetString(reader.GetOrdinal("diff_json")); + PackPopulationDiff diff = JsonSerializer.Deserialize(diffJson, ManagementJsonContext.Default.PackPopulationDiff)!; + int envOrd = reader.GetOrdinal("target_environment"); + int colOrd = reader.GetOrdinal("target_collector_id"); + int reviewerOrd = reader.GetOrdinal("reviewer_name"); + int reviewedAtOrd = reader.GetOrdinal("reviewed_at"); + int reviewReasonOrd = reader.GetOrdinal("review_reason"); + + return new PackInstallRequestRecord( + reader.GetString(reader.GetOrdinal("id")), + reader.GetString(reader.GetOrdinal("pack_id")), + reader.GetString(reader.GetOrdinal("pack_version")), + reader.GetString(reader.GetOrdinal("pack_name")), + reader.GetString(reader.GetOrdinal("pack_hash")), + reader.GetString(reader.GetOrdinal("signed_by_key_id")), + reader.IsDBNull(envOrd) ? null : reader.GetString(envOrd), + reader.IsDBNull(colOrd) ? null : reader.GetString(colOrd), + reader.GetString(reader.GetOrdinal("status")), + diff, + reader.GetString(reader.GetOrdinal("reason")), + reader.GetString(reader.GetOrdinal("requested_by_object_id")), + reader.GetString(reader.GetOrdinal("requested_by_name")), + Parse(reader.GetString(reader.GetOrdinal("requested_at"))), + reader.IsDBNull(reviewerOrd) ? null : reader.GetString(reviewerOrd), + reader.IsDBNull(reviewedAtOrd) ? null : Parse(reader.GetString(reviewedAtOrd)), + reader.IsDBNull(reviewReasonOrd) ? null : reader.GetString(reviewReasonOrd)); + } +} diff --git a/src/Bower.Management.Api/ManagementStore.cs b/src/Bower.Management.Api/ManagementStore.cs index 71ccf73f..efbdd5a0 100644 --- a/src/Bower.Management.Api/ManagementStore.cs +++ b/src/Bower.Management.Api/ManagementStore.cs @@ -144,6 +144,7 @@ await AddColumnIfMissingAsync( await InitializeSourceSetupAsync(connection, cancellationToken); await InitializeOfflineSitesAsync(connection, cancellationToken); await InitializePipelinesAsync(connection, cancellationToken); + await InitializePackInstallsAsync(connection, cancellationToken); } public async Task RegisterAsync( diff --git a/src/Bower.Management.Api/PackGalleryEndpoints.cs b/src/Bower.Management.Api/PackGalleryEndpoints.cs new file mode 100644 index 00000000..99594052 --- /dev/null +++ b/src/Bower.Management.Api/PackGalleryEndpoints.cs @@ -0,0 +1,201 @@ +using System.Security.Claims; +using Bower.Packs; +using Microsoft.AspNetCore.Mvc; + +namespace Bower.Management.Api; + +/// +/// Signed pack gallery and four-eyes pack installation requests. Every pack is signature-verified +/// server side against BOWER_PACK_TRUSTED_KEYS before listing, submission and approval; +/// collectors verify signatures again independently when loading BOWER_PACKS. +/// +internal static class PackGalleryEndpoints +{ + private const long BodyLimit = 32 * 1024; + + public static void Map(RouteGroupBuilder api) + { + api.MapGet( + "/packs", + async ( + PackGalleryService gallery, + ManagementStore store, + TimeProvider clock, + CancellationToken cancellationToken) => + { + (IReadOnlyList packs, int trustedKeyCount) = gallery.List(clock); + IReadOnlyList collectors = await store.ListAsync(null, cancellationToken); + PackTargetGroup[] groups = collectors + .Where(collector => collector.Status is CollectorStatus.Approved or CollectorStatus.Active) + .GroupBy(collector => collector.Environment, StringComparer.Ordinal) + .OrderBy(group => group.Key, StringComparer.Ordinal) + .Select(group => new PackTargetGroup( + group.Key, + group.Count(), + group.Select(collector => collector.Id).OrderBy(id => id, StringComparer.Ordinal).ToArray())) + .ToArray(); + + return Results.Ok(new PackGalleryResponse(gallery.Configured, trustedKeyCount, packs, groups)); + }) + .RequireAuthorization("View"); + + api.MapGet( + "/packs/install-requests", + async (ManagementStore store, CancellationToken cancellationToken) => + Results.Ok(await store.ListPackInstallsAsync(cancellationToken))) + .RequireAuthorization("View"); + + api.MapPost( + "/packs/install-requests", + SubmitInstallAsync) + .WithMetadata(new RequestSizeLimitAttribute(BodyLimit)) + .RequireAuthorization("Operate"); + + api.MapPost( + "/packs/install-requests/{id}/approve", + (string id, ApprovalRequest request, ClaimsPrincipal user, PackGalleryService gallery, + ManagementStore store, TimeProvider clock, CancellationToken cancellationToken) => + ReviewInstallAsync(id, true, request, user, gallery, store, clock, cancellationToken)) + .RequireAuthorization("Approve"); + + api.MapPost( + "/packs/install-requests/{id}/reject", + (string id, ApprovalRequest request, ClaimsPrincipal user, PackGalleryService gallery, + ManagementStore store, TimeProvider clock, CancellationToken cancellationToken) => + ReviewInstallAsync(id, false, request, user, gallery, store, clock, cancellationToken)) + .RequireAuthorization("Approve"); + } + + private static async Task SubmitInstallAsync( + PackInstallSubmission submission, + ClaimsPrincipal user, + PackGalleryService gallery, + ManagementStore store, + TimeProvider clock, + CancellationToken cancellationToken) + { + string packId = submission.PackId?.Trim() ?? string.Empty; + string version = submission.Version?.Trim() ?? string.Empty; + if (string.IsNullOrEmpty(packId) || string.IsNullOrEmpty(version)) + { + return Results.BadRequest(new ErrorResponse("Pack id and version are required.")); + } + + string? targetEnvironment = string.IsNullOrWhiteSpace(submission.TargetEnvironment) + ? null + : submission.TargetEnvironment.Trim(); + string? targetCollectorId = string.IsNullOrWhiteSpace(submission.TargetCollectorId) + ? null + : submission.TargetCollectorId.Trim(); + if ((targetEnvironment is null) == (targetCollectorId is null)) + { + return Results.BadRequest(new ErrorResponse( + "Choose either a collector group (environment) or a single collector.")); + } + + (LoadedPack? loaded, string? refusalReason) = gallery.ResolveTrusted(packId, version); + if (loaded is null) + { + return Results.BadRequest(new ErrorResponse( + refusalReason ?? "Pack is untrusted or could not be verified.")); + } + + IReadOnlyList allCollectors = await store.ListAsync(null, cancellationToken); + CollectorRecord[] targets = targetCollectorId is not null + ? allCollectors.Where(item => + string.Equals(item.Id, targetCollectorId, StringComparison.Ordinal) + && item.Status is CollectorStatus.Approved or CollectorStatus.Active).ToArray() + : allCollectors.Where(item => + string.Equals(item.Environment, targetEnvironment, StringComparison.Ordinal) + && item.Status is CollectorStatus.Approved or CollectorStatus.Active).ToArray(); + if (targets.Length == 0) + { + return Results.Conflict(new ErrorResponse( + targetCollectorId is not null + ? "That collector was not found or is not approved/active." + : $"No approved or active collectors are in the '{targetEnvironment}' group.")); + } + + PackPopulationDiff diff = PackGalleryService.BuildDiff(loaded, targets); + try + { + PackInstallRequestRecord created = await store.SubmitPackInstallAsync( + loaded.Manifest.Id, + loaded.Manifest.Version, + loaded.Manifest.Name, + loaded.Manifest.PackHash, + loaded.SignedByKeyId, + targetEnvironment, + targetCollectorId, + diff, + submission.Reason, + ManagementApplication.ObjectId(user), + ManagementApplication.DisplayName(user), + clock.GetUtcNow(), + cancellationToken); + return Results.Created($"/api/packs/install-requests/{created.Id}", created); + } + catch (ArgumentException) + { + return Results.ValidationProblem( + new Dictionary { ["reason"] = ["A decision reason (1-500 characters) is required."] }); + } + catch (PackInstallConflictException exception) + { + return Results.Conflict(new ErrorResponse(exception.Message)); + } + } + + private static async Task ReviewInstallAsync( + string id, + bool approve, + ApprovalRequest request, + ClaimsPrincipal user, + PackGalleryService gallery, + ManagementStore store, + TimeProvider clock, + CancellationToken cancellationToken) + { + if (string.IsNullOrWhiteSpace(id) || id.Length != 32 || !id.All(Uri.IsHexDigit)) + { + return Results.NotFound(); + } + + try + { + PackInstallRequestRecord? updated = await store.ReviewPackInstallAsync( + id, + approve, + existing => + { + (LoadedPack? loaded, string? refusal) = gallery.ResolveTrusted(existing.PackId, existing.PackVersion); + if (loaded is null) + { + return refusal ?? "Pack is no longer trusted or available in the gallery."; + } + + if (!string.Equals(loaded.Manifest.PackHash, existing.PackHash, StringComparison.Ordinal)) + { + return "Pack hash changed since the install request was submitted; submit a new request."; + } + + return null; + }, + request.Reason, + ManagementApplication.ObjectId(user), + ManagementApplication.DisplayName(user), + clock.GetUtcNow(), + cancellationToken); + return updated is null ? Results.NotFound() : Results.Ok(updated); + } + catch (ArgumentException) + { + return Results.ValidationProblem( + new Dictionary { ["reason"] = ["A decision reason (1-500 characters) is required."] }); + } + catch (PackInstallConflictException exception) + { + return Results.Conflict(new ErrorResponse(exception.Message)); + } + } +} diff --git a/src/Bower.Management.Api/PackGalleryModels.cs b/src/Bower.Management.Api/PackGalleryModels.cs new file mode 100644 index 00000000..48133267 --- /dev/null +++ b/src/Bower.Management.Api/PackGalleryModels.cs @@ -0,0 +1,110 @@ +namespace Bower.Management.Api; + +public static class PackInstallRequestStatus +{ + public const string PendingReview = "pending-review"; + public const string Approved = "approved"; + public const string Rejected = "rejected"; +} + +/// Gallery listing of signed packs held by management. Metadata and post-redaction checks only. +public sealed record PackGalleryResponse( + bool Configured, + int TrustedKeyCount, + IReadOnlyList Packs, + IReadOnlyList Groups); + +/// A collector group (environment) eligible for pack installation. +public sealed record PackTargetGroup( + string Environment, + int EligibleCollectors, + IReadOnlyList CollectorIds); + +/// +/// One pack archive in the management gallery. Untrusted or tampered archives are returned with +/// = false and a plain refusal reason so operators see why they were refused. +/// +public sealed record PackGalleryItem( + bool Trusted, + string FileName, + string? Id, + string? Version, + string? Name, + string? Description, + string? Owner, + DateTimeOffset? BuiltAtUtc, + string? PackHash, + string? SignedByKeyId, + IReadOnlyList EventTypes, + IReadOnlyList Policies, + IReadOnlyList Redactions, + int DetectionCount, + int ParserCount, + IReadOnlyList SampleResults, + string? RefusalReason); + +public sealed record PackPolicySummary( + string Id, + string Version, + string Action, + IReadOnlyList EventTypes, + string Hash); + +/// Metadata-only sample execution result: never raw sample inputs or sensitive values. +public sealed record PackSampleSummary( + string Name, + bool Passed, + string ExpectedDecision, + string ActualDecision, + IReadOnlyList Problems); + +/// Request to install a signed pack to a collector group (environment) or single collector. +public sealed record PackInstallSubmission( + string? PackId, + string? Version, + string? TargetEnvironment, + string? TargetCollectorId, + string? Reason); + +/// Population diff snapshot computed when submitting or reviewing a pack install. +public sealed record PackPopulationDiff( + string PackId, + string PackVersion, + string PackHash, + IReadOnlyList EventTypesAdded, + IReadOnlyList PolicyChanges, + IReadOnlyList AffectedCollectors); + +public sealed record PackPolicyDiffEntry( + string PolicyId, + string Change, + string Detail); + +public sealed record PackCollectorDiffEntry( + string CollectorId, + string MachineName, + string Environment, + string CurrentPolicyHash, + string? CurrentDesiredPolicyHash, + string TargetPolicyHash, + bool AlreadyAssigned); + +/// Stored four-eyes pack installation request. +public sealed record PackInstallRequestRecord( + string Id, + string PackId, + string PackVersion, + string PackName, + string PackHash, + string SignedByKeyId, + string? TargetEnvironment, + string? TargetCollectorId, + string Status, + PackPopulationDiff Diff, + string Reason, + string RequestedByObjectId, + string RequestedByName, + DateTimeOffset RequestedAt, + string? ReviewerName, + DateTimeOffset? ReviewedAt, + string? ReviewReason); diff --git a/src/Bower.Management.Api/PackGalleryService.cs b/src/Bower.Management.Api/PackGalleryService.cs new file mode 100644 index 00000000..461482ad --- /dev/null +++ b/src/Bower.Management.Api/PackGalleryService.cs @@ -0,0 +1,296 @@ +using System.Security.Cryptography; +using Bower.Packs; +using Bower.Redaction.Privacy; + +namespace Bower.Management.Api; + +/// +/// Server-side signed pack gallery backed by a configured directory (BOWER_PACK_GALLERY_DIR) +/// and trusted ECDSA public keys (BOWER_PACK_TRUSTED_KEYS). Every archive is signature- and +/// hash-verified via before being listed as trusted or accepted for +/// installation; untrusted packs are explicitly surfaced with a plain refusal reason and can never +/// be installed. +/// +public sealed class PackGalleryService +{ + public const string GalleryDirectorySetting = "BOWER_PACK_GALLERY_DIR"; + public const string TrustedKeysSetting = "BOWER_PACK_TRUSTED_KEYS"; + private const int MaximumArchives = 100; + + private readonly string? _galleryDirectory; + private readonly IReadOnlyList _trustedKeyFiles; + + public PackGalleryService(string? galleryDirectory, IReadOnlyList trustedKeyFiles) + { + _galleryDirectory = string.IsNullOrWhiteSpace(galleryDirectory) ? null : Path.GetFullPath(galleryDirectory.Trim()); + _trustedKeyFiles = trustedKeyFiles; + } + + public static PackGalleryService FromConfiguration(IConfiguration configuration) + { + string? directory = configuration[GalleryDirectorySetting]; + string? rawKeys = configuration[TrustedKeysSetting]; + string[] keyFiles = string.IsNullOrWhiteSpace(rawKeys) + ? [] + : rawKeys.Split([',', ';'], StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries); + return new PackGalleryService(directory, keyFiles); + } + + public bool Configured => _galleryDirectory is not null; + + public (IReadOnlyList Items, int TrustedKeyCount) List(TimeProvider clock) + { + if (_galleryDirectory is null || !Directory.Exists(_galleryDirectory)) + { + return ([], ReadTrustedKeys().Count); + } + + List trustedKeys = ReadTrustedKeys(); + string[] archives = Directory.EnumerateFiles(_galleryDirectory, "*.bowerpack", SearchOption.TopDirectoryOnly) + .OrderBy(Path.GetFileName, StringComparer.Ordinal) + .Take(MaximumArchives) + .ToArray(); + + List items = []; + foreach (string archivePath in archives) + { + items.Add(InspectArchive(archivePath, trustedKeys, clock).Item); + } + + return (items, trustedKeys.Count); + } + + /// + /// Re-verifies a specific pack by id and version against the configured trusted keys. + /// Returns either the verified pack or a plain refusal reason. + /// + public (LoadedPack? Pack, string? RefusalReason) ResolveTrusted(string packId, string version) + { + if (_galleryDirectory is null || !Directory.Exists(_galleryDirectory)) + { + return (null, "Pack gallery is not configured on management."); + } + + List trustedKeys = ReadTrustedKeys(); + if (trustedKeys.Count == 0) + { + return (null, "No trusted pack signing keys are configured on management; refusing to trust any pack."); + } + + string[] archives = Directory.EnumerateFiles(_galleryDirectory, "*.bowerpack", SearchOption.TopDirectoryOnly) + .OrderBy(Path.GetFileName, StringComparer.Ordinal) + .Take(MaximumArchives) + .ToArray(); + + string? matchingRefusal = null; + string expectedPrefix = $"{packId}-{version}.bowerpack"; + foreach (string archivePath in archives) + { + try + { + LoadedPack loaded = PackArchive.Load(archivePath, trustedKeys); + if (string.Equals(loaded.Manifest.Id, packId, StringComparison.Ordinal) + && string.Equals(loaded.Manifest.Version, version, StringComparison.Ordinal)) + { + return (loaded, null); + } + } + catch (Exception exception) when (exception is PackVerificationException or InvalidDataException) + { + if (string.Equals(Path.GetFileName(archivePath), expectedPrefix, StringComparison.OrdinalIgnoreCase)) + { + matchingRefusal = SanitiseReason(exception.Message); + } + } + } + + return (null, matchingRefusal ?? $"Signed pack '{packId}' version '{version}' was not found or is not trusted."); + } + + /// + /// Builds the population diff for installing onto . + /// + public static PackPopulationDiff BuildDiff(LoadedPack pack, IReadOnlyList targets) + { + ArgumentNullException.ThrowIfNull(pack); + ArgumentNullException.ThrowIfNull(targets); + + string[] eventTypes = pack.Policies + .SelectMany(policy => policy.Policy.Match.EventTypes) + .Distinct(StringComparer.Ordinal) + .OrderBy(item => item, StringComparer.Ordinal) + .ToArray(); + + PackPolicyDiffEntry[] policyChanges = pack.Policies + .OrderBy(policy => policy.Policy.Metadata.Id, StringComparer.Ordinal) + .Select(policy => new PackPolicyDiffEntry( + policy.Policy.Metadata.Id, + "policy-added", + $"Action {policy.Policy.Decision.Action} for {string.Join(", ", policy.Policy.Match.EventTypes)}.")) + .ToArray(); + + PackCollectorDiffEntry[] collectors = targets + .OrderBy(collector => collector.Id, StringComparer.Ordinal) + .Select(collector => new PackCollectorDiffEntry( + collector.Id, + collector.MachineName, + collector.Environment, + collector.PolicyHash, + collector.DesiredPolicyHash, + pack.Manifest.PackHash, + string.Equals(collector.DesiredPolicyHash, pack.Manifest.PackHash, StringComparison.Ordinal))) + .ToArray(); + + return new PackPopulationDiff( + pack.Manifest.Id, + pack.Manifest.Version, + pack.Manifest.PackHash, + eventTypes, + policyChanges, + collectors); + } + + private static (PackGalleryItem Item, LoadedPack? Loaded) InspectArchive( + string archivePath, + List trustedKeys, + TimeProvider clock) + { + string fileName = Path.GetFileName(archivePath); + if (trustedKeys.Count == 0) + { + return (Refused(fileName, "No trusted pack signing keys are configured on management; refusing to trust any pack."), null); + } + + try + { + LoadedPack loaded = PackArchive.Load(archivePath, trustedKeys); + PrivacyPolicy privacy = BuildPrivacyPolicy(loaded.PrivacyProfileYaml, out string[] redactions); + PackSampleSummary[] samples = PackTester.Run(loaded, privacy, clock) + .Select(result => new PackSampleSummary( + result.Name, + result.Passed, + result.ExpectedDecision, + result.ActualDecision, + result.Problems)) + .ToArray(); + + string[] eventTypes = loaded.Policies + .SelectMany(policy => policy.Policy.Match.EventTypes) + .Distinct(StringComparer.Ordinal) + .OrderBy(item => item, StringComparer.Ordinal) + .ToArray(); + + PackPolicySummary[] policies = loaded.Policies + .OrderBy(policy => policy.Policy.Metadata.Id, StringComparer.Ordinal) + .Select(policy => new PackPolicySummary( + policy.Policy.Metadata.Id, + policy.Policy.Metadata.Version, + policy.Policy.Decision.Action, + policy.Policy.Match.EventTypes, + policy.Hash)) + .ToArray(); + + PackGalleryItem item = new( + true, + fileName, + loaded.Manifest.Id, + loaded.Manifest.Version, + loaded.Manifest.Name, + loaded.Manifest.Description, + loaded.Manifest.Owner, + loaded.Manifest.CreatedAt, + loaded.Manifest.PackHash, + loaded.SignedByKeyId, + eventTypes, + policies, + redactions, + loaded.Detections.Count, + loaded.Parsers.Count, + samples, + null); + return (item, loaded); + } + catch (Exception exception) when (exception is PackVerificationException or InvalidDataException) + { + return (Refused(fileName, SanitiseReason(exception.Message)), null); + } + catch (Exception exception) when (exception is not OutOfMemoryException) + { + return (Refused(fileName, "Pack archive could not be verified."), null); + } + } + + private static PackGalleryItem Refused(string fileName, string reason) => new( + false, + fileName, + null, + null, + null, + null, + null, + null, + null, + null, + [], + [], + [], + 0, + 0, + [], + reason); + + private List ReadTrustedKeys() + { + List keys = []; + foreach (string path in _trustedKeyFiles) + { + if (File.Exists(path)) + { + keys.Add(File.ReadAllText(path)); + } + } + + return keys; + } + + private static PrivacyPolicy BuildPrivacyPolicy(string? privacyProfileYaml, out string[] summary) + { + byte[] key = RandomNumberGenerator.GetBytes(32); + if (string.IsNullOrWhiteSpace(privacyProfileYaml)) + { + summary = + [ + "Default Australian privacy policy (TFN, Medicare, BSB, payment cards, credentials and tokens redacted before persistence)." + ]; + return PrivacyPolicy.CreateDefault(); + } + + LoadedPrivacyProfile loaded = PrivacyProfileLoader.Load(privacyProfileYaml, key, "gallery-preview"); + List lines = + [ + $"Bundled privacy profile {loaded.Id} v{loaded.Version} (Australian defaults active)." + ]; + if (loaded.Policy.SecretFieldNames.Count > 0) + { + lines.Add($"Removes {loaded.Policy.SecretFieldNames.Count} additional secret field name(s)."); + } + + if (loaded.Policy.FieldRules.Count > 0) + { + lines.Add($"Applies {loaded.Policy.FieldRules.Count} explicit field rule(s)."); + } + + foreach (CustomDetectorDefinition detector in loaded.Policy.CustomDetectors) + { + lines.Add($"Custom detector {detector.Id}: {detector.Action} ({detector.Description})."); + } + + summary = [.. lines]; + return loaded.Policy; + } + + private static string SanitiseReason(string message) => + string.IsNullOrWhiteSpace(message) + ? "Pack failed signature or integrity verification." + : message.Length <= 300 ? message : message[..300]; +} diff --git a/src/Bower.Management.Api/packages.lock.json b/src/Bower.Management.Api/packages.lock.json index c19adb71..0dce648c 100644 --- a/src/Bower.Management.Api/packages.lock.json +++ b/src/Bower.Management.Api/packages.lock.json @@ -305,6 +305,13 @@ "bower.dcr": { "type": "Project" }, + "bower.detection": { + "type": "Project", + "dependencies": { + "Bower.Contracts": "[1.0.0, )", + "YamlDotNet": "[18.1.0, )" + } + }, "bower.evidence": { "type": "Project", "dependencies": { @@ -319,6 +326,18 @@ "bower.jobs": { "type": "Project" }, + "bower.packs": { + "type": "Project", + "dependencies": { + "Bower.Dcr": "[1.0.0, )", + "Bower.Detection": "[1.0.0, )", + "Bower.Integrity": "[1.0.0, )", + "Bower.Pipeline": "[1.0.0, )", + "Bower.PolicyEngine": "[1.0.0, )", + "Bower.Redaction": "[1.0.0, )", + "YamlDotNet": "[18.1.0, )" + } + }, "bower.pipeline": { "type": "Project", "dependencies": { diff --git a/tests/Bower.UnitTests/PackGalleryApiTests.cs b/tests/Bower.UnitTests/PackGalleryApiTests.cs new file mode 100644 index 00000000..5ac328af --- /dev/null +++ b/tests/Bower.UnitTests/PackGalleryApiTests.cs @@ -0,0 +1,266 @@ +using System.IO.Compression; +using System.Net; +using System.Net.Http.Json; +using System.Security.Claims; +using System.Text; +using System.Text.Encodings.Web; +using Bower.Integrity; +using Bower.Management.Api; +using Bower.Packs; +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 PackGalleryApiTests +{ + [Fact] + public async Task Gallery_ListsVerifiedPack_RefusesUntrustedPack_AndEnforcesFourEyesGroupInstall() + { + CancellationToken ct = TestContext.Current.CancellationToken; + using SqliteTemporaryDirectory temp = new(); + string galleryDir = Path.Combine(temp.Path, "gallery"); + Directory.CreateDirectory(galleryDir); + + (string trustedPrivatePem, string trustedPublicPem, _) = DetachedSigner.GenerateKeyPair(); + (string roguePrivatePem, _, _) = DetachedSigner.GenerateKeyPair(); + + string trustedKeyFile = Path.Combine(temp.Path, "trusted.pub.pem"); + File.WriteAllText(trustedKeyFile, trustedPublicPem); + + string sourcePackDir = FindPackDirectory("linux-ssh-gateway"); + string trustedArchive = PackArchive.Build(sourcePackDir, trustedPrivatePem, galleryDir); + string rogueTemp = Path.Combine(temp.Path, "rogue-out"); + string rogueArchive = PackArchive.Build(sourcePackDir, roguePrivatePem, rogueTemp); + File.Copy(rogueArchive, Path.Combine(galleryDir, "rogue-ssh-1.0.0.bowerpack")); + + // Also create a tampered copy of the trusted archive. + string tamperedArchive = Path.Combine(galleryDir, "tampered-ssh-1.0.0.bowerpack"); + File.Copy(trustedArchive, tamperedArchive); + using (ZipArchive zip = ZipFile.Open(tamperedArchive, ZipArchiveMode.Update)) + { + ZipArchiveEntry extra = zip.CreateEntry("content/injected.txt"); + using StreamWriter writer = new(extra.Open(), Encoding.UTF8); + writer.Write("tampered"); + } + + await using WebApplication app = await StartManagementAsync(temp.Path, galleryDir, trustedKeyFile, ct); + using HttpClient client = app.GetTestClient(); + + // Register and approve two collectors in "production" and one in "staging". + foreach ((string id, string env) in new[] { ("col-prod-1", "production"), ("col-prod-2", "production"), ("col-stage-1", "staging") }) + { + using HttpRequestMessage reg = Request(HttpMethod.Post, "/api/collectors/register", $"sp-{id}", id, BowerRoles.Collector); + reg.Content = JsonContent.Create( + new CollectorRegistration(id, id, env, "1.0.1", "cfg-1", "old-policy-hash", [], []), + ManagementJsonContext.Default.CollectorRegistration); + HttpResponseMessage regResp = await client.SendAsync(reg, ct); + Assert.Equal(HttpStatusCode.Accepted, regResp.StatusCode); + + using HttpRequestMessage appr = Request(HttpMethod.Post, $"/api/approvals/{id}/approve", "admin-1", "Admin", BowerRoles.Administrator); + appr.Content = JsonContent.Create(new ApprovalRequest("Approved for test"), ManagementJsonContext.Default.ApprovalRequest); + HttpResponseMessage apprResp = await client.SendAsync(appr, ct); + Assert.Equal(HttpStatusCode.OK, apprResp.StatusCode); + } + + // 1. Viewer can browse gallery; trusted pack verified, rogue and tampered refused with clear reasons. + using HttpRequestMessage listReq = Request(HttpMethod.Get, "/api/packs", "viewer-1", "Viewer", BowerRoles.Viewer); + HttpResponseMessage listResp = await client.SendAsync(listReq, ct); + Assert.Equal(HttpStatusCode.OK, listResp.StatusCode); + PackGalleryResponse gallery = (await listResp.Content.ReadFromJsonAsync(ManagementJsonContext.Default.PackGalleryResponse, ct))!; + Assert.True(gallery.Configured); + Assert.Equal(1, gallery.TrustedKeyCount); + Assert.Equal(3, gallery.Packs.Count); + + PackGalleryItem verified = Assert.Single(gallery.Packs, p => p.Trusted); + Assert.Equal("linux-ssh-gateway", verified.Id); + Assert.NotEmpty(verified.EventTypes); + Assert.NotEmpty(verified.Redactions); + Assert.NotEmpty(verified.SampleResults); + Assert.All(verified.SampleResults, sample => Assert.True(sample.Passed)); + + PackGalleryItem[] refused = gallery.Packs.Where(p => !p.Trusted).ToArray(); + Assert.Equal(2, refused.Length); + Assert.All(refused, item => Assert.False(string.IsNullOrWhiteSpace(item.RefusalReason))); + + // Ensure no full host directory paths leak in gallery response. + string rawBody = await listResp.Content.ReadAsStringAsync(ct); + Assert.DoesNotContain(temp.Path, rawBody, StringComparison.Ordinal); + + // 2. Untrusted pack cannot be submitted for install. + using HttpRequestMessage badInstall = Request(HttpMethod.Post, "/api/packs/install-requests", "op-1", "Operator", BowerRoles.Operator); + badInstall.Content = JsonContent.Create( + new PackInstallSubmission("rogue-ssh", "1.0.0", "production", null, "Try untrusted"), + ManagementJsonContext.Default.PackInstallSubmission); + HttpResponseMessage badResp = await client.SendAsync(badInstall, ct); + Assert.Equal(HttpStatusCode.BadRequest, badResp.StatusCode); + + // 3. Viewer cannot submit pack install (403). + using HttpRequestMessage viewerInstall = Request(HttpMethod.Post, "/api/packs/install-requests", "viewer-1", "Viewer", BowerRoles.Viewer); + viewerInstall.Content = JsonContent.Create( + new PackInstallSubmission(verified.Id, verified.Version, "production", null, "Viewer attempt"), + ManagementJsonContext.Default.PackInstallSubmission); + Assert.Equal(HttpStatusCode.Forbidden, (await client.SendAsync(viewerInstall, ct)).StatusCode); + + // 4. Operator submits group install for "production" -> 201 with population diff covering both prod collectors. + using HttpRequestMessage submitReq = Request(HttpMethod.Post, "/api/packs/install-requests", "op-1", "Alice Operator", BowerRoles.Operator); + submitReq.Content = JsonContent.Create( + new PackInstallSubmission(verified.Id, verified.Version, "production", null, "Enable SSH pack in prod"), + ManagementJsonContext.Default.PackInstallSubmission); + HttpResponseMessage submitResp = await client.SendAsync(submitReq, ct); + Assert.Equal(HttpStatusCode.Created, submitResp.StatusCode); + PackInstallRequestRecord created = (await submitResp.Content.ReadFromJsonAsync(ManagementJsonContext.Default.PackInstallRequestRecord, ct))!; + Assert.Equal(PackInstallRequestStatus.PendingReview, created.Status); + Assert.Equal(2, created.Diff.AffectedCollectors.Count); + Assert.Equal(verified.PackHash, created.PackHash); + + // 5. Four-eyes: requester (even if Approver) cannot approve their own request -> 409. + using HttpRequestMessage selfApprove = Request( + HttpMethod.Post, + $"/api/packs/install-requests/{created.Id}/approve", + "op-1", + "Alice Operator", + BowerRoles.Approver); + selfApprove.Content = JsonContent.Create(new ApprovalRequest("Self approve"), ManagementJsonContext.Default.ApprovalRequest); + Assert.Equal(HttpStatusCode.Conflict, (await client.SendAsync(selfApprove, ct)).StatusCode); + + // 6. Different Approver approves -> 200, updates desiredPolicyHash on both prod collectors only (not staging). + using HttpRequestMessage approveReq = Request( + HttpMethod.Post, + $"/api/packs/install-requests/{created.Id}/approve", + "approver-2", + "Bob Approver", + BowerRoles.Approver); + approveReq.Content = JsonContent.Create(new ApprovalRequest("Reviewed diff and signature"), ManagementJsonContext.Default.ApprovalRequest); + HttpResponseMessage approveResp = await client.SendAsync(approveReq, ct); + Assert.Equal(HttpStatusCode.OK, approveResp.StatusCode); + PackInstallRequestRecord approved = (await approveResp.Content.ReadFromJsonAsync(ManagementJsonContext.Default.PackInstallRequestRecord, ct))!; + Assert.Equal(PackInstallRequestStatus.Approved, approved.Status); + Assert.Equal("Bob Approver", approved.ReviewerName); + + // Verify desiredPolicyHash applied to both production collectors and NOT staging. + using HttpRequestMessage colReq = Request(HttpMethod.Get, "/api/collectors", "viewer-1", "Viewer", BowerRoles.Viewer); + using System.Text.Json.JsonDocument colDoc = System.Text.Json.JsonDocument.Parse( + await (await client.SendAsync(colReq, ct)).Content.ReadAsStringAsync(ct)); + Dictionary desiredByCollector = colDoc.RootElement.EnumerateArray() + .ToDictionary( + item => item.GetProperty("id").GetString()!, + item => item.TryGetProperty("desiredPolicyHash", out System.Text.Json.JsonElement h) + && h.ValueKind == System.Text.Json.JsonValueKind.String + ? h.GetString() + : null, + StringComparer.Ordinal); + Assert.Equal(verified.PackHash, desiredByCollector["col-prod-1"]); + Assert.Equal(verified.PackHash, desiredByCollector["col-prod-2"]); + Assert.Null(desiredByCollector["col-stage-1"]); + + // Verify audit trail captured both request and approval. + using HttpRequestMessage auditReq = Request(HttpMethod.Get, "/api/audit", "viewer-1", "Viewer", BowerRoles.Viewer); + List audits = (await (await client.SendAsync(auditReq, ct)) + .Content.ReadFromJsonAsync(ManagementJsonContext.Default.ListAuditRecord, ct))!; + Assert.Contains(audits, a => a.Action == "pack.install-requested" && a.TargetId == created.Id); + Assert.Contains(audits, a => a.Action == "pack.install-approved" && a.TargetId == created.Id && a.InitiatedByObjectId == "op-1"); + } + + private static string FindPackDirectory(string packName) + { + DirectoryInfo? current = new(AppContext.BaseDirectory); + while (current is not null) + { + string candidate = Path.Combine(current.FullName, "packs", packName); + if (Directory.Exists(candidate)) + { + return candidate; + } + + current = current.Parent; + } + + throw new DirectoryNotFoundException($"Could not locate packs/{packName}."); + } + + private static async Task StartManagementAsync( + string root, + string galleryDir, + string trustedKeyFile, + 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_PACK_GALLERY_DIR={galleryDir}", + $"--BOWER_PACK_TRUSTED_KEYS={trustedKeyFile}" + ], + builder => + { + builder.WebHost.UseTestServer(); + builder.Services.AddAuthentication(options => + { + options.DefaultAuthenticateScheme = "PackTest"; + options.DefaultChallengeScheme = "PackTest"; + options.DefaultScheme = "PackTest"; + }).AddScheme("PackTest", _ => { }); + }); + await ManagementApplication.InitializeAsync(app, cancellationToken); + await app.StartAsync(cancellationToken); + return app; + } + + private sealed class PackTestAuthHandler( + 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/packages.lock.json b/tests/Bower.UnitTests/packages.lock.json index 60c63e4b..ee57e48f 100644 --- a/tests/Bower.UnitTests/packages.lock.json +++ b/tests/Bower.UnitTests/packages.lock.json @@ -848,6 +848,7 @@ "Bower.Evidence": "[1.0.0, )", "Bower.Integrity": "[1.0.0, )", "Bower.Jobs": "[1.0.0, )", + "Bower.Packs": "[1.0.0, )", "Bower.Pipeline": "[1.0.0, )", "Bower.PolicyEngine": "[1.0.0, )", "Bower.Redaction": "[1.0.0, )", diff --git a/ui/Bower.Management.Web/src/App.tsx b/ui/Bower.Management.Web/src/App.tsx index 1f5ef459..997f3210 100644 --- a/ui/Bower.Management.Web/src/App.tsx +++ b/ui/Bower.Management.Web/src/App.tsx @@ -9,6 +9,7 @@ import { KeyRound, ListChecks, Menu, + Package, Plug, Moon, ScrollText, @@ -39,6 +40,7 @@ import { PoliciesPage } from "./pages/PoliciesPage"; import { SetupPage } from "./pages/SetupPage"; import { EnrolmentPage } from "./pages/EnrolmentPage"; import { SourcesPage } from "./pages/SourcesPage"; +import { PacksPage } from "./pages/PacksPage"; import { useConsoleView } from "./hooks/useConsoleView"; const navItems = [ @@ -49,6 +51,7 @@ const navItems = [ { to: "/setup", label: "Setup", icon: ListChecks }, { to: "/collectors", label: "Collectors", icon: Boxes }, { to: "/sources", label: "Sources", icon: Plug }, + { to: "/packs", label: "Packs", icon: Package }, { to: "/pipelines", label: "Pipelines", icon: GitBranch }, { to: "/approvals", label: "Approvals", icon: ClipboardCheck }, { to: "/enrolment", label: "Enrolment", icon: Ticket }, @@ -184,6 +187,7 @@ export function App() { } /> } /> } /> + } /> } /> } /> } /> diff --git a/ui/Bower.Management.Web/src/pages/ApprovalsPage.tsx b/ui/Bower.Management.Web/src/pages/ApprovalsPage.tsx index 1db73151..6624a80c 100644 --- a/ui/Bower.Management.Web/src/pages/ApprovalsPage.tsx +++ b/ui/Bower.Management.Web/src/pages/ApprovalsPage.tsx @@ -12,6 +12,7 @@ import { useResource } from "../hooks/useResource"; import { formatDate } from "../lib/format"; import type { Access, Approval, Collector } from "../types"; import { SourceSetupApprovals } from "./SourceSetupApprovals"; +import { PackInstallApprovals } from "./PackInstallApprovals"; export function ApprovalsPage() { const api = useApi(); @@ -154,6 +155,8 @@ export function ApprovalsPage() { + +

Decision history

diff --git a/ui/Bower.Management.Web/src/pages/PackInstallApprovals.tsx b/ui/Bower.Management.Web/src/pages/PackInstallApprovals.tsx new file mode 100644 index 00000000..8d429a36 --- /dev/null +++ b/ui/Bower.Management.Web/src/pages/PackInstallApprovals.tsx @@ -0,0 +1,169 @@ +import { CheckCircle2, KeyRound } from "lucide-react"; +import { useState } from "react"; +import { useApi } from "../api"; +import { EmptyState, ResourceState } from "../components/ui"; +import { useResource } from "../hooks/useResource"; +import { formatDate } from "../lib/format"; +import type { Access, PackInstallRequestRecord } from "../types"; + +export function PackInstallApprovals({ access, canApprove }: { access: Access | null; canApprove: boolean }) { + const [refresh, setRefresh] = useState(0); + const requests = useResource("/api/packs/install-requests", refresh); + + return ( +
+
+

Pack installation requests

+ Two people: one asks, another decides +
+ + {(items) => { + const pending = Array.isArray(items) + ? items.filter((item) => item.status === "pending-review") + : []; + return pending.length ? ( +
+ {pending.map((item) => ( + setRefresh((value) => value + 1)} + /> + ))} +
+ ) : ( +
+
+ ); +} + +function PackInstallApprovalCard({ + item, + access, + canApprove, + onDecided +}: { + item: PackInstallRequestRecord; + access: Access | null; + canApprove: boolean; + onDecided: () => void; +}) { + const api = useApi(); + const [reason, setReason] = useState(""); + const [busy, setBusy] = useState(false); + const [error, setError] = useState(null); + const own = access !== null && access.objectId === item.requestedByObjectId; + + async function decide(action: "approve" | "reject") { + if (!reason.trim()) { + setError("Enter a reason before recording the decision."); + return; + } + setBusy(true); + setError(null); + try { + await api(`/api/packs/install-requests/${encodeURIComponent(item.id)}/${action}`, { + method: "POST", + body: JSON.stringify({ reason: reason.trim() }) + }); + onDecided(); + } catch (decisionError) { + setError(decisionError instanceof Error ? decisionError.message : "Decision failed."); + } finally { + setBusy(false); + } + } + + return ( +
+
+

+ {item.packName} v{item.packVersion} → {item.targetEnvironment ?? item.targetCollectorId} +

+
+
+
Asked for by
+
+ {item.requestedByName}, {formatDate(item.requestedAt)} +
+
+
+
Reason
+
{item.reason}
+
+
+
Signed key / Pack hash
+
+ {item.signedByKeyId} · {item.packHash.slice(0, 12)} +
+
+
+
Population diff
+
+ {item.diff.affectedCollectors.length} collector + {item.diff.affectedCollectors.length === 1 ? "" : "s"} · {item.diff.eventTypesAdded.join(", ")} +
+
+
+
+ {!canApprove ? ( +
+
+ ) : own ? ( +
+
+ ) : ( +
{ + event.preventDefault(); + void decide("approve"); + }} + > + {error && ( +
+ {error} +
+ )} + +