save progress
This commit is contained in:
@@ -20,6 +20,9 @@ public sealed class AocForbiddenFieldAnalyzer : DiagnosticAnalyzer
|
||||
public const string DiagnosticIdForbiddenField = "AOC0001";
|
||||
public const string DiagnosticIdDerivedField = "AOC0002";
|
||||
public const string DiagnosticIdUnguardedWrite = "AOC0003";
|
||||
private const string IngestionAllOption = "stellaops_aoc_ingestion";
|
||||
private const string IngestionAssemblyOption = "stellaops_aoc_ingestion_assemblies";
|
||||
private const string IngestionNamespaceOption = "stellaops_aoc_ingestion_namespace_prefixes";
|
||||
|
||||
private static readonly ImmutableHashSet<string> ForbiddenTopLevel = ImmutableHashSet.Create(
|
||||
StringComparer.OrdinalIgnoreCase,
|
||||
@@ -72,21 +75,25 @@ public sealed class AocForbiddenFieldAnalyzer : DiagnosticAnalyzer
|
||||
context.ConfigureGeneratedCodeAnalysis(GeneratedCodeAnalysisFlags.None);
|
||||
context.EnableConcurrentExecution();
|
||||
|
||||
context.RegisterOperationAction(AnalyzeAssignment, OperationKind.SimpleAssignment);
|
||||
context.RegisterOperationAction(AnalyzePropertyReference, OperationKind.PropertyReference);
|
||||
context.RegisterOperationAction(AnalyzeInvocation, OperationKind.Invocation);
|
||||
context.RegisterSyntaxNodeAction(AnalyzeObjectInitializer, SyntaxKind.ObjectInitializerExpression);
|
||||
context.RegisterSyntaxNodeAction(AnalyzeAnonymousObjectMember, SyntaxKind.AnonymousObjectMemberDeclarator);
|
||||
context.RegisterCompilationStartAction(startContext =>
|
||||
{
|
||||
var symbols = new AnalyzerTypeSymbols(startContext.Compilation);
|
||||
startContext.RegisterOperationAction(ctx => AnalyzeAssignment(ctx, symbols), OperationKind.SimpleAssignment);
|
||||
startContext.RegisterOperationAction(ctx => AnalyzePropertyReference(ctx, symbols), OperationKind.PropertyReference);
|
||||
startContext.RegisterOperationAction(ctx => AnalyzeInvocation(ctx, symbols), OperationKind.Invocation);
|
||||
startContext.RegisterSyntaxNodeAction(ctx => AnalyzeObjectInitializer(ctx, symbols), SyntaxKind.ObjectInitializerExpression);
|
||||
startContext.RegisterSyntaxNodeAction(ctx => AnalyzeAnonymousObjectMember(ctx, symbols), SyntaxKind.AnonymousObjectMemberDeclarator);
|
||||
});
|
||||
}
|
||||
|
||||
private static void AnalyzeAssignment(OperationAnalysisContext context)
|
||||
private static void AnalyzeAssignment(OperationAnalysisContext context, AnalyzerTypeSymbols symbols)
|
||||
{
|
||||
if (context.Operation is not ISimpleAssignmentOperation assignment)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
if (!IsIngestionContext(context.ContainingSymbol))
|
||||
if (!IsIngestionContext(context.ContainingSymbol, context.Options, symbols))
|
||||
{
|
||||
return;
|
||||
}
|
||||
@@ -100,14 +107,14 @@ public sealed class AocForbiddenFieldAnalyzer : DiagnosticAnalyzer
|
||||
CheckForbiddenField(context, targetName!, assignment.Syntax.GetLocation());
|
||||
}
|
||||
|
||||
private static void AnalyzePropertyReference(OperationAnalysisContext context)
|
||||
private static void AnalyzePropertyReference(OperationAnalysisContext context, AnalyzerTypeSymbols symbols)
|
||||
{
|
||||
if (context.Operation is not IPropertyReferenceOperation propertyRef)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
if (!IsIngestionContext(context.ContainingSymbol))
|
||||
if (!IsIngestionContext(context.ContainingSymbol, context.Options, symbols))
|
||||
{
|
||||
return;
|
||||
}
|
||||
@@ -121,14 +128,14 @@ public sealed class AocForbiddenFieldAnalyzer : DiagnosticAnalyzer
|
||||
CheckForbiddenField(context, propertyName, propertyRef.Syntax.GetLocation());
|
||||
}
|
||||
|
||||
private static void AnalyzeInvocation(OperationAnalysisContext context)
|
||||
private static void AnalyzeInvocation(OperationAnalysisContext context, AnalyzerTypeSymbols symbols)
|
||||
{
|
||||
if (context.Operation is not IInvocationOperation invocation)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
if (!IsIngestionContext(context.ContainingSymbol))
|
||||
if (!IsIngestionContext(context.ContainingSymbol, context.Options, symbols))
|
||||
{
|
||||
return;
|
||||
}
|
||||
@@ -144,9 +151,9 @@ public sealed class AocForbiddenFieldAnalyzer : DiagnosticAnalyzer
|
||||
}
|
||||
|
||||
// Check for unguarded database write operations
|
||||
if (IsDatabaseWriteOperation(method))
|
||||
if (IsDatabaseWriteOperation(method, symbols))
|
||||
{
|
||||
if (!IsWithinAocGuardScope(invocation))
|
||||
if (!IsWithinAocGuardScope(invocation, symbols))
|
||||
{
|
||||
var diagnostic = Diagnostic.Create(
|
||||
UnguardedWriteRule,
|
||||
@@ -157,11 +164,11 @@ public sealed class AocForbiddenFieldAnalyzer : DiagnosticAnalyzer
|
||||
}
|
||||
}
|
||||
|
||||
private static void AnalyzeObjectInitializer(SyntaxNodeAnalysisContext context)
|
||||
private static void AnalyzeObjectInitializer(SyntaxNodeAnalysisContext context, AnalyzerTypeSymbols symbols)
|
||||
{
|
||||
var initializer = (InitializerExpressionSyntax)context.Node;
|
||||
|
||||
if (!IsIngestionContext(context.ContainingSymbol))
|
||||
if (!IsIngestionContext(context.ContainingSymbol, context.Options, symbols))
|
||||
{
|
||||
return;
|
||||
}
|
||||
@@ -185,11 +192,11 @@ public sealed class AocForbiddenFieldAnalyzer : DiagnosticAnalyzer
|
||||
}
|
||||
}
|
||||
|
||||
private static void AnalyzeAnonymousObjectMember(SyntaxNodeAnalysisContext context)
|
||||
private static void AnalyzeAnonymousObjectMember(SyntaxNodeAnalysisContext context, AnalyzerTypeSymbols symbols)
|
||||
{
|
||||
var member = (AnonymousObjectMemberDeclaratorSyntax)context.Node;
|
||||
|
||||
if (!IsIngestionContext(context.ContainingSymbol))
|
||||
if (!IsIngestionContext(context.ContainingSymbol, context.Options, symbols))
|
||||
{
|
||||
return;
|
||||
}
|
||||
@@ -265,7 +272,7 @@ public sealed class AocForbiddenFieldAnalyzer : DiagnosticAnalyzer
|
||||
return parent is ISimpleAssignmentOperation assignment && assignment.Target == propertyRef;
|
||||
}
|
||||
|
||||
private static bool IsIngestionContext(ISymbol? containingSymbol)
|
||||
private static bool IsIngestionContext(ISymbol? containingSymbol, AnalyzerOptions options, AnalyzerTypeSymbols symbols)
|
||||
{
|
||||
if (containingSymbol is null)
|
||||
{
|
||||
@@ -280,11 +287,30 @@ public sealed class AocForbiddenFieldAnalyzer : DiagnosticAnalyzer
|
||||
|
||||
// Allow analyzer assemblies and tests
|
||||
if (assemblyName!.EndsWith(".Analyzers", StringComparison.Ordinal) ||
|
||||
assemblyName.EndsWith(".Tests", StringComparison.Ordinal))
|
||||
assemblyName.EndsWith(".Tests", StringComparison.Ordinal) ||
|
||||
assemblyName.EndsWith(".Test", StringComparison.Ordinal) ||
|
||||
assemblyName.EndsWith(".Testing", StringComparison.Ordinal))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
if (HasIngestionMarker(containingSymbol) ||
|
||||
HasIngestionMarker(containingSymbol.ContainingType) ||
|
||||
HasIngestionMarker(containingSymbol.ContainingAssembly))
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
if (IsConfigIngestionAssembly(assemblyName, options))
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
if (IsConfigIngestionNamespace(containingSymbol.ContainingNamespace?.ToDisplayString(), options))
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
// Check for ingestion-related assemblies/namespaces
|
||||
if (assemblyName.Contains(".Connector.", StringComparison.Ordinal) ||
|
||||
assemblyName.Contains(".Ingestion", StringComparison.Ordinal) ||
|
||||
@@ -307,6 +333,112 @@ public sealed class AocForbiddenFieldAnalyzer : DiagnosticAnalyzer
|
||||
return false;
|
||||
}
|
||||
|
||||
private static bool HasIngestionMarker(ISymbol? symbol)
|
||||
{
|
||||
if (symbol is null)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
foreach (var attribute in symbol.GetAttributes())
|
||||
{
|
||||
var attributeName = attribute.AttributeClass?.Name;
|
||||
if (string.Equals(attributeName, "AocIngestionAttribute", StringComparison.Ordinal) ||
|
||||
string.Equals(attributeName, "AocIngestionContextAttribute", StringComparison.Ordinal))
|
||||
{
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
private static bool IsConfigIngestionAssembly(string assemblyName, AnalyzerOptions options)
|
||||
{
|
||||
if (IsConfigIngestionEnabledForAll(options))
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
if (TryGetOption(options, IngestionAssemblyOption, out var assemblies) ||
|
||||
TryGetOption(options, "build_property.StellaOpsAocIngestionAssemblies", out assemblies))
|
||||
{
|
||||
foreach (var name in SplitOptionValue(assemblies))
|
||||
{
|
||||
if (string.Equals(name, "*", StringComparison.Ordinal) ||
|
||||
string.Equals(name, "all", StringComparison.OrdinalIgnoreCase) ||
|
||||
string.Equals(name, assemblyName, StringComparison.Ordinal))
|
||||
{
|
||||
return true;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
private static bool IsConfigIngestionNamespace(string? ns, AnalyzerOptions options)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(ns))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
var namespaceValue = ns!;
|
||||
if (TryGetOption(options, IngestionNamespaceOption, out var namespaces) ||
|
||||
TryGetOption(options, "build_property.StellaOpsAocIngestionNamespacePrefixes", out namespaces))
|
||||
{
|
||||
foreach (var prefix in SplitOptionValue(namespaces))
|
||||
{
|
||||
if (namespaceValue.StartsWith(prefix, StringComparison.Ordinal))
|
||||
{
|
||||
return true;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
private static bool IsConfigIngestionEnabledForAll(AnalyzerOptions options)
|
||||
{
|
||||
if (TryGetOption(options, IngestionAllOption, out var value) ||
|
||||
TryGetOption(options, "build_property.StellaOpsAocIngestion", out value))
|
||||
{
|
||||
if (string.Equals(value, "true", StringComparison.OrdinalIgnoreCase) ||
|
||||
string.Equals(value, "all", StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
private static bool TryGetOption(AnalyzerOptions options, string key, out string value)
|
||||
{
|
||||
value = string.Empty;
|
||||
if (!options.AnalyzerConfigOptionsProvider.GlobalOptions.TryGetValue(key, out var raw) || string.IsNullOrWhiteSpace(raw))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
value = raw.Trim();
|
||||
return value.Length > 0;
|
||||
}
|
||||
|
||||
private static IEnumerable<string> SplitOptionValue(string value)
|
||||
{
|
||||
foreach (var entry in value.Split(new[] { ';', ',', ' ' }, StringSplitOptions.RemoveEmptyEntries))
|
||||
{
|
||||
var trimmed = entry.Trim();
|
||||
if (!string.IsNullOrEmpty(trimmed))
|
||||
{
|
||||
yield return trimmed;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static bool IsDictionarySetOperation(IMethodSymbol method)
|
||||
{
|
||||
var name = method.Name;
|
||||
@@ -331,35 +463,54 @@ public sealed class AocForbiddenFieldAnalyzer : DiagnosticAnalyzer
|
||||
typeName.Contains("JsonElement", StringComparison.Ordinal);
|
||||
}
|
||||
|
||||
private static bool IsDatabaseWriteOperation(IMethodSymbol method)
|
||||
private static bool IsDatabaseWriteOperation(IMethodSymbol method, AnalyzerTypeSymbols symbols)
|
||||
{
|
||||
var name = method.Name;
|
||||
var writeOps = new[]
|
||||
if ((string.Equals(name, "SaveChanges", StringComparison.Ordinal) ||
|
||||
string.Equals(name, "SaveChangesAsync", StringComparison.Ordinal)) &&
|
||||
IsOnTypeOrDerived(method.ContainingType, symbols.DbContext))
|
||||
{
|
||||
"InsertOne", "InsertOneAsync",
|
||||
"InsertMany", "InsertManyAsync",
|
||||
"UpdateOne", "UpdateOneAsync",
|
||||
"UpdateMany", "UpdateManyAsync",
|
||||
"ReplaceOne", "ReplaceOneAsync",
|
||||
"BulkWrite", "BulkWriteAsync",
|
||||
"ExecuteNonQuery", "ExecuteNonQueryAsync",
|
||||
"SaveChanges", "SaveChangesAsync",
|
||||
"Add", "AddAsync",
|
||||
"Update", "UpdateAsync"
|
||||
};
|
||||
return true;
|
||||
}
|
||||
|
||||
foreach (var op in writeOps)
|
||||
if ((string.Equals(name, "Add", StringComparison.Ordinal) ||
|
||||
string.Equals(name, "AddAsync", StringComparison.Ordinal) ||
|
||||
string.Equals(name, "Update", StringComparison.Ordinal) ||
|
||||
string.Equals(name, "UpdateAsync", StringComparison.Ordinal)) &&
|
||||
IsOnTypeOrDerived(method.ContainingType, symbols.DbSet))
|
||||
{
|
||||
if (string.Equals(name, op, StringComparison.Ordinal))
|
||||
{
|
||||
return true;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
if ((string.Equals(name, "ExecuteNonQuery", StringComparison.Ordinal) ||
|
||||
string.Equals(name, "ExecuteNonQueryAsync", StringComparison.Ordinal)) &&
|
||||
(IsOnTypeOrDerived(method.ContainingType, symbols.DbCommand) ||
|
||||
IsOnTypeOrDerived(method.ContainingType, symbols.NpgsqlCommand)))
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
if ((string.Equals(name, "InsertOne", StringComparison.Ordinal) ||
|
||||
string.Equals(name, "InsertOneAsync", StringComparison.Ordinal) ||
|
||||
string.Equals(name, "InsertMany", StringComparison.Ordinal) ||
|
||||
string.Equals(name, "InsertManyAsync", StringComparison.Ordinal) ||
|
||||
string.Equals(name, "UpdateOne", StringComparison.Ordinal) ||
|
||||
string.Equals(name, "UpdateOneAsync", StringComparison.Ordinal) ||
|
||||
string.Equals(name, "UpdateMany", StringComparison.Ordinal) ||
|
||||
string.Equals(name, "UpdateManyAsync", StringComparison.Ordinal) ||
|
||||
string.Equals(name, "ReplaceOne", StringComparison.Ordinal) ||
|
||||
string.Equals(name, "ReplaceOneAsync", StringComparison.Ordinal) ||
|
||||
string.Equals(name, "BulkWrite", StringComparison.Ordinal) ||
|
||||
string.Equals(name, "BulkWriteAsync", StringComparison.Ordinal)) &&
|
||||
IsOnTypeOrDerived(method.ContainingType, symbols.MongoCollection))
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
private static bool IsWithinAocGuardScope(IInvocationOperation invocation)
|
||||
private static bool IsWithinAocGuardScope(IInvocationOperation invocation, AnalyzerTypeSymbols symbols)
|
||||
{
|
||||
// Walk up the operation tree to find if we're within an AOC guard validation scope
|
||||
var current = invocation.Parent;
|
||||
@@ -371,8 +522,8 @@ public sealed class AocForbiddenFieldAnalyzer : DiagnosticAnalyzer
|
||||
if (current is IInvocationOperation parentInvocation)
|
||||
{
|
||||
var method = parentInvocation.TargetMethod;
|
||||
if (method.Name == "Validate" &&
|
||||
method.ContainingType?.Name.Contains("AocGuard", StringComparison.Ordinal) == true)
|
||||
if ((method.Name == "Validate" || method.Name == "ValidateOrThrow") &&
|
||||
IsAocGuardInvocation(method, symbols))
|
||||
{
|
||||
return true;
|
||||
}
|
||||
@@ -387,7 +538,7 @@ public sealed class AocForbiddenFieldAnalyzer : DiagnosticAnalyzer
|
||||
{
|
||||
foreach (var param in containingMethod.Parameters)
|
||||
{
|
||||
if (param.Type.Name.Contains("AocGuard", StringComparison.Ordinal))
|
||||
if (IsAocGuardType(param.Type, symbols))
|
||||
{
|
||||
return true;
|
||||
}
|
||||
@@ -401,4 +552,80 @@ public sealed class AocForbiddenFieldAnalyzer : DiagnosticAnalyzer
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
private static bool IsOnTypeOrDerived(INamedTypeSymbol? type, INamedTypeSymbol? expected)
|
||||
{
|
||||
if (type is null || expected is null)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
for (var current = type; current is not null; current = current.BaseType)
|
||||
{
|
||||
if (SymbolEqualityComparer.Default.Equals(current, expected))
|
||||
{
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
foreach (var iface in type.AllInterfaces)
|
||||
{
|
||||
if (SymbolEqualityComparer.Default.Equals(iface, expected))
|
||||
{
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
private static bool IsAocGuardType(ITypeSymbol? type, AnalyzerTypeSymbols symbols)
|
||||
{
|
||||
if (type is null)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
if (symbols.AocGuard is not null && IsOnTypeOrDerived(type as INamedTypeSymbol, symbols.AocGuard))
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
return type.Name.Contains("AocGuard", StringComparison.Ordinal);
|
||||
}
|
||||
|
||||
private static bool IsAocGuardInvocation(IMethodSymbol method, AnalyzerTypeSymbols symbols)
|
||||
{
|
||||
if (IsAocGuardType(method.ContainingType, symbols))
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
if (method.IsExtensionMethod && method.Parameters.Length > 0)
|
||||
{
|
||||
return IsAocGuardType(method.Parameters[0].Type, symbols);
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
private sealed class AnalyzerTypeSymbols
|
||||
{
|
||||
public AnalyzerTypeSymbols(Compilation compilation)
|
||||
{
|
||||
AocGuard = compilation.GetTypeByMetadataName("StellaOps.Aoc.IAocGuard");
|
||||
DbContext = compilation.GetTypeByMetadataName("Microsoft.EntityFrameworkCore.DbContext");
|
||||
DbSet = compilation.GetTypeByMetadataName("Microsoft.EntityFrameworkCore.DbSet`1");
|
||||
DbCommand = compilation.GetTypeByMetadataName("System.Data.Common.DbCommand");
|
||||
NpgsqlCommand = compilation.GetTypeByMetadataName("Npgsql.NpgsqlCommand");
|
||||
MongoCollection = compilation.GetTypeByMetadataName("MongoDB.Driver.IMongoCollection`1");
|
||||
}
|
||||
|
||||
public INamedTypeSymbol? AocGuard { get; }
|
||||
public INamedTypeSymbol? DbContext { get; }
|
||||
public INamedTypeSymbol? DbSet { get; }
|
||||
public INamedTypeSymbol? DbCommand { get; }
|
||||
public INamedTypeSymbol? NpgsqlCommand { get; }
|
||||
public INamedTypeSymbol? MongoCollection { get; }
|
||||
}
|
||||
}
|
||||
|
||||
@@ -7,4 +7,4 @@ Source of truth: `docs/implplan/SPRINT_20251229_049_BE_csproj_audit_maint_tests.
|
||||
| --- | --- | --- |
|
||||
| AUDIT-0037-M | DONE | Maintainability audit for StellaOps.Aoc.Analyzers. |
|
||||
| AUDIT-0037-T | DONE | Test coverage audit for StellaOps.Aoc.Analyzers. |
|
||||
| AUDIT-0037-A | TODO | Pending approval for changes. |
|
||||
| AUDIT-0037-A | DONE | Applied ingestion markers, tighter DB detection, and guard-scope coverage. |
|
||||
|
||||
@@ -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. |
|
||||
|
||||
@@ -256,7 +256,7 @@ public sealed class AocForbiddenFieldAnalyzerTests
|
||||
|
||||
[Trait("Category", TestCategories.Unit)]
|
||||
[Fact]
|
||||
public async Task DoesNotReportDiagnostic_ForIngestionNamespaceButNotConnector()
|
||||
public async Task ReportsDiagnostic_ForIngestionNamespace()
|
||||
{
|
||||
const string source = """
|
||||
namespace StellaOps.Concelier.Ingestion;
|
||||
@@ -279,6 +279,166 @@ public sealed class AocForbiddenFieldAnalyzerTests
|
||||
Assert.Contains(diagnostics, d => d.Id == AocForbiddenFieldAnalyzer.DiagnosticIdForbiddenField);
|
||||
}
|
||||
|
||||
[Trait("Category", TestCategories.Unit)]
|
||||
[Theory]
|
||||
[InlineData("StellaOps.Concelier.Connector.Sample.Test")]
|
||||
[InlineData("StellaOps.Concelier.Connector.Sample.Testing")]
|
||||
public async Task DoesNotReportDiagnostic_ForTestAssemblySuffixes(string assemblyName)
|
||||
{
|
||||
const string source = """
|
||||
namespace StellaOps.Concelier.Connector.Sample;
|
||||
|
||||
public sealed class AdvisoryModel
|
||||
{
|
||||
public string? severity { get; set; }
|
||||
}
|
||||
|
||||
public sealed class IngesterTests
|
||||
{
|
||||
public void TestProcess()
|
||||
{
|
||||
var advisory = new AdvisoryModel { severity = "high" };
|
||||
}
|
||||
}
|
||||
""";
|
||||
|
||||
var diagnostics = await AnalyzeAsync(source, assemblyName);
|
||||
Assert.DoesNotContain(diagnostics, d => d.Id == AocForbiddenFieldAnalyzer.DiagnosticIdForbiddenField);
|
||||
}
|
||||
|
||||
[Trait("Category", TestCategories.Unit)]
|
||||
[Fact]
|
||||
public async Task ReportsDiagnostic_ForIngestionAttribute()
|
||||
{
|
||||
const string source = """
|
||||
using System;
|
||||
|
||||
namespace StellaOps.Aoc
|
||||
{
|
||||
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method | AttributeTargets.Assembly)]
|
||||
public sealed class AocIngestionAttribute : Attribute { }
|
||||
}
|
||||
|
||||
namespace StellaOps.Internal.Processing;
|
||||
|
||||
public sealed class AdvisoryModel
|
||||
{
|
||||
public string? severity { get; set; }
|
||||
}
|
||||
|
||||
[StellaOps.Aoc.AocIngestion]
|
||||
public sealed class Processor
|
||||
{
|
||||
public void Process(AdvisoryModel advisory)
|
||||
{
|
||||
advisory.severity = "high";
|
||||
}
|
||||
}
|
||||
""";
|
||||
|
||||
var diagnostics = await AnalyzeAsync(source, "StellaOps.Internal.Processing");
|
||||
Assert.Contains(diagnostics, d => d.Id == AocForbiddenFieldAnalyzer.DiagnosticIdForbiddenField);
|
||||
}
|
||||
|
||||
[Trait("Category", TestCategories.Unit)]
|
||||
[Fact]
|
||||
public async Task ReportsDiagnostic_ForDbContextSaveChangesWithoutGuard()
|
||||
{
|
||||
const string source = """
|
||||
namespace Microsoft.EntityFrameworkCore
|
||||
{
|
||||
public class DbContext
|
||||
{
|
||||
public int SaveChanges() => 0;
|
||||
}
|
||||
}
|
||||
|
||||
namespace StellaOps.Concelier.Connector.Sample;
|
||||
|
||||
public sealed class TestDbContext : Microsoft.EntityFrameworkCore.DbContext
|
||||
{
|
||||
}
|
||||
|
||||
public sealed class Ingester
|
||||
{
|
||||
public void Process()
|
||||
{
|
||||
var db = new TestDbContext();
|
||||
db.SaveChanges();
|
||||
}
|
||||
}
|
||||
""";
|
||||
|
||||
var diagnostics = await AnalyzeAsync(source, "StellaOps.Concelier.Connector.Sample");
|
||||
Assert.Contains(diagnostics, d => d.Id == AocForbiddenFieldAnalyzer.DiagnosticIdUnguardedWrite);
|
||||
}
|
||||
|
||||
[Trait("Category", TestCategories.Unit)]
|
||||
[Fact]
|
||||
public async Task DoesNotReportDiagnostic_ForNonDbAddMethod()
|
||||
{
|
||||
const string source = """
|
||||
namespace StellaOps.Concelier.Connector.Sample;
|
||||
|
||||
public sealed class CustomRepo
|
||||
{
|
||||
public void Add(object value) { }
|
||||
}
|
||||
|
||||
public sealed class Ingester
|
||||
{
|
||||
public void Process(CustomRepo repo)
|
||||
{
|
||||
repo.Add(new object());
|
||||
}
|
||||
}
|
||||
""";
|
||||
|
||||
var diagnostics = await AnalyzeAsync(source, "StellaOps.Concelier.Connector.Sample");
|
||||
Assert.DoesNotContain(diagnostics, d => d.Id == AocForbiddenFieldAnalyzer.DiagnosticIdUnguardedWrite);
|
||||
}
|
||||
|
||||
[Trait("Category", TestCategories.Unit)]
|
||||
[Fact]
|
||||
public async Task DoesNotReportDiagnostic_WhenGuardParameterPresent()
|
||||
{
|
||||
const string source = """
|
||||
namespace StellaOps.Aoc
|
||||
{
|
||||
public interface IAocGuard
|
||||
{
|
||||
void Validate(object doc);
|
||||
}
|
||||
}
|
||||
|
||||
namespace Microsoft.EntityFrameworkCore
|
||||
{
|
||||
public class DbContext
|
||||
{
|
||||
public int SaveChanges() => 0;
|
||||
}
|
||||
}
|
||||
|
||||
namespace StellaOps.Concelier.Connector.Sample;
|
||||
|
||||
public sealed class TestDbContext : Microsoft.EntityFrameworkCore.DbContext
|
||||
{
|
||||
}
|
||||
|
||||
public sealed class Ingester
|
||||
{
|
||||
public void Process(StellaOps.Aoc.IAocGuard guard)
|
||||
{
|
||||
var db = new TestDbContext();
|
||||
db.SaveChanges();
|
||||
}
|
||||
}
|
||||
""";
|
||||
|
||||
var diagnostics = await AnalyzeAsync(source, "StellaOps.Concelier.Connector.Sample");
|
||||
Assert.DoesNotContain(diagnostics, d => d.Id == AocForbiddenFieldAnalyzer.DiagnosticIdUnguardedWrite);
|
||||
}
|
||||
|
||||
private static async Task<ImmutableArray<Diagnostic>> AnalyzeAsync(string source, string assemblyName)
|
||||
{
|
||||
var compilation = CSharpCompilation.Create(
|
||||
|
||||
@@ -0,0 +1,138 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
using System.Text.Json;
|
||||
using System.Threading.Tasks;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using StellaOps.Aoc;
|
||||
using StellaOps.Aoc.AspNetCore.Routing;
|
||||
using StellaOps.TestKit;
|
||||
|
||||
namespace StellaOps.Aoc.AspNetCore.Tests;
|
||||
|
||||
public sealed class AocGuardEndpointFilterTests
|
||||
{
|
||||
[Trait("Category", TestCategories.Unit)]
|
||||
[Fact]
|
||||
public async Task ReturnsProblem_WhenRequestMissing()
|
||||
{
|
||||
var httpContext = BuildHttpContext(new TestAocGuard());
|
||||
var filter = new AocGuardEndpointFilter<GuardPayload>(_ => Array.Empty<object?>(), null, null);
|
||||
var context = new TestEndpointFilterInvocationContext(httpContext, Array.Empty<object?>());
|
||||
|
||||
var result = await filter.InvokeAsync(context, _ => new ValueTask<object?>(TypedResults.Ok()));
|
||||
|
||||
var status = await ExecuteAsync(result, httpContext);
|
||||
Assert.Equal(StatusCodes.Status400BadRequest, status);
|
||||
}
|
||||
|
||||
[Trait("Category", TestCategories.Unit)]
|
||||
[Fact]
|
||||
public async Task ReturnsProblem_WhenPayloadSelectorThrows()
|
||||
{
|
||||
var httpContext = BuildHttpContext(new TestAocGuard());
|
||||
var filter = new AocGuardEndpointFilter<GuardPayload>(_ => throw new InvalidOperationException("boom"), null, null);
|
||||
var context = new TestEndpointFilterInvocationContext(httpContext, new object?[] { new GuardPayload(new JsonElement()) });
|
||||
|
||||
var result = await filter.InvokeAsync(context, _ => new ValueTask<object?>(TypedResults.Ok()));
|
||||
|
||||
var status = await ExecuteAsync(result, httpContext);
|
||||
Assert.Equal(StatusCodes.Status400BadRequest, status);
|
||||
}
|
||||
|
||||
[Trait("Category", TestCategories.Unit)]
|
||||
[Fact]
|
||||
public async Task ReturnsProblem_WhenSerializationFails()
|
||||
{
|
||||
var httpContext = BuildHttpContext(new TestAocGuard());
|
||||
var filter = new AocGuardEndpointFilter<GuardPayload>(_ => new object?[] { new SelfReferencingPayload() }, null, null);
|
||||
var context = new TestEndpointFilterInvocationContext(httpContext, new object?[] { new GuardPayload(new JsonElement()) });
|
||||
|
||||
var result = await filter.InvokeAsync(context, _ => new ValueTask<object?>(TypedResults.Ok()));
|
||||
|
||||
var status = await ExecuteAsync(result, httpContext);
|
||||
Assert.Equal(StatusCodes.Status400BadRequest, status);
|
||||
}
|
||||
|
||||
[Trait("Category", TestCategories.Unit)]
|
||||
[Fact]
|
||||
public async Task ValidatesJsonDocumentPayloads()
|
||||
{
|
||||
var guard = new TestAocGuard();
|
||||
var httpContext = BuildHttpContext(guard);
|
||||
var filter = new AocGuardEndpointFilter<GuardPayload>(_ =>
|
||||
{
|
||||
using var doc = JsonDocument.Parse("""{"tenant":"default","source":{},"upstream":{"content_hash":"sha256:abc","signature":{"present":false}},"content":{"raw":{}},"linkset":{}}""");
|
||||
return new object?[] { JsonDocument.Parse(doc.RootElement.GetRawText()) };
|
||||
}, null, null);
|
||||
var context = new TestEndpointFilterInvocationContext(httpContext, new object?[] { new GuardPayload(new JsonElement()) });
|
||||
|
||||
var result = await filter.InvokeAsync(context, _ => new ValueTask<object?>(TypedResults.Ok()));
|
||||
|
||||
var status = await ExecuteAsync(result, httpContext);
|
||||
Assert.Equal(StatusCodes.Status200OK, status);
|
||||
Assert.True(guard.WasValidated);
|
||||
}
|
||||
|
||||
private static DefaultHttpContext BuildHttpContext(IAocGuard guard)
|
||||
{
|
||||
var services = new ServiceCollection();
|
||||
services.AddLogging();
|
||||
services.AddSingleton(guard);
|
||||
var provider = services.BuildServiceProvider();
|
||||
|
||||
return new DefaultHttpContext { RequestServices = provider, Response = { Body = new MemoryStream() } };
|
||||
}
|
||||
|
||||
private static async Task<int> ExecuteAsync(object? result, HttpContext context)
|
||||
{
|
||||
if (result is IResult httpResult)
|
||||
{
|
||||
await httpResult.ExecuteAsync(context);
|
||||
}
|
||||
|
||||
return context.Response.StatusCode;
|
||||
}
|
||||
|
||||
private sealed record GuardPayload(JsonElement Payload);
|
||||
|
||||
private sealed class SelfReferencingPayload
|
||||
{
|
||||
public SelfReferencingPayload? Self { get; set; }
|
||||
|
||||
public SelfReferencingPayload()
|
||||
{
|
||||
Self = this;
|
||||
}
|
||||
}
|
||||
|
||||
private sealed class TestAocGuard : IAocGuard
|
||||
{
|
||||
public bool WasValidated { get; private set; }
|
||||
|
||||
public AocGuardResult Validate(JsonElement document, AocGuardOptions? options = null)
|
||||
{
|
||||
WasValidated = true;
|
||||
return AocGuardResult.Success;
|
||||
}
|
||||
}
|
||||
|
||||
private sealed class TestEndpointFilterInvocationContext : EndpointFilterInvocationContext
|
||||
{
|
||||
private readonly HttpContext _httpContext;
|
||||
private readonly IList<object?> _arguments;
|
||||
|
||||
public TestEndpointFilterInvocationContext(HttpContext httpContext, IList<object?> arguments)
|
||||
{
|
||||
_httpContext = httpContext;
|
||||
_arguments = arguments;
|
||||
}
|
||||
|
||||
public override HttpContext HttpContext => _httpContext;
|
||||
|
||||
public override IList<object?> Arguments => _arguments;
|
||||
|
||||
public override T GetArgument<T>(int index) => (T)_arguments[index]!;
|
||||
}
|
||||
}
|
||||
@@ -40,17 +40,17 @@ public sealed class AocHttpResultsTests
|
||||
var root = document.RootElement;
|
||||
|
||||
// Assert
|
||||
Assert.Equal(StatusCodes.Status422UnprocessableEntity, context.Response.StatusCode);
|
||||
Assert.Equal(StatusCodes.Status400BadRequest, context.Response.StatusCode);
|
||||
Assert.Equal("Aggregation-Only Contract violation", root.GetProperty("title").GetString());
|
||||
Assert.Equal("ERR_AOC_004", root.GetProperty("code").GetString());
|
||||
Assert.Equal("ERR_AOC_001", root.GetProperty("code").GetString());
|
||||
|
||||
var violationsJson = root.GetProperty("violations");
|
||||
Assert.Equal(2, violationsJson.GetArrayLength());
|
||||
Assert.Equal("ERR_AOC_004", violationsJson[0].GetProperty("code").GetString());
|
||||
Assert.Equal("/upstream", violationsJson[0].GetProperty("path").GetString());
|
||||
Assert.Equal("ERR_AOC_001", violationsJson[0].GetProperty("code").GetString());
|
||||
Assert.Equal("/severity", violationsJson[0].GetProperty("path").GetString());
|
||||
|
||||
var errorJson = root.GetProperty("error");
|
||||
Assert.Equal("ERR_AOC_004", errorJson.GetProperty("code").GetString());
|
||||
Assert.Equal("ERR_AOC_001", errorJson.GetProperty("code").GetString());
|
||||
Assert.Equal(2, errorJson.GetProperty("violations").GetArrayLength());
|
||||
Assert.False(string.IsNullOrWhiteSpace(errorJson.GetProperty("message").GetString()));
|
||||
}
|
||||
|
||||
@@ -8,7 +8,7 @@ public sealed class AocErrorTests
|
||||
{
|
||||
[Trait("Category", TestCategories.Unit)]
|
||||
[Fact]
|
||||
public void FromResult_UsesFirstViolationCode()
|
||||
public void FromResult_UsesDeterministicViolationCode()
|
||||
{
|
||||
var violations = ImmutableArray.Create(
|
||||
AocViolation.Create(AocViolationCode.MissingProvenance, "/upstream", "Missing"),
|
||||
@@ -18,8 +18,8 @@ public sealed class AocErrorTests
|
||||
|
||||
var error = AocError.FromResult(result);
|
||||
|
||||
Assert.Equal("ERR_AOC_004", error.Code);
|
||||
Assert.Equal(violations, error.Violations);
|
||||
Assert.Equal("ERR_AOC_001", error.Code);
|
||||
Assert.Equal("ERR_AOC_001", error.Violations[0].ErrorCode);
|
||||
}
|
||||
|
||||
[Trait("Category", TestCategories.Unit)]
|
||||
|
||||
@@ -90,7 +90,7 @@ public sealed class AocWriteGuardTests
|
||||
var result = Guard.Validate(document.RootElement);
|
||||
|
||||
Assert.False(result.IsValid);
|
||||
Assert.Contains(result.Violations, v => v.ErrorCode == "ERR_AOC_004" && v.Path == "/tenant");
|
||||
Assert.Contains(result.Violations, v => v.ErrorCode == "ERR_AOC_009" && v.Path == "/tenant");
|
||||
}
|
||||
|
||||
[Trait("Category", TestCategories.Unit)]
|
||||
|
||||
Reference in New Issue
Block a user