Skip to content
61 changes: 39 additions & 22 deletions Conductor/Client/ApiClient.cs
Original file line number Diff line number Diff line change
Expand Up @@ -203,7 +203,7 @@ private RestResponse RetryRestClientCallApi(String path, Method method, List<Key
var metricsUri = path;

RestResponse response = null;
while (retryCount < Constants.MAX_TOKEN_REFRESH_RETRY_COUNT)
while (true)
{
var sw = Stopwatch.StartNew();
string statusCode = "0";
Expand Down Expand Up @@ -237,23 +237,42 @@ private RestResponse RetryRestClientCallApi(String path, Method method, List<Key
}
}

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<JObject>(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<JObject>(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<object> CallApiAsync(
String path, RestSharp.Method method, List<KeyValuePair<String, String>> queryParams, Object postBody,
Dictionary<String, String> headerParams, Dictionary<String, String> formParams,
Expand Down Expand Up @@ -335,7 +354,7 @@ private async Task<RestResponse> 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,
Expand All @@ -346,17 +365,15 @@ private async Task<RestResponse> 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<JObject>(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;
}
Expand Down
33 changes: 28 additions & 5 deletions Conductor/Client/Authentication/TokenHandler.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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);
}
}

/// <summary>
/// Replaces <paramref name="staleToken"/>, 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.
/// </summary>
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(
Expand Down
11 changes: 11 additions & 0 deletions Conductor/Client/Configuration.cs
Original file line number Diff line number Diff line change
Expand Up @@ -263,6 +263,17 @@ public string GetRefreshToken()
return _tokenHandler.RefreshToken(AuthenticationSettings, _tokenClient);
}

/// <summary>
/// Get a token to replace <paramref name="staleToken"/>, which the server rejected.
/// Fetches a new one only if no other caller has already replaced it.
/// </summary>
/// <returns> new token</returns>
public string GetRefreshToken(string staleToken)
{
_tokenClient = GetClient<TokenResourceApi>();
return _tokenHandler.RefreshToken(AuthenticationSettings, _tokenClient, staleToken);
}

#endregion Methods
}
}
209 changes: 209 additions & 0 deletions Tests/Client/TokenRefreshUnitTest.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,209 @@
/*
* Copyright 2026 Conductor Authors.
* <p>
* 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
* <p>
* http://www.apache.org/licenses/LICENSE-2.0
* <p>
* 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
{
/// <summary>
/// Server-less tests for the refresh-and-retry on a 401 that rejects the client's token.
/// </summary>
[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<bool>(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<ApiException>(() => api.GetSecret("key"));

AssertEveryRefreshWasUsed(e, sentTokens, issued());
}

[Fact]
public async Task PersistentRejection_RetriesWithEveryRefreshedToken_Async()
{
var (api, sentTokens, issued) = AlwaysRejectingApi();

var e = await Assert.ThrowsAsync<ApiException>(() => 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<ApiException>(() => 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<ApiException>(() => api.GetSecretAsync("key"));

Assert.Equal(401, e.ErrorCode);
Assert.Equal(1, issued());
}

private static (SecretResourceApi Api, Func<int> Issued) HtmlRejectingApi()
{
int issued = 0;
var api = ApiFor(request => Task.FromResult(IsTokenRequest(request)
? (HttpStatusCode.OK, $"{{\"token\":\"t{Interlocked.Increment(ref issued)}\"}}")
: (HttpStatusCode.Unauthorized, "<html><body><h1>401 Unauthorized</h1></body></html>")));
return (api, () => Volatile.Read(ref issued));
}

private static (SecretResourceApi Api, ConcurrentQueue<string> SentTokens, Func<int> Issued) AlwaysRejectingApi()
{
int issued = 0;
var sentTokens = new ConcurrentQueue<string>();
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<string> 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<HttpRequestMessage, Task<(HttpStatusCode Status, string Body)>> 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<SecretResourceApi>();
}

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<HttpRequestMessage, Task<(HttpStatusCode Status, string Body)>> _respond;

public AsyncStubHandler(Func<HttpRequestMessage, Task<(HttpStatusCode Status, string Body)>> respond)
{
_respond = respond;
}

protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
{
var (status, body) = await _respond(request);
return new HttpResponseMessage(status) { Content = new StringContent(body, Encoding.UTF8, "application/json") };
}
}
}
}
Loading