| | | 1 | | using System.Text; |
| | | 2 | | using System.Text.Encodings.Web; |
| | | 3 | | using Kestrun.Hosting; |
| | | 4 | | using Microsoft.AspNetCore.Authentication; |
| | | 5 | | using Microsoft.Extensions.Options; |
| | | 6 | | using Microsoft.Extensions.Primitives; |
| | | 7 | | |
| | | 8 | | namespace Kestrun.Authentication; |
| | | 9 | | |
| | | 10 | | /// <summary> |
| | | 11 | | /// Handles API Key authentication for incoming HTTP requests. |
| | | 12 | | /// </summary> |
| | | 13 | | public class ApiKeyAuthHandler |
| | | 14 | | : AuthenticationHandler<ApiKeyAuthenticationOptions> |
| | | 15 | | { |
| | | 16 | | /// <summary> The Kestrun host instance. </summary> |
| | 0 | 17 | | public KestrunHost Host { get; } |
| | | 18 | | |
| | | 19 | | /// <summary> |
| | | 20 | | /// Initializes a new instance of the <see cref="ApiKeyAuthHandler"/> class. |
| | | 21 | | /// </summary> |
| | | 22 | | /// <param name="host">The Kestrun host instance.</param> |
| | | 23 | | /// <param name="options">The options monitor for API key authentication options.</param> |
| | | 24 | | /// <param name="logger">The logger factory.</param> |
| | | 25 | | /// <param name="encoder">The URL encoder.</param> |
| | | 26 | | public ApiKeyAuthHandler(KestrunHost host, |
| | | 27 | | IOptionsMonitor<ApiKeyAuthenticationOptions> options, |
| | | 28 | | ILoggerFactory logger, |
| | | 29 | | UrlEncoder encoder) |
| | 12 | 30 | | : base(options, logger, encoder) |
| | | 31 | | { |
| | 12 | 32 | | ArgumentNullException.ThrowIfNull(host); |
| | 12 | 33 | | Host = host; |
| | 12 | 34 | | if (options.CurrentValue.Logger.IsEnabled(Serilog.Events.LogEventLevel.Debug)) |
| | | 35 | | { |
| | 9 | 36 | | options.CurrentValue.Logger.Debug("ApiKeyAuthHandler initialized"); |
| | | 37 | | } |
| | 12 | 38 | | } |
| | | 39 | | |
| | | 40 | | /// <summary> |
| | | 41 | | /// Authenticates the incoming request using an API key. |
| | | 42 | | /// </summary> |
| | | 43 | | /// <returns>An <see cref="AuthenticateResult"/> indicating the authentication outcome.</returns> |
| | | 44 | | protected override async Task<AuthenticateResult> HandleAuthenticateAsync() |
| | | 45 | | { |
| | | 46 | | try |
| | | 47 | | { |
| | 11 | 48 | | if (Options.Logger.IsEnabled(Serilog.Events.LogEventLevel.Debug)) |
| | | 49 | | { |
| | 8 | 50 | | Options.Logger.Debug("Handling API Key authentication for request: {Request}", Request); |
| | | 51 | | } |
| | | 52 | | |
| | 11 | 53 | | if (Options.RequireHttps && !Request.IsHttps) |
| | | 54 | | { |
| | 1 | 55 | | return Fail("HTTPS required"); |
| | | 56 | | } |
| | | 57 | | |
| | 10 | 58 | | if (!TryGetApiKey(out var providedKey)) |
| | | 59 | | { |
| | 1 | 60 | | return Fail("Missing API Key"); |
| | | 61 | | } |
| | | 62 | | |
| | 9 | 63 | | var providedKeyBytes = Encoding.UTF8.GetBytes(providedKey); |
| | 9 | 64 | | var valid = await ValidateApiKeyAsync(providedKey, providedKeyBytes); |
| | 9 | 65 | | if (!valid) |
| | | 66 | | { |
| | 3 | 67 | | return Fail($"Invalid API Key: {providedKey}"); |
| | | 68 | | } |
| | | 69 | | |
| | 6 | 70 | | var ticket = await CreateTicketAsync(providedKey); |
| | 6 | 71 | | if (ticket.Principal is null) |
| | | 72 | | { |
| | 0 | 73 | | return Fail("Authentication ticket has no principal"); |
| | | 74 | | } |
| | 6 | 75 | | Options.Logger.Information("API Key authentication succeeded for identity: {Identity}", ticket.Principal.Ide |
| | | 76 | | |
| | 6 | 77 | | return AuthenticateResult.Success(ticket); |
| | | 78 | | } |
| | 0 | 79 | | catch (Exception ex) |
| | | 80 | | { |
| | 0 | 81 | | Options.Logger.Error(ex, "API Key authentication failed with exception."); |
| | 0 | 82 | | return Fail("Error processing API Key"); |
| | | 83 | | } |
| | 11 | 84 | | } |
| | | 85 | | |
| | | 86 | | /// <summary> |
| | | 87 | | /// Tries to retrieve the API key from the request headers or query string. |
| | | 88 | | /// </summary> |
| | | 89 | | /// <param name="providedKey">The retrieved API key.</param> |
| | | 90 | | /// <returns>True if the API key was found; otherwise, false.</returns> |
| | | 91 | | private bool TryGetApiKey(out string providedKey) |
| | | 92 | | { |
| | 10 | 93 | | providedKey = string.Empty; |
| | | 94 | | |
| | | 95 | | // Primary header |
| | 10 | 96 | | if (!Request.Headers.TryGetValue(Options.HeaderName, out var values)) |
| | | 97 | | { |
| | | 98 | | // Additional headers |
| | 11 | 99 | | foreach (var header in Options.AdditionalHeaderNames) |
| | | 100 | | { |
| | 3 | 101 | | if (Request.Headers.TryGetValue(header, out values)) |
| | | 102 | | { |
| | | 103 | | break; |
| | | 104 | | } |
| | | 105 | | } |
| | | 106 | | } |
| | | 107 | | |
| | | 108 | | // Query string fallback |
| | 10 | 109 | | if ((values.Count == 0 || StringValues.IsNullOrEmpty(values)) |
| | 10 | 110 | | && Options.AllowQueryStringFallback |
| | 10 | 111 | | && Request.Query.TryGetValue(Options.HeaderName, out var qsValues)) |
| | | 112 | | { |
| | 2 | 113 | | values = qsValues; |
| | | 114 | | } |
| | | 115 | | |
| | 10 | 116 | | if (StringValues.IsNullOrEmpty(values)) |
| | | 117 | | { |
| | 1 | 118 | | return false; |
| | | 119 | | } |
| | | 120 | | |
| | | 121 | | // Normalize potential whitespace/newlines from transport |
| | 9 | 122 | | providedKey = values.ToString().Trim(); |
| | 9 | 123 | | return true; |
| | | 124 | | } |
| | | 125 | | |
| | | 126 | | /// <summary> |
| | | 127 | | /// Validates the provided API key against the expected key or a custom validation method. |
| | | 128 | | /// </summary> |
| | | 129 | | /// <param name="providedKey">The API key provided by the client.</param> |
| | | 130 | | /// <param name="providedKeyBytes">The byte representation of the provided API key.</param> |
| | | 131 | | /// <returns>True if the API key is valid; otherwise, false.</returns> |
| | | 132 | | private async Task<bool> ValidateApiKeyAsync(string providedKey, byte[] providedKeyBytes) |
| | | 133 | | { |
| | 9 | 134 | | return Options.ExpectedKeyBytes is not null |
| | 9 | 135 | | ? FixedTimeEquals.Test(providedKeyBytes, Options.ExpectedKeyBytes) |
| | 9 | 136 | | : Options.ValidateKeyAsync is not null |
| | 9 | 137 | | ? await Options.ValidateKeyAsync(Context, providedKey, providedKeyBytes) |
| | 9 | 138 | | : throw new InvalidOperationException( |
| | 9 | 139 | | "No API key validation configured. Either set ValidateKey or ExpectedKey in ApiKeyAuthenticationOptions."); |
| | 9 | 140 | | } |
| | | 141 | | |
| | | 142 | | /// <summary> |
| | | 143 | | /// Creates an authentication ticket for the provided API key. |
| | | 144 | | /// </summary> |
| | | 145 | | /// <param name="providedKey"></param> |
| | | 146 | | /// <returns></returns> |
| | | 147 | | private Task<AuthenticationTicket> CreateTicketAsync(string providedKey) |
| | 6 | 148 | | => IAuthHandler.GetAuthenticationTicketAsync(Context, providedKey, Options, Scheme, "ApiKeyClient"); |
| | | 149 | | |
| | | 150 | | /// <summary> |
| | | 151 | | /// Fails the authentication process with the specified reason. |
| | | 152 | | /// </summary> |
| | | 153 | | /// <param name="reason">The reason for the failure.</param> |
| | | 154 | | /// <returns>An <see cref="AuthenticateResult"/> indicating the failure.</returns> |
| | | 155 | | private AuthenticateResult Fail(string reason) |
| | | 156 | | { |
| | 5 | 157 | | Options.Logger.Warning("API Key authentication failed: {Reason}", reason); |
| | 5 | 158 | | return AuthenticateResult.Fail(reason); |
| | | 159 | | } |
| | | 160 | | |
| | | 161 | | /// <summary> |
| | | 162 | | /// Handles the authentication challenge by setting the appropriate response headers and status code. |
| | | 163 | | /// </summary> |
| | | 164 | | /// <param name="properties">Authentication properties for the challenge.</param> |
| | | 165 | | /// <returns>A completed task.</returns> |
| | | 166 | | protected override Task HandleChallengeAsync(AuthenticationProperties properties) |
| | | 167 | | { |
| | 1 | 168 | | if (Options.EmitChallengeHeader) |
| | | 169 | | { |
| | 1 | 170 | | var header = Options.HeaderName ?? "X-Api-Key"; |
| | | 171 | | |
| | 1 | 172 | | var value = Options.ChallengeHeaderFormat == ApiKeyChallengeFormat.ApiKeyHeader |
| | 1 | 173 | | ? $"ApiKey header=\"{header}\"" |
| | 1 | 174 | | : header; |
| | | 175 | | |
| | 1 | 176 | | Response.Headers.WWWAuthenticate = value; |
| | | 177 | | } |
| | 1 | 178 | | Response.StatusCode = StatusCodes.Status401Unauthorized; |
| | 1 | 179 | | return Task.CompletedTask; |
| | | 180 | | } |
| | | 181 | | /// <summary> |
| | | 182 | | /// Builds a PowerShell-based API key validator delegate using the provided authentication code settings. |
| | | 183 | | /// </summary> |
| | | 184 | | ///<param name="host">The Kestrun host instance.</param> |
| | | 185 | | /// <param name="settings">The settings containing the PowerShell authentication code.</param> |
| | | 186 | | /// <returns>A delegate that validates an API key using PowerShell code.</returns> |
| | | 187 | | /// <remarks> |
| | | 188 | | /// This method compiles the PowerShell script and returns a delegate that can be used to validate API keys. |
| | | 189 | | /// </remarks> |
| | | 190 | | public static Func<HttpContext, string, byte[], Task<bool>> BuildPsValidator( |
| | | 191 | | KestrunHost host, |
| | | 192 | | AuthenticationCodeSettings settings) |
| | | 193 | | { |
| | 2 | 194 | | if (host.Logger.IsEnabled(Serilog.Events.LogEventLevel.Debug)) |
| | | 195 | | { |
| | 2 | 196 | | host.Logger.Debug("BuildPsValidator settings: {Settings}", settings); |
| | | 197 | | } |
| | | 198 | | |
| | 2 | 199 | | return async (ctx, providedKey, providedKeyBytes) => |
| | 2 | 200 | | { |
| | 2 | 201 | | return await IAuthHandler.ValidatePowerShellAsync(settings.Code, ctx, new Dictionary<string, string> |
| | 2 | 202 | | { |
| | 2 | 203 | | { "providedKey", providedKey }, |
| | 2 | 204 | | { "providedKeyBytes", Convert.ToBase64String(providedKeyBytes) } |
| | 2 | 205 | | }, host.Logger); |
| | 4 | 206 | | }; |
| | | 207 | | } |
| | | 208 | | |
| | | 209 | | /// <summary> |
| | | 210 | | /// Builds a C#-based API key validator delegate using the provided authentication code settings. |
| | | 211 | | /// </summary> |
| | | 212 | | /// <param name="host">The Kestrun host instance.</param> |
| | | 213 | | /// <param name="settings">The settings containing the C# authentication code.</param> |
| | | 214 | | /// <returns>A delegate that validates an API key using C# code.</returns> |
| | | 215 | | public static Func<HttpContext, string, byte[], Task<bool>> BuildCsValidator( |
| | | 216 | | KestrunHost host, |
| | | 217 | | AuthenticationCodeSettings settings) |
| | | 218 | | { |
| | 1 | 219 | | if (host.Logger.IsEnabled(Serilog.Events.LogEventLevel.Debug)) |
| | | 220 | | { |
| | 1 | 221 | | host.Logger.Debug("BuildCsValidator settings: {Settings}", settings); |
| | | 222 | | } |
| | | 223 | | // pass the settings to the core C# validator |
| | 1 | 224 | | var core = IAuthHandler.BuildCsValidator(host, |
| | 1 | 225 | | settings, |
| | 1 | 226 | | ("providedKey", string.Empty), ("providedKeyBytes", Array.Empty<byte>()) |
| | 1 | 227 | | ) ?? throw new InvalidOperationException("Failed to build C# validator delegate from provided settings."); |
| | 1 | 228 | | return (ctx, providedKey, providedKeyBytes) => |
| | 3 | 229 | | core(ctx, new Dictionary<string, object?> |
| | 3 | 230 | | { |
| | 3 | 231 | | ["providedKey"] = providedKey, |
| | 3 | 232 | | ["providedKeyBytes"] = providedKeyBytes |
| | 3 | 233 | | }); |
| | | 234 | | } |
| | | 235 | | |
| | | 236 | | /// <summary> |
| | | 237 | | /// Builds a VB.NET-based API key validator delegate using the provided authentication code settings. |
| | | 238 | | /// </summary> |
| | | 239 | | /// <param name="host">The Kestrun host instance.</param> |
| | | 240 | | /// <param name="settings">The settings containing the VB.NET authentication code.</param> |
| | | 241 | | /// <returns>A delegate that validates an API key using VB.NET code.</returns> |
| | | 242 | | public static Func<HttpContext, string, byte[], Task<bool>> BuildVBNetValidator( |
| | | 243 | | KestrunHost host, |
| | | 244 | | AuthenticationCodeSettings settings) |
| | | 245 | | { |
| | 2 | 246 | | if (host.Logger.IsEnabled(Serilog.Events.LogEventLevel.Debug)) |
| | | 247 | | { |
| | 1 | 248 | | host.Logger.Debug("BuildVBNetValidator settings: {Settings}", settings); |
| | | 249 | | } |
| | | 250 | | // pass the settings to the core VB.NET validator |
| | 2 | 251 | | var core = IAuthHandler.BuildVBNetValidator(host, |
| | 2 | 252 | | settings, |
| | 2 | 253 | | ("providedKey", string.Empty), ("providedKeyBytes", Array.Empty<byte>()) |
| | 2 | 254 | | ) ?? throw new InvalidOperationException("Failed to build VB.NET validator delegate from provided settings." |
| | 2 | 255 | | return (ctx, providedKey, providedKeyBytes) => |
| | 4 | 256 | | core(ctx, new Dictionary<string, object?> |
| | 4 | 257 | | { |
| | 4 | 258 | | ["providedKey"] = providedKey, |
| | 4 | 259 | | ["providedKeyBytes"] = providedKeyBytes |
| | 4 | 260 | | }); |
| | | 261 | | } |
| | | 262 | | } |