| | | 1 | | #nullable enable |
| | | 2 | | |
| | | 3 | | using System; |
| | | 4 | | using System.Linq; |
| | | 5 | | using System.Net.Http; |
| | | 6 | | using System.Net.Http.Headers; |
| | | 7 | | using System.Threading; |
| | | 8 | | using System.Threading.Tasks; |
| | | 9 | | |
| | | 10 | | namespace dotnet_etcd; |
| | | 11 | | |
| | | 12 | | /// <summary> |
| | | 13 | | /// DelegatingHandler that attaches an etcd auth token to outgoing requests. Fetches |
| | | 14 | | /// the token via the supplied provider, caches it for the configured duration, and |
| | | 15 | | /// bypasses the Authenticate RPC itself so the token-fetch call doesn't recurse. |
| | | 16 | | /// </summary> |
| | | 17 | | internal sealed class AuthenticationHttpHandler : DelegatingHandler |
| | | 18 | | { |
| | | 19 | | private const string AuthorizationHeader = "authorization"; |
| | | 20 | | private const string AuthenticatePath = "/etcdserverpb.Auth/Authenticate"; |
| | | 21 | | private const string GrpcStatusHeader = "grpc-status"; |
| | | 22 | | private const string GrpcStatusUnauthenticated = "16"; // StatusCode.Unauthenticated |
| | | 23 | | |
| | 124 | 24 | | private readonly SemaphoreSlim _semaphore = new(1, 1); |
| | | 25 | | private readonly Func< |
| | | 26 | | CancellationToken, |
| | | 27 | | Task<(string token, TimeSpan cacheDuration)?> |
| | | 28 | | > _tokenProvider; |
| | | 29 | | |
| | | 30 | | private CachedToken? _cachedToken; |
| | | 31 | | private volatile bool _disposed; |
| | | 32 | | |
| | | 33 | | public AuthenticationHttpHandler( |
| | | 34 | | Func<CancellationToken, Task<(string token, TimeSpan cacheDuration)?>> tokenProvider, |
| | | 35 | | HttpMessageHandler innerHandler |
| | | 36 | | ) |
| | 124 | 37 | | : base(innerHandler) |
| | 124 | 38 | | { |
| | 124 | 39 | | _tokenProvider = tokenProvider ?? throw new ArgumentNullException(nameof(tokenProvider)); |
| | 123 | 40 | | } |
| | | 41 | | |
| | | 42 | | /// <summary> |
| | | 43 | | /// Clears any cached token so the next request re-fetches via the token provider. |
| | | 44 | | /// Call this after credentials change so in-flight cached tokens don't outlive the change. |
| | | 45 | | /// </summary> |
| | | 46 | | public void InvalidateToken() |
| | 70 | 47 | | { |
| | 70 | 48 | | if (_disposed) |
| | 1 | 49 | | return; |
| | | 50 | | |
| | | 51 | | try |
| | 69 | 52 | | { |
| | 69 | 53 | | _semaphore.Wait(); |
| | 69 | 54 | | } |
| | 0 | 55 | | catch (ObjectDisposedException) |
| | 0 | 56 | | { |
| | | 57 | | // Lost a race with Dispose() — nothing to invalidate on a disposed handler. |
| | 0 | 58 | | return; |
| | | 59 | | } |
| | | 60 | | |
| | | 61 | | try |
| | 69 | 62 | | { |
| | 69 | 63 | | _cachedToken = null; |
| | 69 | 64 | | } |
| | | 65 | | finally |
| | 69 | 66 | | { |
| | 69 | 67 | | _semaphore.Release(); |
| | 69 | 68 | | } |
| | 70 | 69 | | } |
| | | 70 | | |
| | | 71 | | protected override async Task<HttpResponseMessage> SendAsync( |
| | | 72 | | HttpRequestMessage request, |
| | | 73 | | CancellationToken cancellationToken |
| | | 74 | | ) |
| | 601 | 75 | | { |
| | | 76 | | // If the request is an authorization request, we do nothing to prevent deadlocking |
| | 601 | 77 | | if (request.RequestUri?.AbsolutePath == AuthenticatePath) |
| | 62 | 78 | | return await base.SendAsync(request, cancellationToken).ConfigureAwait(false); |
| | | 79 | | |
| | 539 | 80 | | string? token = await GetValidTokenAsync(cancellationToken).ConfigureAwait(false); |
| | 522 | 81 | | bool tokenAttached = !string.IsNullOrWhiteSpace(token); |
| | 522 | 82 | | if (tokenAttached) |
| | 178 | 83 | | { |
| | | 84 | | // Replace any existing authorization header. Use TryAddWithoutValidation so opaque |
| | | 85 | | // etcd tokens (JWT/base64 containing '+', '/', '=') aren't rejected by the typed |
| | | 86 | | // Authorization header parser, which would otherwise throw FormatException. |
| | 178 | 87 | | request.Headers.Remove(AuthorizationHeader); |
| | 178 | 88 | | request.Headers.TryAddWithoutValidation(AuthorizationHeader, token); |
| | 178 | 89 | | } |
| | | 90 | | |
| | 522 | 91 | | HttpResponseMessage response = await base.SendAsync(request, cancellationToken) |
| | 522 | 92 | | .ConfigureAwait(false); |
| | | 93 | | |
| | | 94 | | // If etcd rejected the token we attached, purge the cache so the next attempt (e.g. a |
| | | 95 | | // watch/lease stream re-establishing) fetches a fresh token instead of replaying the |
| | | 96 | | // rejected one. See issue #283. |
| | 517 | 97 | | if (tokenAttached && IsUnauthenticated(response)) |
| | 3 | 98 | | InvalidateToken(); |
| | | 99 | | |
| | 517 | 100 | | return response; |
| | 579 | 101 | | } |
| | | 102 | | |
| | | 103 | | private static bool IsUnauthenticated(HttpResponseMessage response) |
| | 178 | 104 | | { |
| | | 105 | | // A gRPC error surfaces grpc-status either in the initial headers (a "trailers-only" |
| | | 106 | | // response, which is how etcd fast-fails an invalid/expired token) or in the trailing |
| | | 107 | | // headers. Check both so we catch the rejection wherever it lands. |
| | 178 | 108 | | return HasUnauthenticatedStatus(response.Headers) |
| | 178 | 109 | | || HasUnauthenticatedStatus(response.TrailingHeaders); |
| | 178 | 110 | | } |
| | | 111 | | |
| | | 112 | | private static bool HasUnauthenticatedStatus(HttpResponseHeaders headers) |
| | 353 | 113 | | { |
| | 353 | 114 | | return headers.TryGetValues(GrpcStatusHeader, out var values) |
| | 353 | 115 | | && values.Contains(GrpcStatusUnauthenticated); |
| | 353 | 116 | | } |
| | | 117 | | |
| | | 118 | | private async Task<string?> GetValidTokenAsync(CancellationToken cancellationToken) |
| | 539 | 119 | | { |
| | 539 | 120 | | var current = _cachedToken; |
| | 539 | 121 | | if (current is not null && DateTime.UtcNow < current.ExpiresAtUtc) |
| | 382 | 122 | | return current.Token; |
| | | 123 | | |
| | 157 | 124 | | await _semaphore.WaitAsync(cancellationToken).ConfigureAwait(false); |
| | | 125 | | try |
| | 157 | 126 | | { |
| | 157 | 127 | | current = _cachedToken; |
| | 157 | 128 | | if (current is not null && DateTime.UtcNow < current.ExpiresAtUtc) |
| | 2 | 129 | | return current.Token; |
| | | 130 | | |
| | 155 | 131 | | (string token, TimeSpan cacheDuration)? result = await _tokenProvider(cancellationToken) |
| | 155 | 132 | | .ConfigureAwait(false); |
| | | 133 | | |
| | 138 | 134 | | if (!result.HasValue) |
| | 80 | 135 | | { |
| | | 136 | | // Client needs no authentication, cache null token value until the next invalidated call |
| | 80 | 137 | | _cachedToken = new CachedToken(null, DateTime.MaxValue); |
| | 80 | 138 | | return null; |
| | | 139 | | } |
| | | 140 | | |
| | 58 | 141 | | _cachedToken = new CachedToken( |
| | 58 | 142 | | result.Value.token, |
| | 58 | 143 | | DateTime.UtcNow + result.Value.cacheDuration |
| | 58 | 144 | | ); |
| | 58 | 145 | | return result.Value.token; |
| | | 146 | | } |
| | | 147 | | finally |
| | 157 | 148 | | { |
| | 157 | 149 | | _semaphore.Release(); |
| | 157 | 150 | | } |
| | 522 | 151 | | } |
| | | 152 | | |
| | | 153 | | protected override void Dispose(bool disposing) |
| | 101 | 154 | | { |
| | 101 | 155 | | if (disposing) |
| | 101 | 156 | | { |
| | 101 | 157 | | _disposed = true; |
| | 101 | 158 | | _semaphore.Dispose(); |
| | 101 | 159 | | } |
| | | 160 | | |
| | 101 | 161 | | base.Dispose(disposing); |
| | 101 | 162 | | } |
| | | 163 | | |
| | 908 | 164 | | private record CachedToken(string? Token, DateTime ExpiresAtUtc); |
| | | 165 | | } |