|
2 | 2 | // The .NET Foundation licenses this file to you under the Apache 2.0 License. |
3 | 3 | // See the LICENSE file in the project root for more information. |
4 | 4 |
|
5 | | -using System.Collections.Concurrent; |
6 | 5 | using System.Net.Http.Headers; |
| 6 | +using Microsoft.Extensions.Caching.Memory; |
| 7 | +using Microsoft.Extensions.Internal; |
| 8 | +using Microsoft.Extensions.Logging; |
7 | 9 | using Microsoft.IdentityModel.Tokens; |
| 10 | +using Steeltoe.Common.Extensions; |
8 | 11 |
|
9 | 12 | namespace Steeltoe.Security.Authentication.JwtBearer; |
10 | 13 |
|
11 | | -internal sealed class TokenKeyResolver |
| 14 | +internal sealed partial class TokenKeyResolver : IDisposable |
12 | 15 | { |
13 | 16 | private static readonly MediaTypeWithQualityHeaderValue AcceptHeader = new("application/json"); |
14 | | - private readonly HttpClient _httpClient; |
15 | | - private readonly Uri _authorityUri; |
| 17 | + private static readonly TimeSpan CacheTimeToLiveForKeyFound = TimeSpan.FromHours(12); |
| 18 | + private static readonly TimeSpan CacheMinTimeToLiveForKeyNotFound = TimeSpan.FromSeconds(30); |
| 19 | + private static readonly TimeSpan CacheMaxTimeToLiveForKeyNotFound = TimeSpan.FromSeconds(60); |
| 20 | + private readonly MemoryCache _cache; |
| 21 | + private readonly ILogger<TokenKeyResolver> _logger; |
16 | 22 |
|
17 | | - internal static ConcurrentDictionary<string, SecurityKey> ResolvedSecurityKeysById { get; } = new(); |
| 23 | + public TokenKeyResolver(TimeProvider timeProvider, ILoggerFactory loggerFactory) |
| 24 | + { |
| 25 | + ArgumentNullException.ThrowIfNull(timeProvider); |
| 26 | + ArgumentNullException.ThrowIfNull(loggerFactory); |
| 27 | + |
| 28 | + _cache = new MemoryCache(new MemoryCacheOptions |
| 29 | + { |
| 30 | + Clock = new TimeProviderSystemClock(timeProvider) |
| 31 | + }, loggerFactory); |
18 | 32 |
|
19 | | - public TokenKeyResolver(string authority, HttpClient httpClient) |
| 33 | + _logger = loggerFactory.CreateLogger<TokenKeyResolver>(); |
| 34 | + } |
| 35 | + |
| 36 | + internal JsonWebKey? ResolveSigningKey(string authority, string keyId, HttpClient httpClient) |
20 | 37 | { |
21 | 38 | ArgumentException.ThrowIfNullOrWhiteSpace(authority); |
| 39 | + ArgumentException.ThrowIfNullOrWhiteSpace(keyId); |
22 | 40 | ArgumentNullException.ThrowIfNull(httpClient); |
23 | 41 |
|
| 42 | + Uri tokenKeysUri = GetTokenKeysUri(authority); |
| 43 | + return CachingResolveSigningKey(tokenKeysUri, keyId, httpClient); |
| 44 | + } |
| 45 | + |
| 46 | + private static Uri GetTokenKeysUri(string authority) |
| 47 | + { |
24 | 48 | if (!authority.EndsWith('/')) |
25 | 49 | { |
26 | 50 | authority += '/'; |
27 | 51 | } |
28 | 52 |
|
29 | | - _authorityUri = new Uri($"{authority}token_keys"); |
30 | | - _httpClient = httpClient; |
| 53 | + var authorityUri = new Uri(authority); |
| 54 | + return new Uri(authorityUri, "token_keys"); |
31 | 55 | } |
32 | 56 |
|
33 | | - internal SecurityKey[] ResolveSigningKey(string keyId) |
| 57 | + private JsonWebKey? CachingResolveSigningKey(Uri tokenKeysUri, string keyId, HttpClient httpClient) |
34 | 58 | { |
35 | | - if (ResolvedSecurityKeysById.TryGetValue(keyId, out SecurityKey? resolved)) |
| 59 | + string cacheKey = GetCacheKey(tokenKeysUri, keyId); |
| 60 | + |
| 61 | + if (!_cache.TryGetValue<JsonWebKey?>(cacheKey, out JsonWebKey? matchingWebKey)) |
36 | 62 | { |
37 | | - return [resolved]; |
| 63 | + JsonWebKeySet? webKeySet = FetchKeySet(tokenKeysUri, httpClient); |
| 64 | + |
| 65 | + foreach (JsonWebKey nextWebKey in webKeySet?.Keys ?? []) |
| 66 | + { |
| 67 | + string nextCacheKey = GetCacheKey(tokenKeysUri, nextWebKey.Kid); |
| 68 | + _cache.Set(nextCacheKey, nextWebKey, CacheTimeToLiveForKeyFound); |
| 69 | + |
| 70 | + if (nextWebKey.Kid == keyId) |
| 71 | + { |
| 72 | + matchingWebKey = nextWebKey; |
| 73 | + } |
| 74 | + } |
| 75 | + |
| 76 | + if (matchingWebKey == null) |
| 77 | + { |
| 78 | + TimeSpan timeToLive = GetTimeToLiveForNotFound(); |
| 79 | + _cache.Set<JsonWebKey?>(cacheKey, null, timeToLive); |
| 80 | + |
| 81 | + if (webKeySet == null) |
| 82 | + { |
| 83 | + LogDisableFetchAfterServerError(keyId, (int)timeToLive.TotalSeconds); |
| 84 | + } |
| 85 | + else |
| 86 | + { |
| 87 | + LogDisableFetchAfterKeyNotFound(keyId, (int)timeToLive.TotalSeconds); |
| 88 | + } |
| 89 | + } |
38 | 90 | } |
39 | 91 |
|
| 92 | + return matchingWebKey; |
| 93 | + } |
| 94 | + |
| 95 | + private static string GetCacheKey(Uri tokenKeysUri, string keyId) |
| 96 | + { |
| 97 | + return $"{tokenKeysUri}:{keyId}"; |
| 98 | + } |
| 99 | + |
| 100 | + private static TimeSpan GetTimeToLiveForNotFound() |
| 101 | + { |
| 102 | + double jitterSeconds = Random.Shared.NextDouble() * (CacheMaxTimeToLiveForKeyNotFound - CacheMinTimeToLiveForKeyNotFound).TotalSeconds; |
| 103 | + return CacheMinTimeToLiveForKeyNotFound + TimeSpan.FromSeconds(jitterSeconds); |
| 104 | + } |
| 105 | + |
| 106 | + private JsonWebKeySet? FetchKeySet(Uri tokenKeysUri, HttpClient httpClient) |
| 107 | + { |
40 | 108 | #pragma warning disable S4462 // Calls to "async" methods should not be blocking |
41 | 109 | // Justification: can't be async all the way until updates are complete in Microsoft libraries |
42 | 110 | // https://github.com/AzureAD/azure-activedirectory-identitymodel-extensions-for-dotnet/issues/468 |
43 | | - JsonWebKeySet? keySet = FetchKeySetAsync(CancellationToken.None).GetAwaiter().GetResult(); |
| 111 | + return FetchKeySetAsync(tokenKeysUri, httpClient, CancellationToken.None).GetAwaiter().GetResult(); |
44 | 112 | #pragma warning restore S4462 // Calls to "async" methods should not be blocking |
| 113 | + } |
| 114 | + |
| 115 | + private async Task<JsonWebKeySet?> FetchKeySetAsync(Uri tokenKeysUri, HttpClient httpClient, CancellationToken cancellationToken) |
| 116 | + { |
| 117 | + using var requestMessage = new HttpRequestMessage(HttpMethod.Get, tokenKeysUri); |
| 118 | + requestMessage.Headers.Accept.Add(AcceptHeader); |
45 | 119 |
|
46 | | - if (keySet != null) |
| 120 | + HttpResponseMessage response; |
| 121 | + |
| 122 | + try |
47 | 123 | { |
48 | | - foreach (JsonWebKey key in keySet.Keys) |
49 | | - { |
50 | | - ResolvedSecurityKeysById[key.Kid] = key; |
51 | | - } |
| 124 | + response = await httpClient.SendAsync(requestMessage, cancellationToken); |
| 125 | + } |
| 126 | + catch (Exception exception) when (exception is HttpRequestException || exception.IsHttpClientTimeout()) |
| 127 | + { |
| 128 | + LogTokenKeysEndpointUnreachable(exception, tokenKeysUri); |
| 129 | + return null; |
52 | 130 | } |
53 | 131 |
|
54 | | - if (ResolvedSecurityKeysById.TryGetValue(keyId, out resolved)) |
| 132 | + if (!response.IsSuccessStatusCode) |
55 | 133 | { |
56 | | - return [resolved]; |
| 134 | + LogFetchTokenKeysStatusFailed(tokenKeysUri, (int)response.StatusCode); |
| 135 | + return null; |
57 | 136 | } |
58 | 137 |
|
59 | | - return []; |
| 138 | + try |
| 139 | + { |
| 140 | + string result = await response.Content.ReadAsStringAsync(cancellationToken); |
| 141 | + return JsonWebKeySet.Create(result); |
| 142 | + } |
| 143 | + catch (ArgumentException exception) |
| 144 | + { |
| 145 | + LogFetchTokenKeysParseFailed(exception, tokenKeysUri); |
| 146 | + return null; |
| 147 | + } |
60 | 148 | } |
61 | 149 |
|
62 | | - internal async Task<JsonWebKeySet?> FetchKeySetAsync(CancellationToken cancellationToken) |
| 150 | + public void Dispose() |
63 | 151 | { |
64 | | - using var requestMessage = new HttpRequestMessage(HttpMethod.Get, _authorityUri); |
65 | | - requestMessage.Headers.Accept.Add(AcceptHeader); |
| 152 | + _cache.Dispose(); |
| 153 | + } |
66 | 154 |
|
67 | | - HttpResponseMessage response = await _httpClient.SendAsync(requestMessage, cancellationToken); |
| 155 | + [LoggerMessage(LogLevel.Warning, "Fetch keys from '{TokenKeysUri}' failed.")] |
| 156 | + private partial void LogTokenKeysEndpointUnreachable(Exception exception, MaskedUri tokenKeysUri); |
68 | 157 |
|
69 | | - if (!response.IsSuccessStatusCode) |
| 158 | + [LoggerMessage(LogLevel.Warning, "Fetch keys from '{TokenKeysUri}' failed with HTTP status {StatusCode}.")] |
| 159 | + private partial void LogFetchTokenKeysStatusFailed(MaskedUri tokenKeysUri, int statusCode); |
| 160 | + |
| 161 | + [LoggerMessage(LogLevel.Warning, "Fetch keys from '{TokenKeysUri}' failed because the returned JSON is invalid.")] |
| 162 | + private partial void LogFetchTokenKeysParseFailed(Exception exception, MaskedUri tokenKeysUri); |
| 163 | + |
| 164 | + [LoggerMessage(LogLevel.Information, "Disabled fetch for key '{KeyId}' for {RetryAfterSeconds}s because the HTTP request failed.")] |
| 165 | + private partial void LogDisableFetchAfterServerError(string keyId, int retryAfterSeconds); |
| 166 | + |
| 167 | + [LoggerMessage(LogLevel.Information, "Disabled fetch for key '{KeyId}' for {RetryAfterSeconds}s because the key was not found in the HTTP response.")] |
| 168 | + private partial void LogDisableFetchAfterKeyNotFound(string keyId, int retryAfterSeconds); |
| 169 | + |
| 170 | + private sealed class TimeProviderSystemClock : ISystemClock |
| 171 | + { |
| 172 | + private readonly TimeProvider _timeProvider; |
| 173 | + |
| 174 | + public DateTimeOffset UtcNow => _timeProvider.GetUtcNow(); |
| 175 | + |
| 176 | + public TimeProviderSystemClock(TimeProvider timeProvider) |
70 | 177 | { |
71 | | - return null; |
| 178 | + ArgumentNullException.ThrowIfNull(timeProvider); |
| 179 | + _timeProvider = timeProvider; |
72 | 180 | } |
73 | | - |
74 | | - string result = await response.Content.ReadAsStringAsync(cancellationToken); |
75 | | - return JsonWebKeySet.Create(result); |
76 | 181 | } |
77 | 182 | } |
0 commit comments