| | | 1 | | using System.Buffers; |
| | | 2 | | using System.Security.Cryptography; |
| | | 3 | | using System.Text.Json; |
| | | 4 | | using AsiBackbone.AspNetCore.Endpoints; |
| | | 5 | | using Microsoft.AspNetCore.Antiforgery; |
| | | 6 | | using Microsoft.AspNetCore.Http; |
| | | 7 | | using Microsoft.AspNetCore.Http.Features; |
| | | 8 | | using Microsoft.Extensions.Options; |
| | | 9 | | using Microsoft.Extensions.Primitives; |
| | | 10 | | |
| | | 11 | | namespace 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 |
| | 39 | 35 | | public sealed class FormFieldCapabilityGrantRequestBindingProvider( |
| | 39 | 36 | | IOptions<FormFieldCapabilityGrantBindingOptions> bindingOptions, |
| | 39 | 37 | | IOptions<SignedCapabilityGrantOptions> grantOptions, |
| | 39 | 38 | | 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 | | |
| | 39 | 45 | | private readonly FormFieldCapabilityGrantBindingOptions bindingOptions = |
| | 39 | 46 | | bindingOptions?.Value ?? throw new ArgumentNullException(nameof(bindingOptions)); |
| | | 47 | | |
| | 39 | 48 | | private readonly SignedCapabilityGrantOptions grantOptions = |
| | 39 | 49 | | grantOptions?.Value ?? throw new ArgumentNullException(nameof(grantOptions)); |
| | | 50 | | |
| | 39 | 51 | | 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 | | { |
| | 44 | 59 | | ArgumentNullException.ThrowIfNull(httpContext); |
| | 44 | 60 | | ArgumentNullException.ThrowIfNull(descriptor); |
| | 44 | 61 | | cancellationToken.ThrowIfCancellationRequested(); |
| | | 62 | | |
| | 44 | 63 | | HttpRequest request = httpContext.Request; |
| | 44 | 64 | | IReadOnlyCollection<string> excludedFieldNames = GetExcludedFieldNames(); |
| | | 65 | | |
| | 44 | 66 | | if (!request.HasFormContentType) |
| | | 67 | | { |
| | 4 | 68 | | return CannotHaveBody(httpContext) |
| | 4 | 69 | | ? CapabilityGrantRequestBinding.Bound(CreateBinding([], excludedFieldNames)) |
| | 4 | 70 | | : CapabilityGrantRequestBinding.Unavailable( |
| | 4 | 71 | | "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 | | { |
| | 40 | 78 | | form = await request.ReadFormAsync(cancellationToken).ConfigureAwait(false); |
| | 40 | 79 | | } |
| | 0 | 80 | | catch (Exception exception) when (exception is InvalidDataException or IOException or BadHttpRequestException) |
| | | 81 | | { |
| | 0 | 82 | | return CapabilityGrantRequestBinding.Unavailable("The request form could not be read."); |
| | | 83 | | } |
| | | 84 | | |
| | 40 | 85 | | return form.Files.Count > 0 |
| | 40 | 86 | | ? CapabilityGrantRequestBinding.Unavailable( |
| | 40 | 87 | | "The request form contains files, which the form-field binding provider does not bind.") |
| | 40 | 88 | | : CapabilityGrantRequestBinding.Bound(CreateBinding(form, excludedFieldNames)); |
| | 44 | 89 | | } |
| | | 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 | | { |
| | 195 | 108 | | ArgumentNullException.ThrowIfNull(fields); |
| | | 109 | | |
| | 194 | 110 | | HashSet<string> excluded = new( |
| | 194 | 111 | | (excludedFieldNames ?? []).Where(name => !string.IsNullOrWhiteSpace(name)).Select(name => name.Trim()), |
| | 194 | 112 | | StringComparer.OrdinalIgnoreCase); |
| | 194 | 113 | | SortedDictionary<string, StringValues> normalized = new(StringComparer.Ordinal); |
| | | 114 | | |
| | 1152 | 115 | | foreach (KeyValuePair<string, StringValues> field in fields) |
| | | 116 | | { |
| | 383 | 117 | | if (string.IsNullOrWhiteSpace(field.Key)) |
| | | 118 | | { |
| | 1 | 119 | | throw new ArgumentException("Form field names must not be blank.", nameof(fields)); |
| | | 120 | | } |
| | | 121 | | |
| | 382 | 122 | | if (excluded.Contains(field.Key.Trim())) |
| | | 123 | | { |
| | | 124 | | continue; |
| | | 125 | | } |
| | | 126 | | |
| | 375 | 127 | | string name = field.Key.Trim().ToLowerInvariant(); |
| | | 128 | | |
| | 375 | 129 | | if (!normalized.TryAdd(name, field.Value)) |
| | | 130 | | { |
| | 1 | 131 | | throw new ArgumentException($"Form field names collide once lower-cased: '{name}'.", nameof(fields)); |
| | | 132 | | } |
| | | 133 | | } |
| | | 134 | | |
| | 192 | 135 | | ArrayBufferWriter<byte> buffer = new(); |
| | 192 | 136 | | using (Utf8JsonWriter writer = new(buffer)) |
| | | 137 | | { |
| | 192 | 138 | | writer.WriteStartArray(); |
| | 1130 | 139 | | foreach (KeyValuePair<string, StringValues> field in normalized) |
| | | 140 | | { |
| | 373 | 141 | | writer.WriteStartArray(); |
| | 373 | 142 | | writer.WriteStringValue(field.Key); |
| | 373 | 143 | | writer.WriteStartArray(); |
| | 1498 | 144 | | foreach (string? value in field.Value) |
| | | 145 | | { |
| | 376 | 146 | | writer.WriteStringValue(value ?? string.Empty); |
| | | 147 | | } |
| | | 148 | | |
| | 373 | 149 | | writer.WriteEndArray(); |
| | 373 | 150 | | writer.WriteEndArray(); |
| | | 151 | | } |
| | | 152 | | |
| | 192 | 153 | | writer.WriteEndArray(); |
| | 192 | 154 | | } |
| | | 155 | | |
| | 192 | 156 | | return BindingPrefix + Convert.ToHexStringLower(SHA256.HashData(buffer.WrittenSpan)); |
| | | 157 | | } |
| | | 158 | | |
| | | 159 | | private static bool CannotHaveBody(HttpContext httpContext) |
| | | 160 | | { |
| | 4 | 161 | | IHttpRequestBodyDetectionFeature? bodyDetection = httpContext.Features.Get<IHttpRequestBodyDetectionFeature>(); |
| | | 162 | | |
| | 4 | 163 | | if (bodyDetection is not null) |
| | | 164 | | { |
| | 2 | 165 | | return !bodyDetection.CanHaveBody; |
| | | 166 | | } |
| | | 167 | | |
| | 2 | 168 | | HttpRequest request = httpContext.Request; |
| | 2 | 169 | | return request.ContentLength == 0 |
| | 2 | 170 | | || (request.ContentLength is null && string.IsNullOrEmpty(request.ContentType)); |
| | | 171 | | } |
| | | 172 | | |
| | | 173 | | private string[] GetExcludedFieldNames() |
| | | 174 | | { |
| | 44 | 175 | | List<string> names = [.. bindingOptions.ExcludedFieldNames]; |
| | | 176 | | |
| | 44 | 177 | | if (!string.IsNullOrWhiteSpace(antiforgeryOptions?.FormFieldName)) |
| | | 178 | | { |
| | 41 | 179 | | names.Add(antiforgeryOptions.FormFieldName); |
| | | 180 | | } |
| | | 181 | | |
| | 44 | 182 | | if (!string.IsNullOrWhiteSpace(grantOptions.TokenFormFieldName)) |
| | | 183 | | { |
| | 2 | 184 | | names.Add(grantOptions.TokenFormFieldName); |
| | | 185 | | } |
| | | 186 | | |
| | 44 | 187 | | return [.. names]; |
| | | 188 | | } |
| | | 189 | | } |
| | | 190 | | |
| | | 191 | | /// <summary> |
| | | 192 | | /// Configures <see cref="FormFieldCapabilityGrantRequestBindingProvider" />. |
| | | 193 | | /// </summary> |
| | | 194 | | public 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 | | } |