< Summary

Information
Class: AsiBackbone.AspNetCore.CapabilityGrants.FormFieldCapabilityGrantRequestBindingProvider
Assembly: AsiBackbone.AspNetCore
File(s): /home/runner/work/AsiBackbone/AsiBackbone/src/AsiBackbone.AspNetCore/CapabilityGrants/FormFieldCapabilityGrantRequestBindingProvider.cs
Line coverage
96%
Covered lines: 64
Uncovered lines: 2
Coverable lines: 66
Total lines: 212
Line coverage: 96.9%
Branch coverage
86%
Covered branches: 38
Total branches: 44
Branch coverage: 86.3%
Method coverage

Feature is only available for sponsors

Upgrade to PRO version

Metrics

MethodBranch coverage Crap Score Cyclomatic complexity Line coverage
.ctor(...)60%1010100%
ResolveAsync()100%6689.47%
CreateBinding(...)93.75%1616100%
CannotHaveBody(...)83.33%66100%
GetExcludedFieldNames()100%66100%

File(s)

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

#LineLine coverage
 1using System.Buffers;
 2using System.Security.Cryptography;
 3using System.Text.Json;
 4using AsiBackbone.AspNetCore.Endpoints;
 5using Microsoft.AspNetCore.Antiforgery;
 6using Microsoft.AspNetCore.Http;
 7using Microsoft.AspNetCore.Http.Features;
 8using Microsoft.Extensions.Options;
 9using Microsoft.Extensions.Primitives;
 10
 11namespace AsiBackbone.AspNetCore.CapabilityGrants;
 12
 13/// <summary>
 14/// Binds a capability grant to the submitted form fields of the request.
 15/// </summary>
 16/// <remarks>
 17/// <para>
 18/// The binding value is <see cref="BindingPrefix" /> followed by the lowercase hexadecimal SHA-256 hash of a canonical
 19/// JSON encoding of the form fields: field names lower-cased with the invariant culture and sorted ordinally, each with
 20/// its values in submitted order. The antiforgery field configured in <see cref="AntiforgeryOptions.FormFieldName" />,
 21/// the token form field configured in <see cref="SignedCapabilityGrantOptions.TokenFormFieldName" />, and any name in
 22/// <see cref="FormFieldCapabilityGrantBindingOptions.ExcludedFieldNames" /> are left out. Issuers compute the same valu
 23/// for the fields they intend to authorize with <see cref="CreateBinding" />.
 24/// </para>
 25/// <para>
 26/// A request that cannot carry a body binds the empty field set. A request with a form body that contains files, a body
 27/// that is not a form, or a form that cannot be read is not bound, which denies it. Only the form body is covered: the
 28/// query string and route values are not, so an endpoint that takes a resource identifier from its route should carry
 29/// that identifier as a form field or use a provider that binds it.
 30/// </para>
 31/// </remarks>
 32/// <param name="bindingOptions">The form-field binding options.</param>
 33/// <param name="grantOptions">The signed capability grant options, whose token form field is excluded.</param>
 34/// <param name="antiforgeryOptions">The antiforgery options, whose form field is excluded, when antiforgery is configur
 3935public sealed class FormFieldCapabilityGrantRequestBindingProvider(
 3936    IOptions<FormFieldCapabilityGrantBindingOptions> bindingOptions,
 3937    IOptions<SignedCapabilityGrantOptions> grantOptions,
 3938    IOptions<AntiforgeryOptions>? antiforgeryOptions = null) : ICapabilityGrantRequestBindingProvider
 39{
 40    /// <summary>
 41    /// Gets the prefix of every binding value produced by this provider.
 42    /// </summary>
 43    public const string BindingPrefix = "form-sha256:";
 44
 3945    private readonly FormFieldCapabilityGrantBindingOptions bindingOptions =
 3946        bindingOptions?.Value ?? throw new ArgumentNullException(nameof(bindingOptions));
 47
 3948    private readonly SignedCapabilityGrantOptions grantOptions =
 3949        grantOptions?.Value ?? throw new ArgumentNullException(nameof(grantOptions));
 50
 3951    private readonly AntiforgeryOptions? antiforgeryOptions = antiforgeryOptions?.Value;
 52
 53    /// <inheritdoc />
 54    public async ValueTask<CapabilityGrantRequestBinding> ResolveAsync(
 55        HttpContext httpContext,
 56        EndpointGovernanceDescriptor descriptor,
 57        CancellationToken cancellationToken = default)
 58    {
 4459        ArgumentNullException.ThrowIfNull(httpContext);
 4460        ArgumentNullException.ThrowIfNull(descriptor);
 4461        cancellationToken.ThrowIfCancellationRequested();
 62
 4463        HttpRequest request = httpContext.Request;
 4464        IReadOnlyCollection<string> excludedFieldNames = GetExcludedFieldNames();
 65
 4466        if (!request.HasFormContentType)
 67        {
 468            return CannotHaveBody(httpContext)
 469                ? CapabilityGrantRequestBinding.Bound(CreateBinding([], excludedFieldNames))
 470                : CapabilityGrantRequestBinding.Unavailable(
 471                    "The request body is not a form, so the form-field binding provider cannot bind it.");
 72        }
 73
 74        IFormCollection form;
 75
 76        try
 77        {
 4078            form = await request.ReadFormAsync(cancellationToken).ConfigureAwait(false);
 4079        }
 080        catch (Exception exception) when (exception is InvalidDataException or IOException or BadHttpRequestException)
 81        {
 082            return CapabilityGrantRequestBinding.Unavailable("The request form could not be read.");
 83        }
 84
 4085        return form.Files.Count > 0
 4086            ? CapabilityGrantRequestBinding.Unavailable(
 4087                "The request form contains files, which the form-field binding provider does not bind.")
 4088            : CapabilityGrantRequestBinding.Bound(CreateBinding(form, excludedFieldNames));
 4489    }
 90
 91    /// <summary>
 92    /// Computes the binding value for a set of form fields, for an issuer to place in
 93    /// <see cref="Core.CapabilityGrants.CapabilityGrant.ResourceBinding" />.
 94    /// </summary>
 95    /// <remarks>
 96    /// Pass the same exclusions the relying party applies. The relying party always excludes its antiforgery and token
 97    /// form fields, so an issuer that includes either here produces a binding that never matches.
 98    /// </remarks>
 99    /// <param name="fields">The form fields to bind.</param>
 100    /// <param name="excludedFieldNames">Field names to leave out, compared case-insensitively.</param>
 101    /// <returns>The binding value.</returns>
 102    /// <exception cref="ArgumentNullException"><paramref name="fields" /> is <see langword="null" />.</exception>
 103    /// <exception cref="ArgumentException">Two field names are equal once lower-cased, or a field name is blank.</excep
 104    public static string CreateBinding(
 105        IEnumerable<KeyValuePair<string, StringValues>> fields,
 106        IEnumerable<string>? excludedFieldNames = null)
 107    {
 195108        ArgumentNullException.ThrowIfNull(fields);
 109
 194110        HashSet<string> excluded = new(
 194111            (excludedFieldNames ?? []).Where(name => !string.IsNullOrWhiteSpace(name)).Select(name => name.Trim()),
 194112            StringComparer.OrdinalIgnoreCase);
 194113        SortedDictionary<string, StringValues> normalized = new(StringComparer.Ordinal);
 114
 1152115        foreach (KeyValuePair<string, StringValues> field in fields)
 116        {
 383117            if (string.IsNullOrWhiteSpace(field.Key))
 118            {
 1119                throw new ArgumentException("Form field names must not be blank.", nameof(fields));
 120            }
 121
 382122            if (excluded.Contains(field.Key.Trim()))
 123            {
 124                continue;
 125            }
 126
 375127            string name = field.Key.Trim().ToLowerInvariant();
 128
 375129            if (!normalized.TryAdd(name, field.Value))
 130            {
 1131                throw new ArgumentException($"Form field names collide once lower-cased: '{name}'.", nameof(fields));
 132            }
 133        }
 134
 192135        ArrayBufferWriter<byte> buffer = new();
 192136        using (Utf8JsonWriter writer = new(buffer))
 137        {
 192138            writer.WriteStartArray();
 1130139            foreach (KeyValuePair<string, StringValues> field in normalized)
 140            {
 373141                writer.WriteStartArray();
 373142                writer.WriteStringValue(field.Key);
 373143                writer.WriteStartArray();
 1498144                foreach (string? value in field.Value)
 145                {
 376146                    writer.WriteStringValue(value ?? string.Empty);
 147                }
 148
 373149                writer.WriteEndArray();
 373150                writer.WriteEndArray();
 151            }
 152
 192153            writer.WriteEndArray();
 192154        }
 155
 192156        return BindingPrefix + Convert.ToHexStringLower(SHA256.HashData(buffer.WrittenSpan));
 157    }
 158
 159    private static bool CannotHaveBody(HttpContext httpContext)
 160    {
 4161        IHttpRequestBodyDetectionFeature? bodyDetection = httpContext.Features.Get<IHttpRequestBodyDetectionFeature>();
 162
 4163        if (bodyDetection is not null)
 164        {
 2165            return !bodyDetection.CanHaveBody;
 166        }
 167
 2168        HttpRequest request = httpContext.Request;
 2169        return request.ContentLength == 0
 2170            || (request.ContentLength is null && string.IsNullOrEmpty(request.ContentType));
 171    }
 172
 173    private string[] GetExcludedFieldNames()
 174    {
 44175        List<string> names = [.. bindingOptions.ExcludedFieldNames];
 176
 44177        if (!string.IsNullOrWhiteSpace(antiforgeryOptions?.FormFieldName))
 178        {
 41179            names.Add(antiforgeryOptions.FormFieldName);
 180        }
 181
 44182        if (!string.IsNullOrWhiteSpace(grantOptions.TokenFormFieldName))
 183        {
 2184            names.Add(grantOptions.TokenFormFieldName);
 185        }
 186
 44187        return [.. names];
 188    }
 189}
 190
 191/// <summary>
 192/// Configures <see cref="FormFieldCapabilityGrantRequestBindingProvider" />.
 193/// </summary>
 194public sealed class FormFieldCapabilityGrantBindingOptions
 195{
 196    /// <summary>
 197    /// Gets the default antiforgery form field name, excluded even when antiforgery options are not registered.
 198    /// </summary>
 199    public const string DefaultAntiforgeryFormFieldName = "__RequestVerificationToken";
 200
 201    /// <summary>
 202    /// Gets additional form field names, compared case-insensitively, that the binding leaves out.
 203    /// </summary>
 204    /// <remarks>
 205    /// Contains <see cref="DefaultAntiforgeryFormFieldName" /> by default. Exclude only fields that do not change what 
 206    /// request does, because an excluded field can be changed without invalidating the grant.
 207    /// </remarks>
 208    public ISet<string> ExcludedFieldNames { get; } = new HashSet<string>(StringComparer.OrdinalIgnoreCase)
 209    {
 210        DefaultAntiforgeryFormFieldName
 211    };
 212}