|
| 1 | +// Copyright (c) Six Labors. |
| 2 | +// Licensed under the Apache License, Version 2.0. |
| 3 | + |
| 4 | +using System; |
| 5 | +using System.Collections.Generic; |
| 6 | +using System.Runtime.CompilerServices; |
| 7 | +using System.Threading.Tasks; |
| 8 | +using Microsoft.AspNetCore.Http; |
| 9 | + |
| 10 | +#if !NETCOREAPP3_0_OR_GREATER |
| 11 | +using Microsoft.AspNetCore.Http.Internal; |
| 12 | +#endif |
| 13 | + |
| 14 | +using Microsoft.AspNetCore.WebUtilities; |
| 15 | +using Microsoft.Extensions.Options; |
| 16 | +using SixLabors.ImageSharp.Web.Commands; |
| 17 | +using SixLabors.ImageSharp.Web.Middleware; |
| 18 | +using SixLabors.ImageSharp.Web.Processors; |
| 19 | + |
| 20 | +namespace SixLabors.ImageSharp.Web |
| 21 | +{ |
| 22 | + /// <summary> |
| 23 | + /// Contains various helper methods for authorizing image requests. |
| 24 | + /// </summary> |
| 25 | + public sealed class ImageSharpRequestAuthorizationUtilities |
| 26 | + { |
| 27 | + /// <summary> |
| 28 | + /// The command used by image requests for transporting Hash-based Message Authentication Code (HMAC) tokens. |
| 29 | + /// </summary> |
| 30 | + public const string TokenCommand = HMACUtilities.TokenCommand; |
| 31 | + |
| 32 | + private static readonly Uri FallbackBaseUri = new("http://localhost/"); |
| 33 | + private readonly HashSet<string> knownCommands; |
| 34 | + private readonly ImageSharpMiddlewareOptions options; |
| 35 | + private readonly IRequestParser requestParser; |
| 36 | + private readonly IServiceProvider serviceProvider; |
| 37 | + |
| 38 | + /// <summary> |
| 39 | + /// Initializes a new instance of the <see cref="ImageSharpRequestAuthorizationUtilities"/> class. |
| 40 | + /// </summary> |
| 41 | + /// <param name="options">The middleware configuration options.</param> |
| 42 | + /// <param name="requestParser">An <see cref="IRequestParser"/> instance used to parse image requests for commands.</param> |
| 43 | + /// <param name="processors">A collection of <see cref="IImageWebProcessor"/> instances used to process images.</param> |
| 44 | + /// <param name="serviceProvider">The service provider.</param> |
| 45 | + public ImageSharpRequestAuthorizationUtilities( |
| 46 | + IOptions<ImageSharpMiddlewareOptions> options, |
| 47 | + IRequestParser requestParser, |
| 48 | + IEnumerable<IImageWebProcessor> processors, |
| 49 | + IServiceProvider serviceProvider) |
| 50 | + { |
| 51 | + Guard.NotNull(options, nameof(options)); |
| 52 | + Guard.NotNull(requestParser, nameof(requestParser)); |
| 53 | + Guard.NotNull(processors, nameof(processors)); |
| 54 | + Guard.NotNull(serviceProvider, nameof(serviceProvider)); |
| 55 | + |
| 56 | + HashSet<string> commands = new(StringComparer.OrdinalIgnoreCase); |
| 57 | + foreach (IImageWebProcessor processor in processors) |
| 58 | + { |
| 59 | + foreach (string command in processor.Commands) |
| 60 | + { |
| 61 | + commands.Add(command); |
| 62 | + } |
| 63 | + } |
| 64 | + |
| 65 | + this.knownCommands = commands; |
| 66 | + this.options = options.Value; |
| 67 | + } |
| 68 | + |
| 69 | + /// <summary> |
| 70 | + /// Strips any unknown commands from the command collection. |
| 71 | + /// </summary> |
| 72 | + /// <param name="commands">The unsanitized command collection.</param> |
| 73 | + public void StripUnknownCommands(CommandCollection commands) |
| 74 | + { |
| 75 | + if (commands?.Count > 0) |
| 76 | + { |
| 77 | + // Strip out any unknown commands, if needed. |
| 78 | + var keys = new List<string>(commands.Keys); |
| 79 | + for (int i = keys.Count - 1; i >= 0; i--) |
| 80 | + { |
| 81 | + if (!this.knownCommands.Contains(keys[i])) |
| 82 | + { |
| 83 | + commands.RemoveAt(i); |
| 84 | + } |
| 85 | + } |
| 86 | + } |
| 87 | + } |
| 88 | + |
| 89 | + /// <summary> |
| 90 | + /// Compute a Hash-based Message Authentication Code (HMAC) for request authentication. |
| 91 | + /// </summary> |
| 92 | + /// <param name="uri">The uri to compute the code from.</param> |
| 93 | + /// <returns>The computed HMAC.</returns> |
| 94 | + public string ComputeHMAC(string uri) |
| 95 | + => this.ComputeHMAC(new Uri(uri)); |
| 96 | + |
| 97 | + /// <summary> |
| 98 | + /// Compute a Hash-based Message Authentication Code (HMAC) for request authentication. |
| 99 | + /// </summary> |
| 100 | + /// <param name="uri">The uri to compute the code from.</param> |
| 101 | + /// <returns>The computed HMAC.</returns> |
| 102 | + public string ComputeHMAC(Uri uri) |
| 103 | + => AsyncHelper.RunSync(() => this.ComputeHMACAsync(uri)); |
| 104 | + |
| 105 | + /// <summary> |
| 106 | + /// Compute a Hash-based Message Authentication Code (HMAC) for request authentication. |
| 107 | + /// </summary> |
| 108 | + /// <param name="uri">The uri to compute the code from.</param> |
| 109 | + /// <returns>The computed HMAC.</returns> |
| 110 | + public Task<string> ComputeHMACAsync(string uri) |
| 111 | + => this.ComputeHMACAsync(new Uri(uri)); |
| 112 | + |
| 113 | + /// <summary> |
| 114 | + /// Compute a Hash-based Message Authentication Code (HMAC) for request authentication. |
| 115 | + /// </summary> |
| 116 | + /// <param name="uri">The uri to compute the code from.</param> |
| 117 | + /// <returns>The computed HMAC.</returns> |
| 118 | + public async Task<string> ComputeHMACAsync(Uri uri) |
| 119 | + { |
| 120 | + byte[] secret = this.options.HMACSecretKey; |
| 121 | + if (secret is null || secret.Length == 0) |
| 122 | + { |
| 123 | + return null; |
| 124 | + } |
| 125 | + |
| 126 | + // We need to generate a HttpRequest to use the rest of the services. |
| 127 | + DefaultHttpContext context = new() { RequestServices = this.serviceProvider }; |
| 128 | + HttpRequest request = context.Request; |
| 129 | + |
| 130 | + ToComponents( |
| 131 | + uri, |
| 132 | + out HostString host, |
| 133 | + out PathString path, |
| 134 | + out QueryString queryString, |
| 135 | + out QueryCollection query); |
| 136 | + |
| 137 | + request.Host = host; |
| 138 | + request.Path = path; |
| 139 | + request.QueryString = queryString; |
| 140 | + request.Query = query; |
| 141 | + |
| 142 | + CommandCollection commands = this.requestParser.ParseRequestCommands(context); |
| 143 | + |
| 144 | + // The provided URI should not contain invalid commands since image URI geneneration |
| 145 | + // should be tightly controlled by the running application but we will strip any out anyway. |
| 146 | + this.StripUnknownCommands(commands); |
| 147 | + |
| 148 | + ImageCommandContext imageCommandContext = new(context, commands, null, null); |
| 149 | + return await this.options.OnComputeHMACAsync(imageCommandContext, secret); |
| 150 | + } |
| 151 | + |
| 152 | + private static void ToComponents( |
| 153 | + Uri uri, |
| 154 | + out HostString host, |
| 155 | + out PathString path, |
| 156 | + out QueryString queryString, |
| 157 | + out QueryCollection query) |
| 158 | + { |
| 159 | + if (uri.IsAbsoluteUri) |
| 160 | + { |
| 161 | + host = HostString.FromUriComponent(uri); |
| 162 | + path = PathString.FromUriComponent(uri); |
| 163 | + queryString = QueryString.FromUriComponent(uri); |
| 164 | + query = GetQueryComponent(queryString); |
| 165 | + } |
| 166 | + else |
| 167 | + { |
| 168 | + Uri faux = new(FallbackBaseUri, uri); |
| 169 | + host = default; |
| 170 | + path = PathString.FromUriComponent(faux); |
| 171 | + queryString = QueryString.FromUriComponent(faux); |
| 172 | + query = GetQueryComponent(queryString); |
| 173 | + } |
| 174 | + } |
| 175 | + |
| 176 | + [MethodImpl(MethodImplOptions.AggressiveInlining)] |
| 177 | + private static QueryCollection GetQueryComponent(QueryString query) |
| 178 | + => new(QueryHelpers.ParseQuery(query.Value)); |
| 179 | + } |
| 180 | +} |
0 commit comments