diff --git a/src/Bower.Management.Api/Bower.Management.Api.csproj b/src/Bower.Management.Api/Bower.Management.Api.csproj index 9b8d8bd1..609b912c 100644 --- a/src/Bower.Management.Api/Bower.Management.Api.csproj +++ b/src/Bower.Management.Api/Bower.Management.Api.csproj @@ -22,6 +22,7 @@ + diff --git a/src/Bower.Management.Api/ManagementApplication.cs b/src/Bower.Management.Api/ManagementApplication.cs index 9d46865c..4d929043 100644 --- a/src/Bower.Management.Api/ManagementApplication.cs +++ b/src/Bower.Management.Api/ManagementApplication.cs @@ -642,6 +642,7 @@ await store.GetAsync(id, cancellationToken) is null PrivacyProfileEndpoints.Map(api); PrivacyProfileForm.Map(api); + PolicyFormEndpoints.Map(api); SetupEndpoints.Map(api); EnrolmentEndpoints.Map(api); SourceSetupEndpoints.Map(api); diff --git a/src/Bower.Management.Api/ManagementJson.cs b/src/Bower.Management.Api/ManagementJson.cs index 369ac1e7..148aa324 100644 --- a/src/Bower.Management.Api/ManagementJson.cs +++ b/src/Bower.Management.Api/ManagementJson.cs @@ -100,6 +100,10 @@ public sealed record PipelineValidationResponse( [JsonSerializable(typeof(SignedSourceSetup))] [JsonSerializable(typeof(Bower.Evidence.OfflineSiteReportDocument))] [JsonSerializable(typeof(Bower.Evidence.SignedOfflineSiteReport))] +[JsonSerializable(typeof(PolicyTemplateItem[]))] +[JsonSerializable(typeof(PolicyFormRequest))] +[JsonSerializable(typeof(PolicyFormResult))] +[JsonSerializable(typeof(string))] [JsonSerializable(typeof(Dictionary))] [JsonSerializable(typeof(Microsoft.AspNetCore.Mvc.ProblemDetails))] [JsonSerializable(typeof(HttpValidationProblemDetails))] diff --git a/src/Bower.Management.Api/PolicyFormEndpoints.cs b/src/Bower.Management.Api/PolicyFormEndpoints.cs new file mode 100644 index 00000000..add8451d --- /dev/null +++ b/src/Bower.Management.Api/PolicyFormEndpoints.cs @@ -0,0 +1,496 @@ +using System.Globalization; +using System.Text; +using System.Text.Json; +using Bower.Abstractions; +using Bower.Contracts; +using Bower.PolicyEngine; +using Bower.Redaction.Privacy; +using Microsoft.AspNetCore.Mvc; +using YamlDotNet.Core; +using YamlDotNet.RepresentationModel; + +namespace Bower.Management.Api; + +public sealed record PolicyTemplateItem(string Id, string Title, string Description, string Content); + +public sealed record PolicySuppressionForm( + bool Enabled, + IReadOnlyList KeyFields, + int WindowSeconds, + int AllowPerWindow); + +public sealed record PolicyForm( + string Id, + string Name, + string Version, + string Owner, + IReadOnlyList EventCategories, + IReadOnlyList EventTypes, + IReadOnlyList RequiredFields, + IReadOnlyList AtLeastOne, + IReadOnlyList RecommendedFields, + string Action, + int MinimumValueScore, + bool NeverSample, + PolicySuppressionForm? Suppression); + +public sealed record PolicyFormRequest(string Content, PolicyForm? Form); + +public sealed record PolicyDiffEntry(string Change, string Detail); + +public sealed record PolicyFormDiff( + string BeforeHash, + string AfterHash, + bool SemanticallyIdentical, + IReadOnlyList Changes); + +public sealed record PolicyPreviewFinding(string DetectorId, string Action, string Path); + +public sealed record PolicySamplePreview( + bool Valid, + string BeforeDecision, + string AfterDecision, + int ValueScore, + string? RedactedEventJson, + IReadOnlyList Findings); + +public sealed record PolicyFormResult( + PolicyForm Form, + string Content, + bool Valid, + IReadOnlyList Errors, + string? PolicyHash, + PolicyFormDiff? Diff, + PolicySamplePreview? Preview); + +/// +/// No-code policy decision and suppression (aggregate) form editor backed by the +/// collector's own , , +/// and . Only server-owned synthetic samples are previewed, and +/// only post-redaction output ever leaves the API. +/// +internal static class PolicyFormEndpoints +{ + private const long BodyLimit = 256 * 1024; + + private static readonly PolicyTemplateItem[] Templates = + [ + new( + "authentication-failure", + "Authentication failures", + "Accepts authentication failure and account lockout events without sampling.", + """ + apiVersion: bower.security/v1 + kind: TelemetryPolicy + metadata: + id: BWR-POL-AUTH-FAILURE + name: Authentication failures + version: 1.0.0 + owner: Security Operations + match: + eventCategories: + - authentication + eventTypes: + - authentication_failure + - account_lockout + requirements: + requiredFields: + - timeGenerated + - eventType + - eventResult + - application.name + atLeastOne: + - actor.userId + - actor.username + recommendedFields: + - source.ipAddress + - eventOutcomeReason + decision: + action: accept + minimumValueScore: 70 + neverSample: true + routing: + profile: authentication + destination: security-events + """), + new( + "rate-limit-aggregate", + "Rate-limit flood aggregation", + "Aggregates noisy rate-limit hits into per-window summary events using the aggregate action.", + """ + apiVersion: bower.security/v1 + kind: TelemetryPolicy + metadata: + id: BWR-POL-RATE-LIMIT + name: Rate-limit flood aggregation + version: 1.0.0 + owner: Application Security + match: + eventCategories: + - anti-automation + eventTypes: + - rate_limit_exceeded + requirements: + requiredFields: + - timeGenerated + - eventType + - eventResult + - application.name + atLeastOne: + - source.ipAddress + - actor.username + recommendedFields: + - request.correlationId + decision: + action: aggregate + minimumValueScore: 50 + neverSample: false + suppression: + keyFields: + - application.name + - eventType + - source.ipAddress + windowSeconds: 60 + allowPerWindow: 0 + routing: + profile: application-security + destination: security-events + """) + ]; + + public static void Map(RouteGroupBuilder api) + { + api.MapGet("/policies/templates", () => Results.Ok(Templates)) + .RequireAuthorization("View"); + + api.MapPost( + "/policies/form", + (PolicyFormRequest request) => + { + if (string.IsNullOrWhiteSpace(request.Content)) + { + return Results.BadRequest(new ErrorResponse("Policy YAML content is required.")); + } + + LoadedPolicy baseline; + try + { + baseline = PolicyLoader.LoadYaml(request.Content, "policy.yaml"); + } + catch (Exception exception) when (exception is InvalidDataException or YamlException) + { + return Results.BadRequest(new ErrorResponse( + $"Baseline policy YAML is invalid: {exception.Message}")); + } + + string editedYaml = request.Content; + if (request.Form is { } form) + { + if (!TryApplyForm(request.Content, form, out editedYaml, out string? formError)) + { + return Results.Ok(new PolicyFormResult( + form, request.Content, false, [formError!], null, null, null)); + } + } + + LoadedPolicy candidate; + try + { + candidate = PolicyLoader.LoadYaml(editedYaml, "policy.yaml"); + } + catch (Exception exception) when (exception is InvalidDataException or YamlException) + { + return Results.Ok(new PolicyFormResult( + request.Form ?? ToForm(baseline.Policy), + editedYaml, + false, + [exception.Message], + null, + null, + null)); + } + + PolicyFormDiff diff = ComputeDiff(baseline, candidate); + PolicySamplePreview preview = BuildRedactedPreview(baseline, candidate); + return Results.Ok(new PolicyFormResult( + ToForm(candidate.Policy), + editedYaml, + true, + [], + candidate.Hash, + diff, + preview)); + }) + .WithMetadata(new RequestSizeLimitAttribute(BodyLimit)) + .RequireAuthorization("Operate"); + } + + private static bool TryApplyForm( + string originalYaml, + PolicyForm form, + out string updatedYaml, + out string? error) + { + updatedYaml = originalYaml; + error = null; + + if (string.IsNullOrWhiteSpace(form.Id) || form.Id.Length > 128 + || string.IsNullOrWhiteSpace(form.Name) || form.Name.Length > 200 + || string.IsNullOrWhiteSpace(form.Version) || form.Version.Length > 64 + || string.IsNullOrWhiteSpace(form.Owner) || form.Owner.Length > 200) + { + error = "Policy id, name, version and owner are required."; + return false; + } + + string action = (form.Action ?? string.Empty).Trim().ToLowerInvariant(); + if (action is not ("accept" or "redact-and-accept" or "quarantine" or "reject" or "aggregate")) + { + error = "Choose a supported decision action: accept, redact-and-accept, aggregate, quarantine or reject."; + return false; + } + + if (form.MinimumValueScore is < 0 or > 100) + { + error = "Minimum value score must be between 0 and 100."; + return false; + } + + string[] eventTypes = CleanList(form.EventTypes); + if (eventTypes.Length == 0 || eventTypes.Length > 64) + { + error = "List between 1 and 64 event types."; + return false; + } + + YamlStream stream = new(); + stream.Load(new StringReader(originalYaml)); + YamlMappingNode root = (YamlMappingNode)stream.Documents[0].RootNode; + + YamlMappingNode metadata = EnsureMapping(root, "metadata"); + metadata.Children[new YamlScalarNode("id")] = Scalar(form.Id.Trim()); + metadata.Children[new YamlScalarNode("name")] = Scalar(form.Name.Trim()); + metadata.Children[new YamlScalarNode("version")] = Scalar(form.Version.Trim()); + metadata.Children[new YamlScalarNode("owner")] = Scalar(form.Owner.Trim()); + + YamlMappingNode match = EnsureMapping(root, "match"); + match.Children[new YamlScalarNode("eventCategories")] = Sequence(CleanList(form.EventCategories)); + match.Children[new YamlScalarNode("eventTypes")] = Sequence(eventTypes); + + YamlMappingNode requirements = EnsureMapping(root, "requirements"); + requirements.Children[new YamlScalarNode("requiredFields")] = Sequence(CleanList(form.RequiredFields)); + requirements.Children[new YamlScalarNode("atLeastOne")] = Sequence(CleanList(form.AtLeastOne)); + requirements.Children[new YamlScalarNode("recommendedFields")] = Sequence(CleanList(form.RecommendedFields)); + + YamlMappingNode decision = EnsureMapping(root, "decision"); + decision.Children[new YamlScalarNode("action")] = Scalar(action); + decision.Children[new YamlScalarNode("minimumValueScore")] = + new YamlScalarNode(form.MinimumValueScore.ToString(CultureInfo.InvariantCulture)); + decision.Children[new YamlScalarNode("neverSample")] = + new YamlScalarNode(form.NeverSample ? "true" : "false"); + + YamlScalarNode suppressionKey = new("suppression"); + if (form.Suppression is { Enabled: true } suppression) + { + string[] keyFields = CleanList(suppression.KeyFields); + YamlMappingNode suppressionNode = new() + { + { "keyFields", Sequence(keyFields) }, + { "windowSeconds", new YamlScalarNode(suppression.WindowSeconds.ToString(CultureInfo.InvariantCulture)) }, + { "allowPerWindow", new YamlScalarNode(suppression.AllowPerWindow.ToString(CultureInfo.InvariantCulture)) } + }; + root.Children[suppressionKey] = suppressionNode; + } + else + { + root.Children.Remove(suppressionKey); + } + + using StringWriter writer = new(CultureInfo.InvariantCulture); + stream.Save(writer, assignAnchors: false); + updatedYaml = writer.ToString(); + return true; + } + + private static PolicyForm ToForm(TelemetryPolicy policy) => new( + policy.Metadata.Id, + policy.Metadata.Name, + policy.Metadata.Version, + policy.Metadata.Owner, + policy.Match.EventCategories, + policy.Match.EventTypes, + policy.Requirements.RequiredFields, + policy.Requirements.AtLeastOne, + policy.Requirements.RecommendedFields, + policy.Decision.Action, + policy.Decision.MinimumValueScore, + policy.Decision.NeverSample, + policy.Suppression is null + ? new PolicySuppressionForm(false, ["application.name", "eventType", "source.ipAddress"], 60, 0) + : new PolicySuppressionForm( + true, + policy.Suppression.KeyFields, + policy.Suppression.WindowSeconds, + policy.Suppression.AllowPerWindow)); + + private static PolicyFormDiff ComputeDiff(LoadedPolicy before, LoadedPolicy after) + { + List changes = []; + TelemetryPolicy a = before.Policy; + TelemetryPolicy b = after.Policy; + + foreach (string added in b.Match.EventTypes.Except(a.Match.EventTypes, StringComparer.Ordinal)) + { + changes.Add(new("event-type-added", $"Now accepts event type '{added}'.")); + } + + foreach (string removed in a.Match.EventTypes.Except(b.Match.EventTypes, StringComparer.Ordinal)) + { + changes.Add(new("event-type-removed", $"No longer accepts event type '{removed}' (falls back to default-deny).")); + } + + foreach (string added in b.Requirements.RequiredFields.Except(a.Requirements.RequiredFields, StringComparer.Ordinal)) + { + changes.Add(new("required-field-added", $"Requires '{added}' (events without it will be quarantined).")); + } + + foreach (string removed in a.Requirements.RequiredFields.Except(b.Requirements.RequiredFields, StringComparer.Ordinal)) + { + changes.Add(new("required-field-removed", $"No longer requires '{removed}'.")); + } + + if (!string.Equals(a.Decision.Action, b.Decision.Action, StringComparison.OrdinalIgnoreCase)) + { + changes.Add(new("action-changed", $"Decision action changes from {a.Decision.Action} to {b.Decision.Action}.")); + } + + if (a.Decision.MinimumValueScore != b.Decision.MinimumValueScore) + { + changes.Add(new("minimum-score-changed", $"Minimum value score changes from {a.Decision.MinimumValueScore} to {b.Decision.MinimumValueScore}.")); + } + + if (a.Decision.NeverSample != b.Decision.NeverSample) + { + changes.Add(new("never-sample-changed", $"neverSample changes from {a.Decision.NeverSample} to {b.Decision.NeverSample}.")); + } + + string beforeSup = FormatSuppression(a.Suppression); + string afterSup = FormatSuppression(b.Suppression); + if (!string.Equals(beforeSup, afterSup, StringComparison.Ordinal)) + { + changes.Add(new("suppression-changed", $"Suppression changes from {beforeSup} to {afterSup}.")); + } + + if (string.Equals(a.Metadata.Version, b.Metadata.Version, StringComparison.Ordinal) + && !string.Equals(before.Hash, after.Hash, StringComparison.Ordinal)) + { + changes.Add(new("version-not-bumped", "Policy rules changed without bumping metadata.version.")); + } + + return new PolicyFormDiff( + before.Hash, + after.Hash, + string.Equals(before.Hash, after.Hash, StringComparison.Ordinal), + changes); + } + + private static PolicySamplePreview BuildRedactedPreview(LoadedPolicy before, LoadedPolicy after) + { + string sampleEventType = after.Policy.Match.EventTypes.FirstOrDefault() ?? "authentication_failure"; + string sampleCategory = after.Policy.Match.EventCategories.FirstOrDefault() ?? "authentication"; + string syntheticRaw = BuildSyntheticSampleJson(sampleCategory, sampleEventType); + + // Always enforce Bower's built-in privacy protection before showing any preview. + PrivacyScanResult scan = new PrivacyEngine(PrivacyPolicy.CreateDefault()).RedactJson(syntheticRaw); + if (!scan.Succeeded || scan.RedactedJson is null) + { + return new PolicySamplePreview(false, "quarantine", "quarantine", 0, null, []); + } + + SecurityEventEnvelope envelope = JsonSerializer.Deserialize(scan.RedactedJson, BowerJson.Envelope)!; + PolicyDecision beforeDecision = new DeterministicPolicyEvaluator([before]).Evaluate(envelope); + PolicyDecision afterDecision = new DeterministicPolicyEvaluator([after]).Evaluate(envelope); + + PolicyPreviewFinding[] findings = scan.Findings + .Select(finding => new PolicyPreviewFinding(finding.DetectorId, finding.Action.ToString(), finding.Path)) + .ToArray(); + + return new PolicySamplePreview( + true, + FormatPreviewDecision(beforeDecision), + FormatPreviewDecision(afterDecision), + afterDecision.Score, + scan.RedactedJson, + findings); + } + + private static string FormatPreviewDecision(PolicyDecision decision) => + decision.Action == DecisionAction.Accept && decision.Suppression is { AllowPerWindow: 0 } + ? "aggregate" + : decision.Action switch + { + DecisionAction.RedactAndAccept => "redact-and-accept", + _ => decision.Action.ToString().ToLowerInvariant() + }; + + private static string BuildSyntheticSampleJson(string category, string eventType) + { + StringBuilder json = new(); + json.Append('{'); + json.Append("\"schemaVersion\":\"1.0\","); + json.Append("\"eventId\":\"00000000-0000-4000-8000-000000000001\","); + json.Append("\"timeGenerated\":\"2026-11-22T00:00:00Z\","); + json.Append("\"eventCategory\":").Append(JsonSerializer.Serialize(category, ManagementJsonContext.Default.String)).Append(','); + json.Append("\"eventType\":").Append(JsonSerializer.Serialize(eventType, ManagementJsonContext.Default.String)).Append(','); + json.Append("\"eventAction\":\"synthetic.check\","); + json.Append("\"eventResult\":\"failure\","); + json.Append("\"eventOutcomeReason\":\"synthetic_sample\","); + json.Append("\"severity\":\"medium\","); + json.Append("\"application\":{\"name\":\"sample-app\",\"environment\":\"production\"},"); + json.Append("\"actor\":{\"userId\":\"usr-42\",\"username\":\"alex.example@example.com\"},"); + json.Append("\"source\":{\"ipAddress\":\"192.0.2.10\"},"); + json.Append("\"request\":{\"correlationId\":\"corr-synthetic-001\"},"); + json.Append("\"attributes\":{\"password\":\"synthetic-secret-value\",\"tfn\":\"123456782\",\"note\":\"Synthetic preview only\"}"); + json.Append('}'); + return json.ToString(); + } + + private static string FormatSuppression(PolicySuppression? suppression) => + suppression is null + ? "none" + : $"allow {suppression.AllowPerWindow} per {suppression.WindowSeconds}s keyed by [{string.Join(", ", suppression.KeyFields)}]"; + + private static string[] CleanList(IReadOnlyList? values) => + values is null + ? [] + : values.Where(item => !string.IsNullOrWhiteSpace(item)) + .Select(item => item.Trim()) + .Distinct(StringComparer.Ordinal) + .ToArray(); + + private static YamlMappingNode EnsureMapping(YamlMappingNode parent, string key) + { + YamlScalarNode keyNode = new(key); + if (parent.Children.TryGetValue(keyNode, out YamlNode? existing) && existing is YamlMappingNode mapping) + { + return mapping; + } + + YamlMappingNode created = new(); + parent.Children[keyNode] = created; + return created; + } + + private static YamlScalarNode Scalar(string value) => new(value); + + private static YamlSequenceNode Sequence(IEnumerable items) + { + YamlSequenceNode node = new(); + foreach (string item in items) + { + node.Add(new YamlScalarNode(item)); + } + + return node; + } +} diff --git a/src/Bower.Management.Api/packages.lock.json b/src/Bower.Management.Api/packages.lock.json index 9e1bc0e6..c19adb71 100644 --- a/src/Bower.Management.Api/packages.lock.json +++ b/src/Bower.Management.Api/packages.lock.json @@ -326,6 +326,13 @@ "YamlDotNet": "[18.1.0, )" } }, + "bower.policyengine": { + "type": "Project", + "dependencies": { + "Bower.Abstractions": "[1.0.0, )", + "YamlDotNet": "[18.1.0, )" + } + }, "bower.redaction": { "type": "Project", "dependencies": { diff --git a/tests/Bower.UnitTests/PolicyFormApiTests.cs b/tests/Bower.UnitTests/PolicyFormApiTests.cs new file mode 100644 index 00000000..906a5356 --- /dev/null +++ b/tests/Bower.UnitTests/PolicyFormApiTests.cs @@ -0,0 +1,187 @@ +using System.Net; +using System.Net.Http.Json; +using System.Security.Claims; +using System.Text.Encodings.Web; +using Bower.Management.Api; +using Bower.PolicyEngine; +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 PolicyFormApiTests +{ + private const string BaselineYaml = """ + apiVersion: bower.security/v1 + kind: TelemetryPolicy + metadata: + id: BWR-POL-AUTH-FAILURE + name: Authentication failures + version: 1.0.0 + owner: Security Operations + match: + eventCategories: + - authentication + eventTypes: + - authentication_failure + requirements: + requiredFields: + - timeGenerated + - eventType + - eventResult + - application.name + atLeastOne: + - actor.username + recommendedFields: + - source.ipAddress + decision: + action: accept + minimumValueScore: 70 + neverSample: true + """; + + [Fact] + public async Task PolicyForm_PreservesSemanticHash_SupportsAggregateSuppression_RedactsPreview_AndEnforcesRbac() + { + CancellationToken ct = TestContext.Current.CancellationToken; + using SqliteTemporaryDirectory temp = new(); + await using WebApplication app = await StartManagementAsync(temp.Path, ct); + using HttpClient client = app.GetTestClient(); + + // 1. Viewer can list templates but cannot edit forms (403). + using (HttpRequestMessage tplReq = Request(HttpMethod.Get, "/api/policies/templates", "v1", "Viewer", BowerRoles.Viewer)) + { + HttpResponseMessage tplResp = await client.SendAsync(tplReq, ct); + Assert.Equal(HttpStatusCode.OK, tplResp.StatusCode); + PolicyTemplateItem[] templates = (await tplResp.Content.ReadFromJsonAsync( + ManagementJsonContext.Default.PolicyTemplateItemArray, ct))!; + Assert.True(templates.Length >= 2); + } + + using (HttpRequestMessage viewerPost = Request(HttpMethod.Post, "/api/policies/form", "v1", "Viewer", BowerRoles.Viewer)) + { + viewerPost.Content = JsonContent.Create(new PolicyFormRequest(BaselineYaml, null), ManagementJsonContext.Default.PolicyFormRequest); + Assert.Equal(HttpStatusCode.Forbidden, (await client.SendAsync(viewerPost, ct)).StatusCode); + } + + // 2. Round-trip unmodified form preserves identical loaded policy hash (semantic equivalence). + LoadedPolicy baseline = PolicyLoader.LoadYaml(BaselineYaml, "baseline.yaml"); + using HttpRequestMessage loadReq = Request(HttpMethod.Post, "/api/policies/form", "op-1", "Operator", BowerRoles.Operator); + loadReq.Content = JsonContent.Create(new PolicyFormRequest(BaselineYaml, null), ManagementJsonContext.Default.PolicyFormRequest); + HttpResponseMessage loadResp = await client.SendAsync(loadReq, ct); + Assert.Equal(HttpStatusCode.OK, loadResp.StatusCode); + PolicyFormResult loaded = (await loadResp.Content.ReadFromJsonAsync(ManagementJsonContext.Default.PolicyFormResult, ct))!; + Assert.True(loaded.Valid); + Assert.Equal(baseline.Hash, loaded.PolicyHash); + + using HttpRequestMessage roundTripReq = Request(HttpMethod.Post, "/api/policies/form", "op-1", "Operator", BowerRoles.Operator); + roundTripReq.Content = JsonContent.Create(new PolicyFormRequest(BaselineYaml, loaded.Form), ManagementJsonContext.Default.PolicyFormRequest); + PolicyFormResult roundTripped = (await (await client.SendAsync(roundTripReq, ct)) + .Content.ReadFromJsonAsync(ManagementJsonContext.Default.PolicyFormResult, ct))!; + Assert.True(roundTripped.Valid); + Assert.Equal(baseline.Hash, roundTripped.PolicyHash); + Assert.True(roundTripped.Diff!.SemanticallyIdentical); + + // 3. Change action to aggregate with suppression window and bump version -> valid YAML, diff + redacted preview. + PolicyForm edited = loaded.Form with + { + Version = "1.1.0", + Action = "aggregate", + NeverSample = false, + Suppression = new PolicySuppressionForm(true, ["application.name", "eventType", "source.ipAddress"], 60, 0) + }; + using HttpRequestMessage editReq = Request(HttpMethod.Post, "/api/policies/form", "op-1", "Operator", BowerRoles.Operator); + editReq.Content = JsonContent.Create(new PolicyFormRequest(BaselineYaml, edited), ManagementJsonContext.Default.PolicyFormRequest); + PolicyFormResult editedResult = (await (await client.SendAsync(editReq, ct)) + .Content.ReadFromJsonAsync(ManagementJsonContext.Default.PolicyFormResult, ct))!; + Assert.True(editedResult.Valid); + Assert.False(editedResult.Diff!.SemanticallyIdentical); + Assert.Contains(editedResult.Diff.Changes, c => c.Change == "action-changed"); + Assert.Contains(editedResult.Diff.Changes, c => c.Change == "suppression-changed"); + Assert.Equal("accept", editedResult.Preview!.BeforeDecision); + Assert.Equal("aggregate", editedResult.Preview.AfterDecision); + Assert.NotNull(editedResult.Preview.RedactedEventJson); + // Built-in privacy protection MUST remove the synthetic password and mask the synthetic TFN. + Assert.DoesNotContain("synthetic-secret-value", editedResult.Preview.RedactedEventJson, StringComparison.Ordinal); + Assert.DoesNotContain("123456782", editedResult.Preview.RedactedEventJson, StringComparison.Ordinal); + } + + private static async Task StartManagementAsync(string root, 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")}" + ], + builder => + { + builder.WebHost.UseTestServer(); + builder.Services.AddAuthentication(options => + { + options.DefaultAuthenticateScheme = "PolicyFormTest"; + options.DefaultChallengeScheme = "PolicyFormTest"; + options.DefaultScheme = "PolicyFormTest"; + }).AddScheme("PolicyFormTest", _ => { }); + }); + await ManagementApplication.InitializeAsync(app, cancellationToken); + await app.StartAsync(cancellationToken); + return app; + } + + private sealed class PolicyFormAuthHandler( + 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 6b55bdef..60c63e4b 100644 --- a/tests/Bower.UnitTests/packages.lock.json +++ b/tests/Bower.UnitTests/packages.lock.json @@ -849,6 +849,7 @@ "Bower.Integrity": "[1.0.0, )", "Bower.Jobs": "[1.0.0, )", "Bower.Pipeline": "[1.0.0, )", + "Bower.PolicyEngine": "[1.0.0, )", "Bower.Redaction": "[1.0.0, )", "Bower.ServiceDefaults": "[1.0.0, )", "Microsoft.AspNetCore.Authentication.JwtBearer": "[11.0.0, )", diff --git a/ui/Bower.Management.Web/src/App.tsx b/ui/Bower.Management.Web/src/App.tsx index 73ed9c8d..1f5ef459 100644 --- a/ui/Bower.Management.Web/src/App.tsx +++ b/ui/Bower.Management.Web/src/App.tsx @@ -12,6 +12,7 @@ import { Plug, Moon, ScrollText, + ShieldCheck, Sun, Ticket, Timer, @@ -34,6 +35,7 @@ import { AccessPage } from "./pages/AccessPage"; import { AuditPage } from "./pages/AuditPage"; import { JobsPage } from "./pages/JobsPage"; import { PrivacyProfilesPage } from "./pages/PrivacyProfilesPage"; +import { PoliciesPage } from "./pages/PoliciesPage"; import { SetupPage } from "./pages/SetupPage"; import { EnrolmentPage } from "./pages/EnrolmentPage"; import { SourcesPage } from "./pages/SourcesPage"; @@ -50,6 +52,7 @@ const navItems = [ { to: "/pipelines", label: "Pipelines", icon: GitBranch }, { to: "/approvals", label: "Approvals", icon: ClipboardCheck }, { to: "/enrolment", label: "Enrolment", icon: Ticket }, + { to: "/policies", label: "Policies", icon: ShieldCheck }, { to: "/privacy-profiles", label: "Privacy profiles", icon: FileLock }, { to: "/jobs", label: "Jobs", icon: Timer }, { to: "/access", label: "Access", icon: KeyRound }, @@ -184,6 +187,7 @@ export function App() { } /> } /> } /> + } /> } /> } /> } /> diff --git a/ui/Bower.Management.Web/src/pages/PoliciesPage.test.tsx b/ui/Bower.Management.Web/src/pages/PoliciesPage.test.tsx new file mode 100644 index 00000000..137d461e --- /dev/null +++ b/ui/Bower.Management.Web/src/pages/PoliciesPage.test.tsx @@ -0,0 +1,123 @@ +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"; + +describe("PoliciesPage", () => { + beforeEach(() => { + localStorage.setItem("bower-theme", "light"); + localStorage.setItem("bower-console-view", "detailed"); + }); + + afterEach(() => { + cleanup(); + vi.unstubAllGlobals(); + localStorage.clear(); + }); + + it("changes a policy decision to aggregate with suppression and displays redacted preview and diff", async () => { + const initialYaml = "apiVersion: bower.security/v1\nkind: TelemetryPolicy\n"; + 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/policies/templates") { + return new Response( + JSON.stringify([ + { + id: "authentication-failure", + title: "Authentication failures", + description: "Auth failures", + content: initialYaml + } + ]), + { status: 200 } + ); + } + if (path === "/api/policies/form" && init?.method === "POST") { + const body = JSON.parse(String(init.body)) as { form: { action?: string } | null }; + const action = body.form?.action ?? "accept"; + return new Response( + JSON.stringify({ + form: { + id: "BWR-POL-AUTH-FAILURE", + name: "Authentication failures", + version: action === "aggregate" ? "1.1.0" : "1.0.0", + owner: "Security Operations", + eventCategories: ["authentication"], + eventTypes: ["authentication_failure"], + requiredFields: ["timeGenerated", "eventType", "eventResult", "application.name"], + atLeastOne: ["actor.username"], + recommendedFields: ["source.ipAddress"], + action, + minimumValueScore: 70, + neverSample: action !== "aggregate", + suppression: { + enabled: action === "aggregate", + keyFields: ["application.name", "eventType", "source.ipAddress"], + windowSeconds: 60, + allowPerWindow: 0 + } + }, + content: `${initialYaml}decision:\n action: ${action}\n`, + valid: true, + errors: [], + policyHash: action === "aggregate" ? "sha256:bbbbbbbbbbbbbbbbbbbb" : "sha256:aaaaaaaaaaaaaaaaaaaa", + diff: { + beforeHash: "sha256:aaaaaaaaaaaaaaaaaaaa", + afterHash: action === "aggregate" ? "sha256:bbbbbbbbbbbbbbbbbbbb" : "sha256:aaaaaaaaaaaaaaaaaaaa", + semanticallyIdentical: action !== "aggregate", + changes: + action === "aggregate" + ? [{ change: "action-changed", detail: "Decision action changes from accept to aggregate." }] + : [] + }, + preview: { + valid: true, + beforeDecision: "accept", + afterDecision: action, + valueScore: 80, + redactedEventJson: JSON.stringify({ eventType: "authentication_failure", attributes: { note: "Synthetic preview only" } }), + findings: [{ detectorId: "au.tfn", action: "Mask", path: "attributes.tfn" }] + } + }), + { status: 200 } + ); + } + return new Response("Not found", { status: 404 }); + }); + vi.stubGlobal("fetch", fetchMock); + + render( + + + + + + ); + + await waitFor(() => { + expect(screen.getByLabelText("Decision action")).toBeTruthy(); + }); + + fireEvent.change(screen.getByLabelText("Decision action"), { + target: { value: "aggregate" } + }); + fireEvent.click(screen.getByRole("button", { name: "Preview & diff" })); + + await waitFor(() => { + expect(screen.getByText(/Decision action changes from accept to aggregate/i)).toBeTruthy(); + expect(screen.getByLabelText("Redacted sample event")).toBeTruthy(); + }); + }); +}); diff --git a/ui/Bower.Management.Web/src/pages/PoliciesPage.tsx b/ui/Bower.Management.Web/src/pages/PoliciesPage.tsx new file mode 100644 index 00000000..2172f896 --- /dev/null +++ b/ui/Bower.Management.Web/src/pages/PoliciesPage.tsx @@ -0,0 +1,417 @@ +import { ShieldCheck } from "lucide-react"; +import { useEffect, useState } from "react"; +import { useApi } from "../api"; +import { CopyButton } from "../components/SourcePlanView"; +import { Page, ResourceState } from "../components/ui"; +import { useResource } from "../hooks/useResource"; +import { DiffView } from "./PrivacyProfileVersionPanel"; + +interface PolicyTemplateItem { + id: string; + title: string; + description: string; + content: string; +} + +interface PolicySuppressionForm { + enabled: boolean; + keyFields: string[]; + windowSeconds: number; + allowPerWindow: number; +} + +interface PolicyForm { + id: string; + name: string; + version: string; + owner: string; + eventCategories: string[]; + eventTypes: string[]; + requiredFields: string[]; + atLeastOne: string[]; + recommendedFields: string[]; + action: string; + minimumValueScore: number; + neverSample: boolean; + suppression: PolicySuppressionForm | null; +} + +interface PolicyFormResult { + form: PolicyForm; + content: string; + valid: boolean; + errors: string[]; + policyHash: string | null; + diff: { + beforeHash: string; + afterHash: string; + semanticallyIdentical: boolean; + changes: { change: string; detail: string }[]; + } | null; + preview: { + valid: boolean; + beforeDecision: string; + afterDecision: string; + valueScore: number; + redactedEventJson: string | null; + findings: { detectorId: string; action: string; path: string }[]; + } | null; +} + +const decisionOptions = [ + { value: "accept", label: "Accept — keep and deliver matching events" }, + { value: "redact-and-accept", label: "Redact and accept — require redaction before delivery" }, + { value: "aggregate", label: "Aggregate — summarise floods into window counts" }, + { value: "quarantine", label: "Quarantine — set aside for review instead of delivering" }, + { value: "reject", label: "Reject — drop matching events" } +]; + +export function PoliciesPage() { + const api = useApi(); + const templates = useResource("/api/policies/templates"); + const [selectedTemplateId, setSelectedTemplateId] = useState(""); + const [baselineContent, setBaselineContent] = useState(""); + const [form, setForm] = useState(null); + const [result, setResult] = useState(null); + const [busy, setBusy] = useState(false); + const [error, setError] = useState(null); + + useEffect(() => { + const first = templates.data?.[0]; + if (first && !selectedTemplateId) { + setSelectedTemplateId(first.id); + setBaselineContent(first.content); + } + }, [templates.data, selectedTemplateId]); + + useEffect(() => { + if (!baselineContent) return; + let active = true; + setBusy(true); + setError(null); + api("/api/policies/form", { + method: "POST", + body: JSON.stringify({ content: baselineContent, form: null }) + }) + .then((loaded) => { + if (active) { + setForm(loaded.form); + setResult(loaded); + } + }) + .catch((err) => { + if (active) setError(err instanceof Error ? err.message : "Could not load policy."); + }) + .finally(() => { + if (active) setBusy(false); + }); + return () => { + active = false; + }; + }, [api, baselineContent]); + + async function previewChanges() { + if (!form || !baselineContent) return; + setBusy(true); + setError(null); + try { + const next = await api("/api/policies/form", { + method: "POST", + body: JSON.stringify({ content: baselineContent, form }) + }); + setResult(next); + if (next.valid) { + setForm(next.form); + } + } catch (err) { + setError(err instanceof Error ? err.message : "Policy check failed."); + } finally { + setBusy(false); + } + } + + function updateAction(action: string) { + if (!form) return; + const isAggregate = action === "aggregate"; + setForm({ + ...form, + action, + neverSample: isAggregate ? false : form.neverSample, + suppression: isAggregate + ? { + enabled: true, + keyFields: form.suppression?.keyFields.length + ? form.suppression.keyFields + : ["application.name", "eventType", "source.ipAddress"], + windowSeconds: form.suppression?.windowSeconds || 60, + allowPerWindow: form.suppression?.allowPerWindow ?? 0 + } + : form.suppression + }); + } + + return ( + + {error && ( +
+ {error} +
+ )} + + + {(items) => ( +
+
+

+

+ Validated with the collector's PolicyLoader +
+
+ + + + {form && ( +
{ + event.preventDefault(); + void previewChanges(); + }} + > + + setForm({ ...form, id: event.target.value })} + /> + + + setForm({ ...form, version: event.target.value })} + /> + + + + setForm({ + ...form, + eventTypes: event.target.value + .split(",") + .map((value) => value.trim()) + .filter(Boolean) + }) + } + /> + + + + + + + setForm({ ...form, minimumValueScore: Number(event.target.value) }) + } + /> + + + + {form.suppression?.enabled && ( +
+ Suppression & aggregation window + + + setForm({ + ...form, + suppression: { + ...form.suppression!, + keyFields: event.target.value + .split(",") + .map((value) => value.trim()) + .filter(Boolean) + } + }) + } + /> + + + setForm({ + ...form, + suppression: { + ...form.suppression!, + windowSeconds: Number(event.target.value) + } + }) + } + /> + + + setForm({ + ...form, + suppression: { + ...form.suppression!, + allowPerWindow: Number(event.target.value) + } + }) + } + /> +
+ )} + +
+ +
+
+ )} + + {result && ( +
+ {!result.valid && ( +
+ {result.errors.join(" ")} +
+ )} + + {result.preview && ( +
+

Sample preview (post-redaction only)

+

+ Before decision: {result.preview.beforeDecision} → After decision:{" "} + {result.preview.afterDecision} (value score {result.preview.valueScore}). +

+ {result.preview.redactedEventJson && ( +
+                          {JSON.stringify(JSON.parse(result.preview.redactedEventJson), null, 2)}
+                        
+ )} +
+ )} + + {result.diff && ( +
+

Population diff

+

+ Hash: {result.diff.beforeHash.slice(0, 18)} →{" "} + {result.diff.afterHash.slice(0, 18)}{" "} + {result.diff.semanticallyIdentical && "(identical semantics)"} +

+ {result.diff.changes.length === 0 ? ( +

No semantic policy changes yet.

+ ) : ( +
    + {result.diff.changes.map((entry, idx) => ( +
  • + {entry.change}: {entry.detail} +
  • + ))} +
+ )} +
+ )} + +
+

Generated YAML diff

+ +
+ Generated TelemetryPolicy YAML +
+                        {result.content}
+                      
+ +
+
+
+ )} +
+
+ )} +
+
+ ); +}