diff --git a/Conductor/Client/ApiClient.cs b/Conductor/Client/ApiClient.cs index a421b39a..fcbb9f09 100644 --- a/Conductor/Client/ApiClient.cs +++ b/Conductor/Client/ApiClient.cs @@ -203,7 +203,7 @@ private RestResponse RetryRestClientCallApi(String path, Method method, List(response.Content); - - if (JsonContent["error"].ToString() == "EXPIRED_TOKEN") - { - string refreshToken = configuration.GetRefreshToken(); - headerParams["X-Authorization"] = refreshToken; - retryCount++; - continue; - } + headerParams["X-Authorization"] = configuration.GetRefreshToken(staleToken); + retryCount++; + continue; } break; } return response; } + // INVALID_TOKEN covers a token issued by another server, e.g. the peer region after a failover. + private static bool IsRejectedToken(RestResponse response) + { + if (response.StatusCode != System.Net.HttpStatusCode.Unauthorized || string.IsNullOrEmpty(response.Content)) + { + return false; + } + JObject body; + try + { + body = JsonConvert.DeserializeObject(response.Content); + } + catch (JsonException) + { + // Not a Conductor error body, e.g. an HTML 401 page from a proxy; a new token would not help. + return false; + } + var error = body?["error"]?.ToString(); + return error == "EXPIRED_TOKEN" || error == "INVALID_TOKEN"; + } + public async Task CallApiAsync( String path, RestSharp.Method method, List> queryParams, Object postBody, Dictionary headerParams, Dictionary formParams, @@ -335,7 +354,7 @@ private async Task RetryRestClientCallApiAsync(String path, Method { RestResponse response = null; int retryCount = 0; - while (retryCount < Constants.MAX_TOKEN_REFRESH_RETRY_COUNT) + while (true) { var request = PrepareRequest( path, method, queryParams, postBody, headerParams, formParams, fileParams, @@ -346,17 +365,15 @@ private async Task RetryRestClientCallApiAsync(String path, Method InterceptResponse(request, response); FormatHeaders(response); - if (response.StatusCode == System.Net.HttpStatusCode.Unauthorized) + // Refresh only when a retry follows; a token fetched after the last attempt is never used. + // A request sent without a token, such as /token itself, has nothing to refresh. + if (retryCount < Constants.MAX_TOKEN_REFRESH_RETRY_COUNT + && IsRejectedToken(response) + && headerParams.TryGetValue("X-Authorization", out var staleToken)) { - var jsonContent = JsonConvert.DeserializeObject(response.Content); - - if (jsonContent["error"].ToString() == "EXPIRED_TOKEN") - { - string refreshToken = configuration.GetRefreshToken(); - headerParams["X-Authorization"] = refreshToken; - retryCount++; - continue; - } + headerParams["X-Authorization"] = configuration.GetRefreshToken(staleToken); + retryCount++; + continue; } break; } diff --git a/Conductor/Client/Authentication/TokenHandler.cs b/Conductor/Client/Authentication/TokenHandler.cs index e743e29a..e177e5f2 100644 --- a/Conductor/Client/Authentication/TokenHandler.cs +++ b/Conductor/Client/Authentication/TokenHandler.cs @@ -38,20 +38,43 @@ public string GetToken(OrkesAuthenticationSettings authenticationSettings, Token { return token; } - return RefreshToken(authenticationSettings, tokenClient); + // Callers that miss the cache together queue on the lock; only the first should fetch. + return RefreshToken(authenticationSettings, tokenClient, staleToken: null); } public string RefreshToken(OrkesAuthenticationSettings authenticationSettings, TokenResourceApi tokenClient) { lock (_lockObject) { - string token = GetTokenFromServer(authenticationSettings, tokenClient); - var expirationTime = System.DateTimeOffset.Now.AddMinutes(30); - _memoryCache.Set(authenticationSettings, token, expirationTime); - return token; + return FetchAndCacheToken(authenticationSettings, tokenClient); + } + } + + /// + /// Replaces , the token the server rejected, unless another caller already has. + /// After a failover every in-flight request is rejected at once, and they should share one new token. + /// + public string RefreshToken(OrkesAuthenticationSettings authenticationSettings, TokenResourceApi tokenClient, string staleToken) + { + lock (_lockObject) + { + string token = (string)_memoryCache.Get(authenticationSettings); + if (token != null && token != staleToken) + { + return token; + } + return FetchAndCacheToken(authenticationSettings, tokenClient); } } + private string FetchAndCacheToken(OrkesAuthenticationSettings authenticationSettings, TokenResourceApi tokenClient) + { + string token = GetTokenFromServer(authenticationSettings, tokenClient); + var expirationTime = System.DateTimeOffset.Now.AddMinutes(30); + _memoryCache.Set(authenticationSettings, token, expirationTime); + return token; + } + private string GetTokenFromServer(OrkesAuthenticationSettings authenticationSettings, TokenResourceApi tokenClient) { var tokenRequest = new Client.Models.GenerateTokenRequest( diff --git a/Conductor/Client/Configuration.cs b/Conductor/Client/Configuration.cs index d8b34427..ebf0fbb9 100644 --- a/Conductor/Client/Configuration.cs +++ b/Conductor/Client/Configuration.cs @@ -263,6 +263,17 @@ public string GetRefreshToken() return _tokenHandler.RefreshToken(AuthenticationSettings, _tokenClient); } + /// + /// Get a token to replace , which the server rejected. + /// Fetches a new one only if no other caller has already replaced it. + /// + /// new token + public string GetRefreshToken(string staleToken) + { + _tokenClient = GetClient(); + return _tokenHandler.RefreshToken(AuthenticationSettings, _tokenClient, staleToken); + } + #endregion Methods } } diff --git a/Tests/Client/TokenRefreshUnitTest.cs b/Tests/Client/TokenRefreshUnitTest.cs new file mode 100644 index 00000000..4c10d6fe --- /dev/null +++ b/Tests/Client/TokenRefreshUnitTest.cs @@ -0,0 +1,209 @@ +/* + * Copyright 2026 Conductor Authors. + *

+ * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + *

+ * http://www.apache.org/licenses/LICENSE-2.0 + *

+ * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on + * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the + * specific language governing permissions and limitations under the License. + */ +using System; +using System.Collections.Concurrent; +using System.Linq; +using System.Net; +using System.Net.Http; +using System.Text; +using System.Threading; +using System.Threading.Tasks; +using Conductor.Api; +using Conductor.Client; +using Conductor.Client.Authentication; +using conductor_csharp.test.Helper; +using RestSharp; +using Xunit; + +namespace Tests.Client +{ + ///

+ /// Server-less tests for the refresh-and-retry on a 401 that rejects the client's token. + /// + [Trait("Category", "Unit")] + public class TokenRefreshUnitTest + { + private const string InvalidToken = "{\"error\":\"INVALID_TOKEN\"}"; + + // After a failover every in-flight request is rejected at once; together they must fetch one new token, not one each. + [Fact] + public async Task ConcurrentRejections_FetchOneNewToken() + { + const int n = 20; + int issued = 0, rejected = 0; + var failedOver = false; + var allRejected = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + var api = ApiFor(async request => + { + if (IsTokenRequest(request)) + { + // Hold the fetch open so the other requests' refreshes overlap it. + await Task.Delay(50); + return (HttpStatusCode.OK, $"{{\"token\":\"t{Interlocked.Increment(ref issued)}\"}}"); + } + if (Volatile.Read(ref failedOver) && TokenOf(request) == "t1") + { + if (Interlocked.Increment(ref rejected) == n) + { + allRejected.TrySetResult(true); + } + await Task.WhenAny(allRejected.Task, Task.Delay(TimeSpan.FromSeconds(5))); + return (HttpStatusCode.Unauthorized, InvalidToken); + } + return (HttpStatusCode.OK, "secret"); + }); + await api.GetSecretAsync("key"); + Volatile.Write(ref failedOver, true); + + var results = await Task.WhenAll(Enumerable.Range(0, n).Select(_ => api.GetSecretAsync("key"))); + + Assert.All(results, value => Assert.Equal("secret", value)); + Assert.Equal(n, rejected); + Assert.Equal(2, issued); // t1 before the failover, t2 shared by every retry + } + + [Fact] + public async Task ConcurrentFirstCalls_FetchOneToken() + { + const int n = 20; + int issued = 0; + var api = ApiFor(async request => + { + if (IsTokenRequest(request)) + { + await Task.Delay(50); + return (HttpStatusCode.OK, $"{{\"token\":\"t{Interlocked.Increment(ref issued)}\"}}"); + } + return (HttpStatusCode.OK, "secret"); + }); + + // The token fetch is synchronous, so each caller blocks a thread; LongRunning keeps them off the thread pool. + await Task.WhenAll(Enumerable.Range(0, n).Select(_ => + Task.Factory.StartNew(() => api.GetSecret("key"), TaskCreationOptions.LongRunning))); + + Assert.Equal(1, issued); + } + + [Fact] + public void PersistentRejection_RetriesWithEveryRefreshedToken() + { + var (api, sentTokens, issued) = AlwaysRejectingApi(); + + var e = Assert.Throws(() => api.GetSecret("key")); + + AssertEveryRefreshWasUsed(e, sentTokens, issued()); + } + + [Fact] + public async Task PersistentRejection_RetriesWithEveryRefreshedToken_Async() + { + var (api, sentTokens, issued) = AlwaysRejectingApi(); + + var e = await Assert.ThrowsAsync(() => api.GetSecretAsync("key")); + + AssertEveryRefreshWasUsed(e, sentTokens, issued()); + } + + // A proxy or load balancer can answer 401 with an HTML page; that is not a token the client can fix by refreshing. + [Fact] + public void NonJson401_FailsWithApiExceptionAndNoRefresh() + { + var (api, issued) = HtmlRejectingApi(); + + var e = Assert.Throws(() => api.GetSecret("key")); + + Assert.Equal(401, e.ErrorCode); + Assert.Equal(1, issued()); + } + + [Fact] + public async Task NonJson401_FailsWithApiExceptionAndNoRefresh_Async() + { + var (api, issued) = HtmlRejectingApi(); + + var e = await Assert.ThrowsAsync(() => api.GetSecretAsync("key")); + + Assert.Equal(401, e.ErrorCode); + Assert.Equal(1, issued()); + } + + private static (SecretResourceApi Api, Func Issued) HtmlRejectingApi() + { + int issued = 0; + var api = ApiFor(request => Task.FromResult(IsTokenRequest(request) + ? (HttpStatusCode.OK, $"{{\"token\":\"t{Interlocked.Increment(ref issued)}\"}}") + : (HttpStatusCode.Unauthorized, "

401 Unauthorized

"))); + return (api, () => Volatile.Read(ref issued)); + } + + private static (SecretResourceApi Api, ConcurrentQueue SentTokens, Func Issued) AlwaysRejectingApi() + { + int issued = 0; + var sentTokens = new ConcurrentQueue(); + var api = ApiFor(request => + { + if (IsTokenRequest(request)) + { + return Task.FromResult((HttpStatusCode.OK, $"{{\"token\":\"t{Interlocked.Increment(ref issued)}\"}}")); + } + sentTokens.Enqueue(TokenOf(request)); + return Task.FromResult((HttpStatusCode.Unauthorized, InvalidToken)); + }); + return (api, sentTokens, () => Volatile.Read(ref issued)); + } + + private static void AssertEveryRefreshWasUsed(ApiException e, ConcurrentQueue sentTokens, int issued) + { + Assert.Equal(401, e.ErrorCode); + Assert.Equal(Constants.MAX_TOKEN_REFRESH_RETRY_COUNT + 1, sentTokens.Count); + Assert.Equal(sentTokens.Count, issued); + Assert.Equal($"t{issued}", sentTokens.Last()); + } + + private static SecretResourceApi ApiFor(Func> respond) + { + var configuration = new Configuration + { + BasePath = MockApiClient.BasePath, + AuthenticationSettings = new OrkesAuthenticationSettings("key", "secret"), + }; + configuration.ApiClient.RestClient = new RestClient(new RestClientOptions(MockApiClient.BasePath) + { + ConfigureMessageHandler = _ => new AsyncStubHandler(respond), + }); + return configuration.GetClient(); + } + + private static bool IsTokenRequest(HttpRequestMessage request) => request.RequestUri.AbsolutePath.EndsWith("/token"); + + private static string TokenOf(HttpRequestMessage request) => + request.Headers.TryGetValues("X-Authorization", out var values) ? values.First() : null; + + // StubHttpMessageHandler records requests in a List, which is not safe for concurrent requests. + private sealed class AsyncStubHandler : HttpMessageHandler + { + private readonly Func> _respond; + + public AsyncStubHandler(Func> respond) + { + _respond = respond; + } + + protected override async Task SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) + { + var (status, body) = await _respond(request); + return new HttpResponseMessage(status) { Content = new StringContent(body, Encoding.UTF8, "application/json") }; + } + } + } +}