< Summary

Information
Class: AsiBackbone.AspNetCore.CapabilityGrants.SignedCapabilityGrantEndpointValidator
Assembly: AsiBackbone.AspNetCore
File(s): /home/runner/work/AsiBackbone/AsiBackbone/src/AsiBackbone.AspNetCore/CapabilityGrants/SignedCapabilityGrantEndpointValidator.cs
Line coverage
98%
Covered lines: 141
Uncovered lines: 2
Coverable lines: 143
Total lines: 336
Line coverage: 98.6%
Branch coverage
81%
Covered branches: 52
Total branches: 64
Branch coverage: 81.2%
Method coverage

Feature is only available for sponsors

Upgrade to PRO version

Metrics

MethodBranch coverage Crap Score Cyclomatic complexity Line coverage
.cctor()100%11100%
.ctor(...)50%1212100%
ValidateAsync()90.91%2222100%
MapRejection(...)75%44100%
CreateValidationOptions(...)100%44100%
ResolveBindingAsync()100%22100%
ReadTokenAsync()85.71%141486.67%
ReadSingle(...)75%44100%
Deny(...)100%22100%
CreateDenial(...)100%11100%

File(s)

/home/runner/work/AsiBackbone/AsiBackbone/src/AsiBackbone.AspNetCore/CapabilityGrants/SignedCapabilityGrantEndpointValidator.cs

#LineLine coverage
 1using AsiBackbone.AspNetCore.Acknowledgments;
 2using AsiBackbone.AspNetCore.Actors;
 3using AsiBackbone.AspNetCore.Endpoints;
 4using AsiBackbone.Core.Actors;
 5using AsiBackbone.Core.CapabilityGrants;
 6using AsiBackbone.Core.Decisions;
 7using AsiBackbone.Core.Signing;
 8using Microsoft.AspNetCore.Http;
 9using Microsoft.Extensions.DependencyInjection;
 10using Microsoft.Extensions.Logging;
 11using Microsoft.Extensions.Logging.Abstractions;
 12using Microsoft.Extensions.Options;
 13using Microsoft.Extensions.Primitives;
 14
 15namespace AsiBackbone.AspNetCore.CapabilityGrants;
 16
 17/// <summary>
 18/// Opt-in <see cref="IEndpointCapabilityGrantValidator" /> that accepts only a signed, request-bound capability grant
 19/// carried as a <see cref="CapabilityGrantToken" />.
 20/// </summary>
 21/// <remarks>
 22/// <para>
 23/// For every decision that is not already denied, the validator reads the token from the request, decodes it, resolves
 24/// the request binding, and validates the grant with
 25/// <see cref="CapabilityGrantValidationOptions.CreateBoundExecutionBoundary" /> built from the authenticated actor, the
 26/// endpoint operation and scopes, the policy version and hash of the current decision, and the configured issuer and
 27/// audience. Proof verification is always required. A use is consumed for every outcome except acknowledgment-required:
 28/// that request is answered with a challenge and never executes, so its grant is verified but left for the acknowledged
 29/// retry, which is validated and consumed in turn.
 30/// </para>
 31/// <para>
 32/// Every result other than <see cref="CapabilityGrantValidationCategory.Valid" /> produces a denied decision with a
 33/// reason code from <see cref="SignedCapabilityGrantReasonCodes" />, whatever <see cref="VerificationPolicyAction" /> t
 34/// core validator attached. A not-yet-valid grant, an unavailable use store, an unspecified use state, or a grant missi
 35/// a required acknowledgment reference is therefore denied rather than deferred, escalated, or challenged. A valid gran
 36/// returns the current decision unchanged, so it never bypasses an acknowledgment challenge, and records the grant in
 37/// <see cref="IEndpointCapabilityGrantFeature" /> for the decision receipt. An existing denial is returned unchanged
 38/// before the token is read, so it consumes no use.
 39/// </para>
 40/// <para>
 41/// The host supplies the <see cref="IGovernanceSignatureVerificationService" />, the <see cref="ICapabilityGrantUseStor
 42/// and an <see cref="ICapabilityGrantRequestBindingProvider" />. A missing service denies the request rather than
 43/// weakening validation.
 44/// </para>
 45/// </remarks>
 46public sealed class SignedCapabilityGrantEndpointValidator : IEndpointCapabilityGrantValidator
 47{
 148    private static readonly Action<ILogger, string, string, Exception?> LogGrantDenied =
 149        LoggerMessage.Define<string, string>(
 150            LogLevel.Information,
 151            new EventId(19811, nameof(LogGrantDenied)),
 152            "Signed capability grant denied with {ReasonCode} ({DetailCode}).");
 53
 154    private static readonly Action<ILogger, string, Exception?> LogValidationFailed =
 155        LoggerMessage.Define<string>(
 156            LogLevel.Warning,
 157            new EventId(19812, nameof(LogValidationFailed)),
 158            "Signed capability grant validation failed unexpectedly for operation {OperationName}.");
 59
 60    private readonly IServiceProvider serviceProvider;
 61    private readonly IHttpGovernanceActorContextResolver actorContextResolver;
 62    private readonly SignedCapabilityGrantOptions options;
 63    private readonly TimeProvider timeProvider;
 64    private readonly ILogger logger;
 65
 66    /// <summary>
 67    /// Initializes a new instance of the <see cref="SignedCapabilityGrantEndpointValidator" /> class.
 68    /// </summary>
 69    /// <param name="serviceProvider">The request service provider used to resolve host-supplied services.</param>
 70    /// <param name="actorContextResolver">The actor resolver that supplies the authenticated subject.</param>
 71    /// <param name="options">The signed capability grant options.</param>
 72    /// <param name="logger">An optional logger for denial diagnostics; token content is never logged.</param>
 73    /// <exception cref="ArgumentNullException">A required argument is <see langword="null" />.</exception>
 74    /// <exception cref="InvalidOperationException">The options are invalid.</exception>
 4375    public SignedCapabilityGrantEndpointValidator(
 4376        IServiceProvider serviceProvider,
 4377        IHttpGovernanceActorContextResolver actorContextResolver,
 4378        IOptions<SignedCapabilityGrantOptions> options,
 4379        ILogger<SignedCapabilityGrantEndpointValidator>? logger = null)
 80    {
 4381        this.serviceProvider = serviceProvider ?? throw new ArgumentNullException(nameof(serviceProvider));
 4382        this.actorContextResolver = actorContextResolver ?? throw new ArgumentNullException(nameof(actorContextResolver)
 4383        this.options = options?.Value ?? throw new ArgumentNullException(nameof(options));
 4384        this.options.Validate();
 4385        timeProvider = serviceProvider.GetService<TimeProvider>() ?? TimeProvider.System;
 4386        this.logger = logger ?? NullLogger<SignedCapabilityGrantEndpointValidator>.Instance;
 4387    }
 88
 89    /// <inheritdoc />
 90    public async ValueTask<GovernanceDecision> ValidateAsync(
 91        HttpContext httpContext,
 92        EndpointGovernanceDescriptor descriptor,
 93        GovernanceDecision currentDecision,
 94        CancellationToken cancellationToken = default)
 95    {
 5096        ArgumentNullException.ThrowIfNull(httpContext);
 5097        ArgumentNullException.ThrowIfNull(descriptor);
 5098        ArgumentNullException.ThrowIfNull(currentDecision);
 5099        cancellationToken.ThrowIfCancellationRequested();
 100
 101        // An existing denial is final. Returning it before the token is read keeps a denied request from consuming a us
 50102        if (currentDecision.IsDenied || descriptor.CapabilityScopes.Count == 0)
 103        {
 1104            return currentDecision;
 105        }
 106
 49107        IGovernanceActorContext actor = actorContextResolver.ResolveActorContext();
 49108        if (!AcknowledgmentActorBinding.IsSufficient(actor))
 109        {
 1110            return Deny(
 1111                currentDecision,
 1112                SignedCapabilityGrantReasonCodes.ActorUnresolved,
 1113                "Signed capability grants require a known, authenticated actor to bind the grant to.");
 114        }
 115
 48116        TokenReadResult tokenRead = await ReadTokenAsync(httpContext, cancellationToken).ConfigureAwait(false);
 48117        if (tokenRead.ReasonCode is not null)
 118        {
 4119            return Deny(currentDecision, tokenRead.ReasonCode, tokenRead.Message!);
 120        }
 121
 44122        CapabilityGrantTokenDecodeResult decoded = CapabilityGrantToken.Decode(
 44123            tokenRead.Token,
 44124            options.ProofPayloadOptions,
 44125            options.MaxTokenLength);
 126
 44127        if (!decoded.Succeeded)
 128        {
 1129            return Deny(
 1130                currentDecision,
 1131                SignedCapabilityGrantReasonCodes.Malformed,
 1132                "The capability grant token could not be decoded.",
 1133                decoded.FailureCode);
 134        }
 135
 43136        SignedGovernanceArtifact<CapabilityGrant> signedGrant = decoded.SignedGrant!;
 137
 43138        CapabilityGrantRequestBinding binding = await ResolveBindingAsync(httpContext, descriptor, cancellationToken)
 43139            .ConfigureAwait(false);
 140
 43141        if (!binding.IsAvailable)
 142        {
 3143            return Deny(
 3144                currentDecision,
 3145                SignedCapabilityGrantReasonCodes.BindingUnavailable,
 3146                binding.FailureMessage ?? "The request could not be bound to a capability grant.");
 147        }
 148
 149        // The core validator checks a resource binding only when one is expected. When the request has no bound resourc
 150        // a grant issued for a specific resource is still the wrong grant, so it is denied here before any use is consu
 40151        if (binding.Value is null && signedGrant.Artifact.ResourceBinding is not null)
 152        {
 1153            return Deny(
 1154                currentDecision,
 1155                SignedCapabilityGrantReasonCodes.ResourceMismatch,
 1156                "The capability grant is bound to a resource, but the request has no bound resource.");
 157        }
 158
 159        CapabilityGrantValidationResult result;
 160
 161        try
 162        {
 39163            result = await CapabilityGrantValidator.ValidateAsync(
 39164                signedGrant,
 39165                CreateValidationOptions(actor, descriptor, currentDecision, binding.Value),
 39166                serviceProvider.GetService<IGovernanceSignatureVerificationService>(),
 39167                serviceProvider.GetService<ICapabilityGrantUseStore>(),
 39168                cancellationToken).ConfigureAwait(false);
 38169        }
 1170        catch (Exception exception) when (exception is not OperationCanceledException)
 171        {
 172            // A verifier or use store that throws has not established that the grant is valid. Denying keeps an
 173            // infrastructure fault from becoming an exception the host might handle permissively.
 1174            LogValidationFailed(logger, descriptor.OperationName, exception);
 175
 1176            return Deny(
 1177                currentDecision,
 1178                SignedCapabilityGrantReasonCodes.Failed,
 1179                "Capability grant validation failed unexpectedly.");
 180        }
 181
 38182        GovernanceDecision? rejection = MapRejection(currentDecision, result);
 38183        if (rejection is not null)
 184        {
 23185            LogGrantDenied(logger, rejection.ReasonCodes[0], result.FailureCode ?? "none", null);
 23186            return rejection;
 187        }
 188
 15189        httpContext.Features.Set<IEndpointCapabilityGrantFeature>(new EndpointCapabilityGrantFeature(result.TokenId));
 15190        return currentDecision;
 50191    }
 192
 193    /// <summary>
 194    /// Returns the denial for a rejected grant, or <see langword="null" /> when the grant was accepted.
 195    /// </summary>
 196    /// <remarks>
 197    /// The core result's <see cref="CapabilityGrantValidationResult.Action" /> is deliberately not mapped to an outcome
 198    /// an execution boundary a deferral, an escalation, or an acknowledgment challenge would let a request continue tow
 199    /// execution on a grant that did not validate, so every rejection is a denial.
 200    /// </remarks>
 201    internal static GovernanceDecision? MapRejection(
 202        GovernanceDecision currentDecision,
 203        CapabilityGrantValidationResult result)
 204    {
 139205        return result.IsValid && result.ShouldAllow
 139206            ? null
 139207            : CreateDenial(
 139208                currentDecision,
 139209                SignedCapabilityGrantReasonCodes.ForCategory(result.Category),
 139210                $"The capability grant was rejected: {result.Category}.");
 211    }
 212
 213    private CapabilityGrantValidationOptions CreateValidationOptions(
 214        IGovernanceActorContext actor,
 215        EndpointGovernanceDescriptor descriptor,
 216        GovernanceDecision currentDecision,
 217        string? resourceBinding)
 218    {
 39219        return CapabilityGrantValidationOptions.CreateBoundExecutionBoundary(
 39220            CapabilityGrantBindingExpectations.Create(actor.ActorId, descriptor.OperationName),
 39221            issuer: options.Issuer,
 39222            audience: options.Audience,
 39223            scopes: descriptor.CapabilityScopes,
 39224            validationUtc: timeProvider.GetUtcNow(),
 39225            policyVersion: options.BindPolicy ? currentDecision.PolicyVersion : null,
 39226            policyHash: options.BindPolicy ? currentDecision.PolicyHash : null,
 39227            resourceBinding: resourceBinding,
 39228
 39229            // An acknowledgment-required request is answered with a challenge and never executes, and the acknowledged
 39230            // retry is validated again. Consuming a use here would leave a single-use grant spent before the retry. Eve
 39231            // other outcome can lead to execution from this evaluation, including a deferral or escalation the host lat
 39232            // approves, so it consumes a use.
 39233            requireUseCheck: !currentDecision.RequiresAcknowledgment,
 39234            maxUseCount: options.MaxUseCount,
 39235            allowedClockSkew: options.AllowedClockSkew,
 39236            expectedProofKeyId: options.ExpectedProofKeyId,
 39237            expectedProofKeyVersion: options.ExpectedProofKeyVersion,
 39238            requiredProofProvider: options.RequiredProofProvider,
 39239            requiredProofHashAlgorithm: options.RequiredProofHashAlgorithm,
 39240            proofPayloadOptions: options.ProofPayloadOptions);
 241    }
 242
 243    private async ValueTask<CapabilityGrantRequestBinding> ResolveBindingAsync(
 244        HttpContext httpContext,
 245        EndpointGovernanceDescriptor descriptor,
 246        CancellationToken cancellationToken)
 247    {
 43248        ICapabilityGrantRequestBindingProvider? bindingProvider =
 43249            serviceProvider.GetService<ICapabilityGrantRequestBindingProvider>();
 250
 43251        return bindingProvider is null
 43252            ? CapabilityGrantRequestBinding.Unavailable("No capability grant request-binding provider is registered.")
 43253            : await bindingProvider.ResolveAsync(httpContext, descriptor, cancellationToken).ConfigureAwait(false);
 43254    }
 255
 256    private async ValueTask<TokenReadResult> ReadTokenAsync(HttpContext httpContext, CancellationToken cancellationToken
 257    {
 48258        HttpRequest request = httpContext.Request;
 259
 48260        if (!string.IsNullOrWhiteSpace(options.TokenHeaderName)
 48261            && request.Headers.TryGetValue(options.TokenHeaderName, out StringValues headerValues)
 48262            && headerValues.Count > 0)
 263        {
 44264            return ReadSingle(headerValues);
 265        }
 266
 4267        if (string.IsNullOrWhiteSpace(options.TokenFormFieldName) || !request.HasFormContentType)
 268        {
 3269            return TokenReadResult.Missing;
 270        }
 271
 272        IFormCollection form;
 273
 274        try
 275        {
 1276            form = await request.ReadFormAsync(cancellationToken).ConfigureAwait(false);
 1277        }
 0278        catch (Exception exception) when (exception is InvalidDataException or IOException or BadHttpRequestException)
 279        {
 0280            return TokenReadResult.Unreadable;
 281        }
 282
 1283        return form.TryGetValue(options.TokenFormFieldName, out StringValues formValues) && formValues.Count > 0
 1284            ? ReadSingle(formValues)
 1285            : TokenReadResult.Missing;
 48286    }
 287
 288    private static TokenReadResult ReadSingle(StringValues values)
 289    {
 290        // Two tokens leave it ambiguous which one the request means to present, so neither is chosen.
 45291        return values.Count > 1
 45292            ? TokenReadResult.Ambiguous
 45293            : string.IsNullOrWhiteSpace(values[0])
 45294            ? TokenReadResult.Missing
 45295            : new TokenReadResult(values[0], ReasonCode: null, Message: null);
 296    }
 297
 298    private GovernanceDecision Deny(
 299        GovernanceDecision currentDecision,
 300        string reasonCode,
 301        string message,
 302        string? detailCode = null)
 303    {
 11304        LogGrantDenied(logger, reasonCode, detailCode ?? "none", null);
 11305        return CreateDenial(currentDecision, reasonCode, message);
 306    }
 307
 308    private static GovernanceDecision CreateDenial(GovernanceDecision currentDecision, string reasonCode, string message
 309    {
 134310        return GovernanceDecision.Deny(
 134311            reasonCode,
 134312            message,
 134313            correlationId: currentDecision.CorrelationId,
 134314            traceId: currentDecision.TraceId,
 134315            policyVersion: currentDecision.PolicyVersion,
 134316            policyHash: currentDecision.PolicyHash);
 317    }
 318
 319    private readonly record struct TokenReadResult(string? Token, string? ReasonCode, string? Message)
 320    {
 321        public static TokenReadResult Missing { get; } = new(
 322            null,
 323            SignedCapabilityGrantReasonCodes.Missing,
 324            "No capability grant token was presented.");
 325
 326        public static TokenReadResult Ambiguous { get; } = new(
 327            null,
 328            SignedCapabilityGrantReasonCodes.Malformed,
 329            "More than one capability grant token was presented.");
 330
 331        public static TokenReadResult Unreadable { get; } = new(
 332            null,
 333            SignedCapabilityGrantReasonCodes.Malformed,
 334            "The request form carrying the capability grant token could not be read.");
 335    }
 336}