| | | 1 | | using AsiBackbone.AspNetCore.Acknowledgments; |
| | | 2 | | using AsiBackbone.AspNetCore.Actors; |
| | | 3 | | using AsiBackbone.AspNetCore.Endpoints; |
| | | 4 | | using AsiBackbone.Core.Actors; |
| | | 5 | | using AsiBackbone.Core.CapabilityGrants; |
| | | 6 | | using AsiBackbone.Core.Decisions; |
| | | 7 | | using AsiBackbone.Core.Signing; |
| | | 8 | | using Microsoft.AspNetCore.Http; |
| | | 9 | | using Microsoft.Extensions.DependencyInjection; |
| | | 10 | | using Microsoft.Extensions.Logging; |
| | | 11 | | using Microsoft.Extensions.Logging.Abstractions; |
| | | 12 | | using Microsoft.Extensions.Options; |
| | | 13 | | using Microsoft.Extensions.Primitives; |
| | | 14 | | |
| | | 15 | | namespace 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> |
| | | 46 | | public sealed class SignedCapabilityGrantEndpointValidator : IEndpointCapabilityGrantValidator |
| | | 47 | | { |
| | 1 | 48 | | private static readonly Action<ILogger, string, string, Exception?> LogGrantDenied = |
| | 1 | 49 | | LoggerMessage.Define<string, string>( |
| | 1 | 50 | | LogLevel.Information, |
| | 1 | 51 | | new EventId(19811, nameof(LogGrantDenied)), |
| | 1 | 52 | | "Signed capability grant denied with {ReasonCode} ({DetailCode})."); |
| | | 53 | | |
| | 1 | 54 | | private static readonly Action<ILogger, string, Exception?> LogValidationFailed = |
| | 1 | 55 | | LoggerMessage.Define<string>( |
| | 1 | 56 | | LogLevel.Warning, |
| | 1 | 57 | | new EventId(19812, nameof(LogValidationFailed)), |
| | 1 | 58 | | "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> |
| | 43 | 75 | | public SignedCapabilityGrantEndpointValidator( |
| | 43 | 76 | | IServiceProvider serviceProvider, |
| | 43 | 77 | | IHttpGovernanceActorContextResolver actorContextResolver, |
| | 43 | 78 | | IOptions<SignedCapabilityGrantOptions> options, |
| | 43 | 79 | | ILogger<SignedCapabilityGrantEndpointValidator>? logger = null) |
| | | 80 | | { |
| | 43 | 81 | | this.serviceProvider = serviceProvider ?? throw new ArgumentNullException(nameof(serviceProvider)); |
| | 43 | 82 | | this.actorContextResolver = actorContextResolver ?? throw new ArgumentNullException(nameof(actorContextResolver) |
| | 43 | 83 | | this.options = options?.Value ?? throw new ArgumentNullException(nameof(options)); |
| | 43 | 84 | | this.options.Validate(); |
| | 43 | 85 | | timeProvider = serviceProvider.GetService<TimeProvider>() ?? TimeProvider.System; |
| | 43 | 86 | | this.logger = logger ?? NullLogger<SignedCapabilityGrantEndpointValidator>.Instance; |
| | 43 | 87 | | } |
| | | 88 | | |
| | | 89 | | /// <inheritdoc /> |
| | | 90 | | public async ValueTask<GovernanceDecision> ValidateAsync( |
| | | 91 | | HttpContext httpContext, |
| | | 92 | | EndpointGovernanceDescriptor descriptor, |
| | | 93 | | GovernanceDecision currentDecision, |
| | | 94 | | CancellationToken cancellationToken = default) |
| | | 95 | | { |
| | 50 | 96 | | ArgumentNullException.ThrowIfNull(httpContext); |
| | 50 | 97 | | ArgumentNullException.ThrowIfNull(descriptor); |
| | 50 | 98 | | ArgumentNullException.ThrowIfNull(currentDecision); |
| | 50 | 99 | | cancellationToken.ThrowIfCancellationRequested(); |
| | | 100 | | |
| | | 101 | | // An existing denial is final. Returning it before the token is read keeps a denied request from consuming a us |
| | 50 | 102 | | if (currentDecision.IsDenied || descriptor.CapabilityScopes.Count == 0) |
| | | 103 | | { |
| | 1 | 104 | | return currentDecision; |
| | | 105 | | } |
| | | 106 | | |
| | 49 | 107 | | IGovernanceActorContext actor = actorContextResolver.ResolveActorContext(); |
| | 49 | 108 | | if (!AcknowledgmentActorBinding.IsSufficient(actor)) |
| | | 109 | | { |
| | 1 | 110 | | return Deny( |
| | 1 | 111 | | currentDecision, |
| | 1 | 112 | | SignedCapabilityGrantReasonCodes.ActorUnresolved, |
| | 1 | 113 | | "Signed capability grants require a known, authenticated actor to bind the grant to."); |
| | | 114 | | } |
| | | 115 | | |
| | 48 | 116 | | TokenReadResult tokenRead = await ReadTokenAsync(httpContext, cancellationToken).ConfigureAwait(false); |
| | 48 | 117 | | if (tokenRead.ReasonCode is not null) |
| | | 118 | | { |
| | 4 | 119 | | return Deny(currentDecision, tokenRead.ReasonCode, tokenRead.Message!); |
| | | 120 | | } |
| | | 121 | | |
| | 44 | 122 | | CapabilityGrantTokenDecodeResult decoded = CapabilityGrantToken.Decode( |
| | 44 | 123 | | tokenRead.Token, |
| | 44 | 124 | | options.ProofPayloadOptions, |
| | 44 | 125 | | options.MaxTokenLength); |
| | | 126 | | |
| | 44 | 127 | | if (!decoded.Succeeded) |
| | | 128 | | { |
| | 1 | 129 | | return Deny( |
| | 1 | 130 | | currentDecision, |
| | 1 | 131 | | SignedCapabilityGrantReasonCodes.Malformed, |
| | 1 | 132 | | "The capability grant token could not be decoded.", |
| | 1 | 133 | | decoded.FailureCode); |
| | | 134 | | } |
| | | 135 | | |
| | 43 | 136 | | SignedGovernanceArtifact<CapabilityGrant> signedGrant = decoded.SignedGrant!; |
| | | 137 | | |
| | 43 | 138 | | CapabilityGrantRequestBinding binding = await ResolveBindingAsync(httpContext, descriptor, cancellationToken) |
| | 43 | 139 | | .ConfigureAwait(false); |
| | | 140 | | |
| | 43 | 141 | | if (!binding.IsAvailable) |
| | | 142 | | { |
| | 3 | 143 | | return Deny( |
| | 3 | 144 | | currentDecision, |
| | 3 | 145 | | SignedCapabilityGrantReasonCodes.BindingUnavailable, |
| | 3 | 146 | | 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 |
| | 40 | 151 | | if (binding.Value is null && signedGrant.Artifact.ResourceBinding is not null) |
| | | 152 | | { |
| | 1 | 153 | | return Deny( |
| | 1 | 154 | | currentDecision, |
| | 1 | 155 | | SignedCapabilityGrantReasonCodes.ResourceMismatch, |
| | 1 | 156 | | "The capability grant is bound to a resource, but the request has no bound resource."); |
| | | 157 | | } |
| | | 158 | | |
| | | 159 | | CapabilityGrantValidationResult result; |
| | | 160 | | |
| | | 161 | | try |
| | | 162 | | { |
| | 39 | 163 | | result = await CapabilityGrantValidator.ValidateAsync( |
| | 39 | 164 | | signedGrant, |
| | 39 | 165 | | CreateValidationOptions(actor, descriptor, currentDecision, binding.Value), |
| | 39 | 166 | | serviceProvider.GetService<IGovernanceSignatureVerificationService>(), |
| | 39 | 167 | | serviceProvider.GetService<ICapabilityGrantUseStore>(), |
| | 39 | 168 | | cancellationToken).ConfigureAwait(false); |
| | 38 | 169 | | } |
| | 1 | 170 | | 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. |
| | 1 | 174 | | LogValidationFailed(logger, descriptor.OperationName, exception); |
| | | 175 | | |
| | 1 | 176 | | return Deny( |
| | 1 | 177 | | currentDecision, |
| | 1 | 178 | | SignedCapabilityGrantReasonCodes.Failed, |
| | 1 | 179 | | "Capability grant validation failed unexpectedly."); |
| | | 180 | | } |
| | | 181 | | |
| | 38 | 182 | | GovernanceDecision? rejection = MapRejection(currentDecision, result); |
| | 38 | 183 | | if (rejection is not null) |
| | | 184 | | { |
| | 23 | 185 | | LogGrantDenied(logger, rejection.ReasonCodes[0], result.FailureCode ?? "none", null); |
| | 23 | 186 | | return rejection; |
| | | 187 | | } |
| | | 188 | | |
| | 15 | 189 | | httpContext.Features.Set<IEndpointCapabilityGrantFeature>(new EndpointCapabilityGrantFeature(result.TokenId)); |
| | 15 | 190 | | return currentDecision; |
| | 50 | 191 | | } |
| | | 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 | | { |
| | 139 | 205 | | return result.IsValid && result.ShouldAllow |
| | 139 | 206 | | ? null |
| | 139 | 207 | | : CreateDenial( |
| | 139 | 208 | | currentDecision, |
| | 139 | 209 | | SignedCapabilityGrantReasonCodes.ForCategory(result.Category), |
| | 139 | 210 | | $"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 | | { |
| | 39 | 219 | | return CapabilityGrantValidationOptions.CreateBoundExecutionBoundary( |
| | 39 | 220 | | CapabilityGrantBindingExpectations.Create(actor.ActorId, descriptor.OperationName), |
| | 39 | 221 | | issuer: options.Issuer, |
| | 39 | 222 | | audience: options.Audience, |
| | 39 | 223 | | scopes: descriptor.CapabilityScopes, |
| | 39 | 224 | | validationUtc: timeProvider.GetUtcNow(), |
| | 39 | 225 | | policyVersion: options.BindPolicy ? currentDecision.PolicyVersion : null, |
| | 39 | 226 | | policyHash: options.BindPolicy ? currentDecision.PolicyHash : null, |
| | 39 | 227 | | resourceBinding: resourceBinding, |
| | 39 | 228 | | |
| | 39 | 229 | | // An acknowledgment-required request is answered with a challenge and never executes, and the acknowledged |
| | 39 | 230 | | // retry is validated again. Consuming a use here would leave a single-use grant spent before the retry. Eve |
| | 39 | 231 | | // other outcome can lead to execution from this evaluation, including a deferral or escalation the host lat |
| | 39 | 232 | | // approves, so it consumes a use. |
| | 39 | 233 | | requireUseCheck: !currentDecision.RequiresAcknowledgment, |
| | 39 | 234 | | maxUseCount: options.MaxUseCount, |
| | 39 | 235 | | allowedClockSkew: options.AllowedClockSkew, |
| | 39 | 236 | | expectedProofKeyId: options.ExpectedProofKeyId, |
| | 39 | 237 | | expectedProofKeyVersion: options.ExpectedProofKeyVersion, |
| | 39 | 238 | | requiredProofProvider: options.RequiredProofProvider, |
| | 39 | 239 | | requiredProofHashAlgorithm: options.RequiredProofHashAlgorithm, |
| | 39 | 240 | | proofPayloadOptions: options.ProofPayloadOptions); |
| | | 241 | | } |
| | | 242 | | |
| | | 243 | | private async ValueTask<CapabilityGrantRequestBinding> ResolveBindingAsync( |
| | | 244 | | HttpContext httpContext, |
| | | 245 | | EndpointGovernanceDescriptor descriptor, |
| | | 246 | | CancellationToken cancellationToken) |
| | | 247 | | { |
| | 43 | 248 | | ICapabilityGrantRequestBindingProvider? bindingProvider = |
| | 43 | 249 | | serviceProvider.GetService<ICapabilityGrantRequestBindingProvider>(); |
| | | 250 | | |
| | 43 | 251 | | return bindingProvider is null |
| | 43 | 252 | | ? CapabilityGrantRequestBinding.Unavailable("No capability grant request-binding provider is registered.") |
| | 43 | 253 | | : await bindingProvider.ResolveAsync(httpContext, descriptor, cancellationToken).ConfigureAwait(false); |
| | 43 | 254 | | } |
| | | 255 | | |
| | | 256 | | private async ValueTask<TokenReadResult> ReadTokenAsync(HttpContext httpContext, CancellationToken cancellationToken |
| | | 257 | | { |
| | 48 | 258 | | HttpRequest request = httpContext.Request; |
| | | 259 | | |
| | 48 | 260 | | if (!string.IsNullOrWhiteSpace(options.TokenHeaderName) |
| | 48 | 261 | | && request.Headers.TryGetValue(options.TokenHeaderName, out StringValues headerValues) |
| | 48 | 262 | | && headerValues.Count > 0) |
| | | 263 | | { |
| | 44 | 264 | | return ReadSingle(headerValues); |
| | | 265 | | } |
| | | 266 | | |
| | 4 | 267 | | if (string.IsNullOrWhiteSpace(options.TokenFormFieldName) || !request.HasFormContentType) |
| | | 268 | | { |
| | 3 | 269 | | return TokenReadResult.Missing; |
| | | 270 | | } |
| | | 271 | | |
| | | 272 | | IFormCollection form; |
| | | 273 | | |
| | | 274 | | try |
| | | 275 | | { |
| | 1 | 276 | | form = await request.ReadFormAsync(cancellationToken).ConfigureAwait(false); |
| | 1 | 277 | | } |
| | 0 | 278 | | catch (Exception exception) when (exception is InvalidDataException or IOException or BadHttpRequestException) |
| | | 279 | | { |
| | 0 | 280 | | return TokenReadResult.Unreadable; |
| | | 281 | | } |
| | | 282 | | |
| | 1 | 283 | | return form.TryGetValue(options.TokenFormFieldName, out StringValues formValues) && formValues.Count > 0 |
| | 1 | 284 | | ? ReadSingle(formValues) |
| | 1 | 285 | | : TokenReadResult.Missing; |
| | 48 | 286 | | } |
| | | 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. |
| | 45 | 291 | | return values.Count > 1 |
| | 45 | 292 | | ? TokenReadResult.Ambiguous |
| | 45 | 293 | | : string.IsNullOrWhiteSpace(values[0]) |
| | 45 | 294 | | ? TokenReadResult.Missing |
| | 45 | 295 | | : 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 | | { |
| | 11 | 304 | | LogGrantDenied(logger, reasonCode, detailCode ?? "none", null); |
| | 11 | 305 | | return CreateDenial(currentDecision, reasonCode, message); |
| | | 306 | | } |
| | | 307 | | |
| | | 308 | | private static GovernanceDecision CreateDenial(GovernanceDecision currentDecision, string reasonCode, string message |
| | | 309 | | { |
| | 134 | 310 | | return GovernanceDecision.Deny( |
| | 134 | 311 | | reasonCode, |
| | 134 | 312 | | message, |
| | 134 | 313 | | correlationId: currentDecision.CorrelationId, |
| | 134 | 314 | | traceId: currentDecision.TraceId, |
| | 134 | 315 | | policyVersion: currentDecision.PolicyVersion, |
| | 134 | 316 | | 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 | | } |