From ca8adf22b855a2329bbedb08469f262275919528 Mon Sep 17 00:00:00 2001 From: Manan Bhatt Date: Thu, 19 Nov 2026 12:46:30 +0530 Subject: [PATCH 1/6] fix(auth): refresh the token on INVALID_TOKEN as well as EXPIRED_TOKEN --- Conductor/Client/ApiClient.cs | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/Conductor/Client/ApiClient.cs b/Conductor/Client/ApiClient.cs index a421b39a..775e6483 100644 --- a/Conductor/Client/ApiClient.cs +++ b/Conductor/Client/ApiClient.cs @@ -241,7 +241,9 @@ private RestResponse RetryRestClientCallApi(String path, Method method, List(response.Content); - if (JsonContent["error"].ToString() == "EXPIRED_TOKEN") + var error = JsonContent?["error"]?.ToString(); + // INVALID_TOKEN: e.g. a token issued by another server after a failover; a fresh one works. + if (error == "EXPIRED_TOKEN" || error == "INVALID_TOKEN") { string refreshToken = configuration.GetRefreshToken(); headerParams["X-Authorization"] = refreshToken; @@ -350,7 +352,9 @@ private async Task RetryRestClientCallApiAsync(String path, Method { var jsonContent = JsonConvert.DeserializeObject(response.Content); - if (jsonContent["error"].ToString() == "EXPIRED_TOKEN") + var error = jsonContent?["error"]?.ToString(); + // INVALID_TOKEN: e.g. a token issued by another server after a failover; a fresh one works. + if (error == "EXPIRED_TOKEN" || error == "INVALID_TOKEN") { string refreshToken = configuration.GetRefreshToken(); headerParams["X-Authorization"] = refreshToken; From 9b49f2d93f729df1457c8ee765f332e01d039f8c Mon Sep 17 00:00:00 2001 From: Chris Hagglund Date: Fri, 20 Nov 2026 10:00:44 -0600 Subject: [PATCH 2/6] fix(auth): fetch one new token when concurrent requests are rejected After a failover every in-flight request gets a 401 at once. Each one called GetRefreshToken, which always fetches a new token under a global lock, so N requests made N token fetches, one after another. - RefreshToken(settings, client, staleToken) fetches only if the cache still holds the rejected token; otherwise it returns the cached one. - GetToken checks the cache again under the lock, so callers that miss the cache together fetch once. - A 401 on a request sent without a token (such as /token) does not trigger a refresh. The existing RefreshToken and GetRefreshToken overloads are unchanged. Co-Authored-By: Claude Opus 5.5 --- Conductor/Client/ApiClient.cs | 12 +- .../Client/Authentication/TokenHandler.cs | 33 ++++- Conductor/Client/Configuration.cs | 11 ++ Tests/Client/TokenRefreshUnitTest.cs | 132 ++++++++++++++++++ 4 files changed, 179 insertions(+), 9 deletions(-) create mode 100644 Tests/Client/TokenRefreshUnitTest.cs diff --git a/Conductor/Client/ApiClient.cs b/Conductor/Client/ApiClient.cs index 775e6483..798e1c0a 100644 --- a/Conductor/Client/ApiClient.cs +++ b/Conductor/Client/ApiClient.cs @@ -243,9 +243,11 @@ private RestResponse RetryRestClientCallApi(String path, Method method, List RetryRestClientCallApiAsync(String path, Method var error = jsonContent?["error"]?.ToString(); // INVALID_TOKEN: e.g. a token issued by another server after a failover; a fresh one works. - if (error == "EXPIRED_TOKEN" || error == "INVALID_TOKEN") + // A request sent without a token, such as /token itself, has nothing to refresh. + if ((error == "EXPIRED_TOKEN" || error == "INVALID_TOKEN") + && headerParams.TryGetValue("X-Authorization", out var staleToken)) { - string refreshToken = configuration.GetRefreshToken(); + string refreshToken = configuration.GetRefreshToken(staleToken); headerParams["X-Authorization"] = refreshToken; retryCount++; continue; 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..d72dbd01 --- /dev/null +++ b/Tests/Client/TokenRefreshUnitTest.cs @@ -0,0 +1,132 @@ +/* + * 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.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); + } + + 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") }; + } + } + } +} From 4b52abd48ca10130d27418aeaa7b677af209509c Mon Sep 17 00:00:00 2001 From: Chris Hagglund Date: Fri, 20 Nov 2026 10:01:18 -0600 Subject: [PATCH 3/6] fix(auth): refresh the token only when a retry will follow The retry loop refreshed the token on every 401, including the last attempt, then exited without sending a request with it. A persistent 401 made three token fetches but used only two. Now each refresh is followed by a retry: up to MAX_TOKEN_REFRESH_RETRY_COUNT refreshes, so up to four requests. Co-Authored-By: Claude Opus 5.5 --- Conductor/Client/ApiClient.cs | 12 +++++--- Tests/Client/TokenRefreshUnitTest.cs | 45 ++++++++++++++++++++++++++++ 2 files changed, 53 insertions(+), 4 deletions(-) diff --git a/Conductor/Client/ApiClient.cs b/Conductor/Client/ApiClient.cs index 798e1c0a..d565042f 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); @@ -339,7 +341,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, @@ -350,7 +352,9 @@ 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. + if (response.StatusCode == System.Net.HttpStatusCode.Unauthorized + && retryCount < Constants.MAX_TOKEN_REFRESH_RETRY_COUNT) { var jsonContent = JsonConvert.DeserializeObject(response.Content); diff --git a/Tests/Client/TokenRefreshUnitTest.cs b/Tests/Client/TokenRefreshUnitTest.cs index d72dbd01..1e04325e 100644 --- a/Tests/Client/TokenRefreshUnitTest.cs +++ b/Tests/Client/TokenRefreshUnitTest.cs @@ -11,6 +11,7 @@ * 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; @@ -93,6 +94,50 @@ await Task.WhenAll(Enumerable.Range(0, n).Select(_ => 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()); + } + + 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 From 32af86e033b93b9ed1e15d43c87b21e1de87ce9d Mon Sep 17 00:00:00 2001 From: Chris Hagglund Date: Fri, 20 Nov 2026 10:02:18 -0600 Subject: [PATCH 4/6] fix(auth): return a non-JSON 401 as ApiException instead of throwing A 401 with a body that is not JSON, such as an HTML page from a proxy or load balancer, made the retry loop throw JsonReaderException from the JSON parse. The caller got a parse error instead of the 401. IsRejectedToken now treats a body it cannot parse as "not a rejected token", so the 401 reaches the caller as ApiException with no refresh. Both the sync and async loops use it. Co-Authored-By: Claude Opus 5.5 --- Conductor/Client/ApiClient.cs | 65 +++++++++++++++------------- Tests/Client/TokenRefreshUnitTest.cs | 32 ++++++++++++++ 2 files changed, 67 insertions(+), 30 deletions(-) diff --git a/Conductor/Client/ApiClient.cs b/Conductor/Client/ApiClient.cs index d565042f..fcbb9f09 100644 --- a/Conductor/Client/ApiClient.cs +++ b/Conductor/Client/ApiClient.cs @@ -238,28 +238,41 @@ private RestResponse RetryRestClientCallApi(String path, Method method, List(response.Content); - - var error = JsonContent?["error"]?.ToString(); - // INVALID_TOKEN: e.g. a token issued by another server after a failover; a fresh one works. - // A request sent without a token, such as /token itself, has nothing to refresh. - if ((error == "EXPIRED_TOKEN" || error == "INVALID_TOKEN") - && headerParams.TryGetValue("X-Authorization", out var staleToken)) - { - string refreshToken = configuration.GetRefreshToken(staleToken); - 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, @@ -353,22 +366,14 @@ private async Task RetryRestClientCallApiAsync(String path, Method FormatHeaders(response); // Refresh only when a retry follows; a token fetched after the last attempt is never used. - if (response.StatusCode == System.Net.HttpStatusCode.Unauthorized - && retryCount < Constants.MAX_TOKEN_REFRESH_RETRY_COUNT) + // 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); - - var error = jsonContent?["error"]?.ToString(); - // INVALID_TOKEN: e.g. a token issued by another server after a failover; a fresh one works. - // A request sent without a token, such as /token itself, has nothing to refresh. - if ((error == "EXPIRED_TOKEN" || error == "INVALID_TOKEN") - && headerParams.TryGetValue("X-Authorization", out var staleToken)) - { - string refreshToken = configuration.GetRefreshToken(staleToken); - headerParams["X-Authorization"] = refreshToken; - retryCount++; - continue; - } + headerParams["X-Authorization"] = configuration.GetRefreshToken(staleToken); + retryCount++; + continue; } break; } diff --git a/Tests/Client/TokenRefreshUnitTest.cs b/Tests/Client/TokenRefreshUnitTest.cs index 1e04325e..4c10d6fe 100644 --- a/Tests/Client/TokenRefreshUnitTest.cs +++ b/Tests/Client/TokenRefreshUnitTest.cs @@ -114,6 +114,38 @@ public async Task PersistentRejection_RetriesWithEveryRefreshedToken_Async() 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; From c7b83ca6d9f423df83b3d762f49bdc00aa063920 Mon Sep 17 00:00:00 2001 From: Chris Hagglund Date: Fri, 20 Nov 2026 10:03:06 -0600 Subject: [PATCH 5/6] ci: run PR checks on pull requests into fix/refresh-on-invalid-token Drop this commit before #184 merges into main. Co-Authored-By: Claude Opus 5.5 --- .github/workflows/pull_request.yml | 1 + 1 file changed, 1 insertion(+) diff --git a/.github/workflows/pull_request.yml b/.github/workflows/pull_request.yml index dd04438d..d2dfa81e 100644 --- a/.github/workflows/pull_request.yml +++ b/.github/workflows/pull_request.yml @@ -11,6 +11,7 @@ on: pull_request: branches: - main + - fix/refresh-on-invalid-token workflow_dispatch: inputs: oss_conductor_version: From e57f05332fa4759f6e90bca626d11777f43a7216 Mon Sep 17 00:00:00 2001 From: Chris Hagglund Date: Fri, 20 Nov 2026 10:33:56 -0600 Subject: [PATCH 6/6] ci: remove the PR trigger for fix/refresh-on-invalid-token The PR now targets main, so the extra branch filter is not needed. Co-Authored-By: Claude Opus 5.5 --- .github/workflows/pull_request.yml | 1 - 1 file changed, 1 deletion(-) diff --git a/.github/workflows/pull_request.yml b/.github/workflows/pull_request.yml index d2dfa81e..dd04438d 100644 --- a/.github/workflows/pull_request.yml +++ b/.github/workflows/pull_request.yml @@ -11,7 +11,6 @@ on: pull_request: branches: - main - - fix/refresh-on-invalid-token workflow_dispatch: inputs: oss_conductor_version: