save progress
This commit is contained in:
@@ -5,9 +5,11 @@ using System.Threading.Tasks;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using Microsoft.AspNetCore.Routing;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using Microsoft.Extensions.Options;
|
||||
using StellaOps.Aoc;
|
||||
using StellaOps.Aoc.AspNetCore.Results;
|
||||
using HttpResults = Microsoft.AspNetCore.Http.Results;
|
||||
|
||||
namespace StellaOps.Aoc.AspNetCore.Routing;
|
||||
|
||||
@@ -34,37 +36,57 @@ public sealed class AocGuardEndpointFilter<TRequest> : IEndpointFilter
|
||||
throw new ArgumentNullException(nameof(context));
|
||||
}
|
||||
|
||||
if (TryGetArgument(context, out var request))
|
||||
if (!TryGetArgument(context, out var request))
|
||||
{
|
||||
var payloads = _payloadSelector(request);
|
||||
if (payloads is not null)
|
||||
var logger = context.HttpContext.RequestServices.GetService<ILogger<AocGuardEndpointFilter<TRequest>>>();
|
||||
logger?.LogWarning("AOC guard filter did not find request argument of type {RequestType}.", typeof(TRequest).FullName);
|
||||
return HttpResults.Problem(
|
||||
statusCode: StatusCodes.Status400BadRequest,
|
||||
title: "AOC guard payload missing",
|
||||
detail: $"Request payload of type {typeof(TRequest).Name} was not found.");
|
||||
}
|
||||
|
||||
IEnumerable<object?> payloads;
|
||||
try
|
||||
{
|
||||
payloads = _payloadSelector(request) ?? Array.Empty<object?>();
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
var logger = context.HttpContext.RequestServices.GetService<ILogger<AocGuardEndpointFilter<TRequest>>>();
|
||||
logger?.LogError(ex, "AOC guard payload selector failed for {RequestType}.", typeof(TRequest).FullName);
|
||||
return HttpResults.Problem(
|
||||
statusCode: StatusCodes.Status400BadRequest,
|
||||
title: "AOC guard payload selector failed",
|
||||
detail: "Request payload could not be extracted for validation.");
|
||||
}
|
||||
|
||||
var guard = context.HttpContext.RequestServices.GetRequiredService<IAocGuard>();
|
||||
var options = ResolveOptions(context.HttpContext.RequestServices);
|
||||
|
||||
foreach (var payload in payloads)
|
||||
{
|
||||
if (payload is null)
|
||||
{
|
||||
var guard = context.HttpContext.RequestServices.GetRequiredService<IAocGuard>();
|
||||
var options = ResolveOptions(context.HttpContext.RequestServices);
|
||||
continue;
|
||||
}
|
||||
|
||||
foreach (var payload in payloads)
|
||||
{
|
||||
if (payload is null)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
JsonElement element = payload switch
|
||||
{
|
||||
JsonElement jsonElement => jsonElement,
|
||||
JsonDocument jsonDocument => jsonDocument.RootElement,
|
||||
_ => JsonSerializer.SerializeToElement(payload, _serializerOptions)
|
||||
};
|
||||
|
||||
try
|
||||
{
|
||||
guard.ValidateOrThrow(element, options);
|
||||
}
|
||||
catch (AocGuardException exception)
|
||||
{
|
||||
return AocHttpResults.Problem(context.HttpContext, exception);
|
||||
}
|
||||
}
|
||||
try
|
||||
{
|
||||
ValidatePayload(payload, guard, options);
|
||||
}
|
||||
catch (AocGuardException exception)
|
||||
{
|
||||
return AocHttpResults.Problem(context.HttpContext, exception);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
var logger = context.HttpContext.RequestServices.GetService<ILogger<AocGuardEndpointFilter<TRequest>>>();
|
||||
logger?.LogError(ex, "AOC guard payload validation failed for {RequestType}.", typeof(TRequest).FullName);
|
||||
return HttpResults.Problem(
|
||||
statusCode: StatusCodes.Status400BadRequest,
|
||||
title: "AOC guard payload invalid",
|
||||
detail: "Request payload could not be serialized for validation.");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -96,4 +118,25 @@ public sealed class AocGuardEndpointFilter<TRequest> : IEndpointFilter
|
||||
argument = default!;
|
||||
return false;
|
||||
}
|
||||
|
||||
private void ValidatePayload(object payload, IAocGuard guard, AocGuardOptions options)
|
||||
{
|
||||
if (payload is JsonElement jsonElement)
|
||||
{
|
||||
guard.ValidateOrThrow(jsonElement, options);
|
||||
return;
|
||||
}
|
||||
|
||||
if (payload is JsonDocument jsonDocument)
|
||||
{
|
||||
using (jsonDocument)
|
||||
{
|
||||
guard.ValidateOrThrow(jsonDocument.RootElement, options);
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
var element = JsonSerializer.SerializeToElement(payload, _serializerOptions);
|
||||
guard.ValidateOrThrow(element, options);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -7,4 +7,4 @@ Source of truth: `docs/implplan/SPRINT_20251229_049_BE_csproj_audit_maint_tests.
|
||||
| --- | --- | --- |
|
||||
| AUDIT-0039-M | DONE | Maintainability audit for StellaOps.Aoc.AspNetCore. |
|
||||
| AUDIT-0039-T | DONE | Test coverage audit for StellaOps.Aoc.AspNetCore. |
|
||||
| AUDIT-0039-A | TODO | Pending approval for changes. |
|
||||
| AUDIT-0039-A | DONE | Hardened guard filter error handling and added tests. |
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
using System;
|
||||
using System.Collections.Immutable;
|
||||
using System.Linq;
|
||||
using System.Text.Json.Serialization;
|
||||
|
||||
namespace StellaOps.Aoc;
|
||||
@@ -20,9 +21,16 @@ public sealed record AocError(
|
||||
}
|
||||
|
||||
var violations = result.Violations;
|
||||
var code = violations.IsDefaultOrEmpty ? "ERR_AOC_000" : violations[0].ErrorCode;
|
||||
var orderedViolations = violations.IsDefaultOrEmpty
|
||||
? violations
|
||||
: violations
|
||||
.OrderBy(v => v.ErrorCode, StringComparer.Ordinal)
|
||||
.ThenBy(v => v.Path, StringComparer.Ordinal)
|
||||
.ThenBy(v => v.Message, StringComparer.Ordinal)
|
||||
.ToImmutableArray();
|
||||
var code = orderedViolations.IsDefaultOrEmpty ? "ERR_AOC_000" : orderedViolations[0].ErrorCode;
|
||||
var resolvedMessage = message ?? $"AOC guard rejected the payload with {code}.";
|
||||
return new(code, resolvedMessage, violations);
|
||||
return new(code, resolvedMessage, orderedViolations);
|
||||
}
|
||||
|
||||
public static AocError FromException(AocGuardException exception, string? message = null)
|
||||
|
||||
@@ -45,6 +45,12 @@ public sealed record AocGuardOptions
|
||||
/// </summary>
|
||||
public bool RequireSignatureMetadata { get; init; } = true;
|
||||
|
||||
/// <summary>
|
||||
/// Optional allowlist of signature formats. When empty, any format is accepted.
|
||||
/// </summary>
|
||||
public ImmutableHashSet<string> AllowedSignatureFormats { get; init; } =
|
||||
ImmutableHashSet<string>.Empty.WithComparer(StringComparer.OrdinalIgnoreCase);
|
||||
|
||||
/// <summary>
|
||||
/// When true, tenant must be a non-empty string.
|
||||
/// </summary>
|
||||
|
||||
@@ -26,9 +26,9 @@ public static class AocViolationCodeExtensions
|
||||
AocViolationCode.SignatureInvalid => "ERR_AOC_005",
|
||||
AocViolationCode.DerivedFindingDetected => "ERR_AOC_006",
|
||||
AocViolationCode.UnknownField => "ERR_AOC_007",
|
||||
AocViolationCode.MissingRequiredField => "ERR_AOC_004",
|
||||
AocViolationCode.InvalidTenant => "ERR_AOC_004",
|
||||
AocViolationCode.InvalidSignatureMetadata => "ERR_AOC_005",
|
||||
AocViolationCode.MissingRequiredField => "ERR_AOC_008",
|
||||
AocViolationCode.InvalidTenant => "ERR_AOC_009",
|
||||
AocViolationCode.InvalidSignatureMetadata => "ERR_AOC_010",
|
||||
_ => "ERR_AOC_000",
|
||||
};
|
||||
}
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
using System.Collections.Generic;
|
||||
using System.Collections.Immutable;
|
||||
using System.Linq;
|
||||
using System.Text.Json;
|
||||
|
||||
namespace StellaOps.Aoc;
|
||||
@@ -15,13 +16,12 @@ public sealed class AocWriteGuard : IAocGuard
|
||||
{
|
||||
options ??= AocGuardOptions.Default;
|
||||
var violations = ImmutableArray.CreateBuilder<AocViolation>();
|
||||
var presentTopLevel = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
|
||||
var allowedTopLevelFields = options.AllowedTopLevelFields ?? AocGuardOptions.Default.AllowedTopLevelFields;
|
||||
var requiredTopLevelFields = options.RequiredTopLevelFields ?? AocGuardOptions.Default.RequiredTopLevelFields;
|
||||
var allowedTopLevelFields = (options.AllowedTopLevelFields ?? AocGuardOptions.Default.AllowedTopLevelFields)
|
||||
.Union(requiredTopLevelFields);
|
||||
|
||||
foreach (var property in document.EnumerateObject())
|
||||
{
|
||||
presentTopLevel.Add(property.Name);
|
||||
|
||||
if (AocForbiddenKeys.IsForbiddenTopLevel(property.Name))
|
||||
{
|
||||
violations.Add(AocViolation.Create(AocViolationCode.ForbiddenField, $"/{property.Name}", $"Field '{property.Name}' is forbidden in AOC documents."));
|
||||
@@ -40,20 +40,27 @@ public sealed class AocWriteGuard : IAocGuard
|
||||
}
|
||||
}
|
||||
|
||||
foreach (var required in options.RequiredTopLevelFields)
|
||||
foreach (var required in requiredTopLevelFields.OrderBy(name => name, StringComparer.OrdinalIgnoreCase))
|
||||
{
|
||||
if (options.RequireTenant && string.Equals(required, "tenant", StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
if (!document.TryGetProperty(required, out var element) || element.ValueKind is JsonValueKind.Null or JsonValueKind.Undefined)
|
||||
{
|
||||
violations.Add(AocViolation.Create(AocViolationCode.MissingRequiredField, $"/{required}", $"Required field '{required}' is missing."));
|
||||
continue;
|
||||
}
|
||||
}
|
||||
|
||||
if (options.RequireTenant && string.Equals(required, "tenant", StringComparison.OrdinalIgnoreCase))
|
||||
if (options.RequireTenant)
|
||||
{
|
||||
if (!document.TryGetProperty("tenant", out var tenantElement) ||
|
||||
tenantElement.ValueKind != JsonValueKind.String ||
|
||||
string.IsNullOrWhiteSpace(tenantElement.GetString()))
|
||||
{
|
||||
if (element.ValueKind != JsonValueKind.String || string.IsNullOrWhiteSpace(element.GetString()))
|
||||
{
|
||||
violations.Add(AocViolation.Create(AocViolationCode.InvalidTenant, "/tenant", "Tenant must be a non-empty string."));
|
||||
}
|
||||
violations.Add(AocViolation.Create(AocViolationCode.InvalidTenant, "/tenant", "Tenant must be a non-empty string."));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -73,7 +80,7 @@ public sealed class AocWriteGuard : IAocGuard
|
||||
}
|
||||
else if (options.RequireSignatureMetadata)
|
||||
{
|
||||
ValidateSignature(signature, violations);
|
||||
ValidateSignature(signature, violations, options);
|
||||
}
|
||||
}
|
||||
else
|
||||
@@ -101,7 +108,7 @@ public sealed class AocWriteGuard : IAocGuard
|
||||
return AocGuardResult.FromViolations(violations);
|
||||
}
|
||||
|
||||
private static void ValidateSignature(JsonElement signature, ImmutableArray<AocViolation>.Builder violations)
|
||||
private static void ValidateSignature(JsonElement signature, ImmutableArray<AocViolation>.Builder violations, AocGuardOptions options)
|
||||
{
|
||||
if (!signature.TryGetProperty("present", out var presentElement) || presentElement.ValueKind is not (JsonValueKind.True or JsonValueKind.False))
|
||||
{
|
||||
@@ -113,22 +120,74 @@ public sealed class AocWriteGuard : IAocGuard
|
||||
|
||||
if (!signaturePresent)
|
||||
{
|
||||
return;
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
if (!signature.TryGetProperty("format", out var formatElement) || formatElement.ValueKind != JsonValueKind.String || string.IsNullOrWhiteSpace(formatElement.GetString()))
|
||||
if (!signature.TryGetProperty("format", out var formatElement) || formatElement.ValueKind != JsonValueKind.String || string.IsNullOrWhiteSpace(formatElement.GetString()))
|
||||
{
|
||||
violations.Add(AocViolation.Create(AocViolationCode.InvalidSignatureMetadata, "/upstream/signature/format", "Signature format is required when signature is present."));
|
||||
}
|
||||
else
|
||||
{
|
||||
var format = formatElement.GetString()!.Trim();
|
||||
if (options.AllowedSignatureFormats.Count > 0 &&
|
||||
!options.AllowedSignatureFormats.Contains(format))
|
||||
{
|
||||
violations.Add(AocViolation.Create(AocViolationCode.InvalidSignatureMetadata, "/upstream/signature/format", "Signature format is required when signature is present."));
|
||||
violations.Add(AocViolation.Create(AocViolationCode.InvalidSignatureMetadata, "/upstream/signature/format", $"Signature format '{format}' is not permitted."));
|
||||
}
|
||||
}
|
||||
|
||||
if (!signature.TryGetProperty("sig", out var sigElement) || sigElement.ValueKind != JsonValueKind.String || string.IsNullOrWhiteSpace(sigElement.GetString()))
|
||||
{
|
||||
violations.Add(AocViolation.Create(AocViolationCode.SignatureInvalid, "/upstream/signature/sig", "Signature payload is required when signature is present."));
|
||||
}
|
||||
else if (!IsBase64Payload(sigElement.GetString()!))
|
||||
{
|
||||
violations.Add(AocViolation.Create(AocViolationCode.InvalidSignatureMetadata, "/upstream/signature/sig", "Signature payload must be base64 or base64url encoded."));
|
||||
}
|
||||
|
||||
if (!signature.TryGetProperty("key_id", out var keyIdElement) || keyIdElement.ValueKind != JsonValueKind.String || string.IsNullOrWhiteSpace(keyIdElement.GetString()))
|
||||
{
|
||||
violations.Add(AocViolation.Create(AocViolationCode.InvalidSignatureMetadata, "/upstream/signature/key_id", "Signature key identifier is required when signature is present."));
|
||||
}
|
||||
}
|
||||
|
||||
private static bool IsBase64Payload(string value)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(value))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
if (TryDecodeBase64(value))
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
var normalized = value.Replace('-', '+').Replace('_', '/');
|
||||
switch (normalized.Length % 4)
|
||||
{
|
||||
case 2:
|
||||
normalized += "==";
|
||||
break;
|
||||
case 3:
|
||||
normalized += "=";
|
||||
break;
|
||||
}
|
||||
|
||||
return TryDecodeBase64(normalized);
|
||||
}
|
||||
|
||||
private static bool TryDecodeBase64(string value)
|
||||
{
|
||||
try
|
||||
{
|
||||
Convert.FromBase64String(value);
|
||||
return true;
|
||||
}
|
||||
catch (FormatException)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
<LangVersion>preview</LangVersion>
|
||||
<ImplicitUsings>enable</ImplicitUsings>
|
||||
<Nullable>enable</Nullable>
|
||||
<TreatWarningsAsErrors>false</TreatWarningsAsErrors>
|
||||
<TreatWarningsAsErrors>true</TreatWarningsAsErrors>
|
||||
</PropertyGroup>
|
||||
<ItemGroup>
|
||||
<PackageReference Include="Microsoft.Extensions.DependencyInjection.Abstractions" />
|
||||
|
||||
@@ -7,4 +7,4 @@ Source of truth: `docs/implplan/SPRINT_20251229_049_BE_csproj_audit_maint_tests.
|
||||
| --- | --- | --- |
|
||||
| AUDIT-0036-M | DONE | Maintainability audit for StellaOps.Aoc. |
|
||||
| AUDIT-0036-T | DONE | Test coverage audit for StellaOps.Aoc. |
|
||||
| AUDIT-0036-A | TODO | Pending approval for changes. |
|
||||
| AUDIT-0036-A | DONE | Applied error code fixes, deterministic ordering, and guard validation hardening. |
|
||||
|
||||
Reference in New Issue
Block a user