From 1d5292e7ce1a6cb1ce474dbc02516bd5d48e0d15 Mon Sep 17 00:00:00 2001 From: Paolo Di Tommaso Date: Mon, 5 Jan 2026 18:40:33 +0700 Subject: [PATCH 1/9] Add multi-token support for HxClient MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Introduce HxAuth, HxTokenStore, and HxMapTokenStore to support multiple authentication sessions with automatic token refresh. - HxAuth: Immutable JWT credential container with SHA-256 key - HxTokenStore: Interface for pluggable token storage - HxMapTokenStore: Default ConcurrentHashMap implementation - HxTokenManager: Extended with multi-token methods - HxClient.Builder: Added tokenStore() method for custom stores 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude Opus 4.5 --- lib-httpx/README.md | 72 ++- .../src/main/java/io/seqera/http/HxAuth.java | 125 ++++ .../main/java/io/seqera/http/HxClient.java | 272 +++++++-- .../java/io/seqera/http/HxMapTokenStore.java | 50 ++ .../java/io/seqera/http/HxTokenManager.java | 557 +++++++++++------- .../java/io/seqera/http/HxTokenStore.java | 57 ++ .../groovy/io/seqera/http/HxAuthTest.groovy | 71 +++ .../groovy/io/seqera/http/HxClientTest.groovy | 13 + .../io/seqera/http/HxMapTokenStoreTest.groovy | 59 ++ .../io/seqera/http/HxTokenManagerTest.groovy | 73 +++ 10 files changed, 1072 insertions(+), 277 deletions(-) create mode 100644 lib-httpx/src/main/java/io/seqera/http/HxAuth.java create mode 100644 lib-httpx/src/main/java/io/seqera/http/HxMapTokenStore.java create mode 100644 lib-httpx/src/main/java/io/seqera/http/HxTokenStore.java create mode 100644 lib-httpx/src/test/groovy/io/seqera/http/HxAuthTest.groovy create mode 100644 lib-httpx/src/test/groovy/io/seqera/http/HxMapTokenStoreTest.groovy diff --git a/lib-httpx/README.md b/lib-httpx/README.md index aec7cf95..a20f6bf9 100644 --- a/lib-httpx/README.md +++ b/lib-httpx/README.md @@ -21,11 +21,13 @@ dependencies { - **Retry Logic**: Automatic retry for configurable HTTP status codes (default: 429, 500, 502, 503, 504) - **Authentication Support**: Built-in support for JWT Bearer tokens and HTTP Basic authentication - **JWT Token Refresh**: Automatic JWT token refresh when receiving 401 Unauthorized responses with configurable cookie policies +- **Multi-Session Auth**: Support for multiple concurrent authentication sessions with per-request token management +- **Custom Token Storage**: Pluggable token store interface for distributed deployments (Redis, database, etc.) - **WWW-Authenticate Support**: Automatic handling of HTTP authentication challenges (Basic and Bearer schemes) - **Anonymous Authentication**: Fallback to anonymous authentication when credentials aren't provided - **Configurable**: Customizable retry policies, timeouts, token refresh, authentication settings, and cookie policies - **Generic Integration**: Compatible with any `Retryable.Config` for flexible retry configuration -- **Thread-safe**: Safe for concurrent use +- **Thread-safe**: Safe for concurrent use with atomic token refresh coordination - **Async Support**: Support for both synchronous and asynchronous requests ## Usage @@ -139,6 +141,69 @@ HxClient client = HxClient.newBuilder().config(config).build(); - **Basic**: Uses empty credentials (base64 encoded `:`) - **Bearer**: Attempts to get anonymous tokens from the authentication endpoint using OAuth2 flow +### Multi-Session Authentication + +For applications managing multiple users or authentication contexts, use `HxAuth` to handle per-request authentication with automatic token refresh: + +```java +// Create a shared client with refresh URL configured +HxClient client = HxClient.newBuilder() + .refreshTokenUrl("https://api.example.com/oauth/token") + .build(); + +// Create auth for each user session +HxAuth user1Auth = HxAuth.of("user1.jwt.token", "user1-refresh-token"); +HxAuth user2Auth = HxAuth.of("user2.jwt.token", "user2-refresh-token"); + +// Make requests with per-user authentication +HttpRequest request = HttpRequest.newBuilder() + .uri(URI.create("https://api.example.com/data")) + .GET() + .build(); + +HttpResponse response1 = client.send(request, user1Auth, HttpResponse.BodyHandlers.ofString()); +HttpResponse response2 = client.send(request, user2Auth, HttpResponse.BodyHandlers.ofString()); + +// Async requests also supported +CompletableFuture> future = client.sendAsync(request, user1Auth, HttpResponse.BodyHandlers.ofString()); +``` + +**Features:** +- Each `HxAuth` maintains its own token pair (access + refresh) +- Automatic token refresh on 401 responses, scoped to each auth session +- Thread-safe concurrent refresh coordination per auth key +- Tokens are identified by SHA-256 hash of the access token + +#### Custom Token Store + +By default, tokens are stored in an in-memory `ConcurrentHashMap`. For distributed deployments, provide a custom `HxTokenStore`: + +```java +// Implement custom store (e.g., Redis-backed) +public class RedisTokenStore implements HxTokenStore { + @Override + public HxAuth get(String key) { /* Redis GET */ } + + @Override + public void put(String key, HxAuth auth) { /* Redis SET */ } + + @Override + public HxAuth remove(String key) { /* Redis DEL */ } + + @Override + public HxAuth putIfAbsent(HxAuth auth) { + // Use Redis SETNX for atomic operation + } +} + +// Use custom store +HxTokenStore customStore = new RedisTokenStore(); +HxClient client = HxClient.newBuilder() + .tokenStore(customStore) + .refreshTokenUrl("https://api.example.com/oauth/token") + .build(); +``` + ### Custom Retry Configuration ```java @@ -238,6 +303,7 @@ HxClient client = HxClient.newBuilder() | `refreshToken` | Refresh token for JWT renewal | null | | `refreshTokenUrl` | URL for token refresh requests | null | | `tokenRefreshTimeout` | Timeout for token refresh requests | 30s | +| `tokenStore` | Custom token store for multi-session authentication | HxMapTokenStore | | `basicAuthToken` | Token for HTTP Basic authentication (username:password format) | null | | `refreshCookiePolicy` | Cookie policy for JWT token refresh operations (ACCEPT_ALL, ACCEPT_NONE, ACCEPT_ORIGINAL_SERVER) | null | | `wwwAuthentication` | Enable WWW-Authenticate challenge handling | false | @@ -257,7 +323,9 @@ All classes and methods include comprehensive Javadoc documentation covering: - **`HxClient`** (Http eXtended Client): Main client class with retry, JWT, and WWW-Authenticate functionality - **`HxConfig`**: Configuration builder with all available options including Retryable.Config integration -- **`HxTokenManager`**: Thread-safe JWT token lifecycle management +- **`HxAuth`**: Immutable container for JWT access token and refresh token pairs +- **`HxTokenStore`**: Interface for pluggable token storage (default: in-memory ConcurrentHashMap) +- **`HxTokenManager`**: Thread-safe JWT token lifecycle management with multi-session support - **`AuthenticationChallenge`**: Represents a parsed WWW-Authenticate challenge - **`AuthenticationScheme`**: Enumeration of supported authentication schemes (Basic, Bearer) - **`AuthenticationCallback`**: Interface for providing authentication credentials diff --git a/lib-httpx/src/main/java/io/seqera/http/HxAuth.java b/lib-httpx/src/main/java/io/seqera/http/HxAuth.java new file mode 100644 index 00000000..8f3e2642 --- /dev/null +++ b/lib-httpx/src/main/java/io/seqera/http/HxAuth.java @@ -0,0 +1,125 @@ +/* + * Copyright 2025, Seqera Labs + * + * 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. + * + */ + +package io.seqera.http; + +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.util.HexFormat; +import java.util.Objects; + +/** + * Immutable container for JWT authentication credentials. + * + *

This class holds a JWT access token and an optional refresh token as a pair. + * It provides a {@link #key()} method that computes a SHA-256 hash of the token, + * which can be used as a unique identifier for storing and retrieving token pairs + * in an {@link HxTokenStore}. + * + *

Instances are created using the factory methods {@link #of(String)} or + * {@link #of(String, String)}. + * + * @author Paolo Di Tommaso + */ +public final class HxAuth { + + private final String accessToken; + private final String refreshToken; + + private HxAuth(String accessToken, String refreshToken) { + this.accessToken = accessToken; + this.refreshToken = refreshToken; + } + + /** + * Creates an HxAuth instance. + * + * @param token the authentication token + * @return a new HxAuth instance with null refresh token + */ + public static HxAuth of(String token) { + return new HxAuth(token, null); + } + + /** + * Creates an HxAuth instance. + * + * @param token the authentication token + * @param refresh the refresh token + * @return a new HxAuth instance + */ + public static HxAuth of(String token, String refresh) { + return new HxAuth(token, refresh); + } + + /** + * Computes the SHA-256 hash of the access token. + * + * @return the SHA-256 hash as a hexadecimal string + */ + public String key() { + try { + final MessageDigest digest = MessageDigest.getInstance("SHA-256"); + final byte[] hash = digest.digest(accessToken.getBytes(StandardCharsets.UTF_8)); + return HexFormat.of().formatHex(hash); + } + catch (NoSuchAlgorithmException e) { + throw new RuntimeException("SHA-256 algorithm not available", e); + } + } + + /** + * Returns the JWT access token. + * + * @return the access token + */ + public String accessToken() { + return accessToken; + } + + /** + * Returns the refresh token. + * + * @return the refresh token, or null if not set + */ + public String refreshToken() { + return refreshToken; + } + + @Override + public boolean equals(Object o) { + if (this == o) return true; + if (o == null || getClass() != o.getClass()) return false; + HxAuth hxAuth = (HxAuth) o; + return Objects.equals(accessToken, hxAuth.accessToken) + && Objects.equals(refreshToken, hxAuth.refreshToken); + } + + @Override + public int hashCode() { + return Objects.hash(accessToken, refreshToken); + } + + @Override + public String toString() { + return "HxAuth[" + + "accessToken=" + accessToken + + ", refreshToken=" + refreshToken + + ']'; + } +} \ No newline at end of file diff --git a/lib-httpx/src/main/java/io/seqera/http/HxClient.java b/lib-httpx/src/main/java/io/seqera/http/HxClient.java index 19088679..849062d4 100644 --- a/lib-httpx/src/main/java/io/seqera/http/HxClient.java +++ b/lib-httpx/src/main/java/io/seqera/http/HxClient.java @@ -156,9 +156,15 @@ public class HxClient { * If null, the default configuration will be used. */ protected HxClient(HttpClient httpClient, HxConfig config) { + this(httpClient, config, null); + } + + protected HxClient(HttpClient httpClient, HxConfig config, HxTokenStore tokenStore) { this.httpClient = httpClient; this.config = config; - this.tokenManager = new HxTokenManager(config); + this.tokenManager = tokenStore != null + ? new HxTokenManager(config, tokenStore) + : new HxTokenManager(config); } /** @@ -275,6 +281,93 @@ public HttpResponse sendAsStream(HttpRequest request) { return sendWithRetry(request, HttpResponse.BodyHandlers.ofInputStream()); } + // ======================================================================== + // Multi-user authentication methods + // ======================================================================== + + /** + * Sends an HTTP request synchronously with automatic retry logic using the specified authentication. + * + *

This method allows per-request authentication for multi-user scenarios. The token + * is retrieved from the token store (and may have been refreshed since initial creation). + * If a 401 response is received, the token will be refreshed and the request retried. + * + * @param the response body type + * @param request the HTTP request to send + * @param auth the authentication data for this request + * @param responseBodyHandler the response body handler + * @return the HTTP response + * @throws IOException if all retry attempts fail + * @throws InterruptedException if the operation is interrupted + */ + public HttpResponse send(HttpRequest request, HxAuth auth, HttpResponse.BodyHandler responseBodyHandler) + throws IOException, InterruptedException { + return sendWithRetry(request, auth, responseBodyHandler); + } + + /** + * Sends an HTTP request synchronously as String using the specified authentication. + * + * @param request the HTTP request to send + * @param auth the authentication data for this request + * @return the HTTP response with String body + */ + public HttpResponse sendAsString(HttpRequest request, HxAuth auth) { + return sendWithRetry(request, auth, HttpResponse.BodyHandlers.ofString()); + } + + /** + * Sends an HTTP request synchronously as byte array using the specified authentication. + * + * @param request the HTTP request to send + * @param auth the authentication data for this request + * @return the HTTP response with byte array body + */ + public HttpResponse sendAsBytes(HttpRequest request, HxAuth auth) { + return sendWithRetry(request, auth, HttpResponse.BodyHandlers.ofByteArray()); + } + + /** + * Sends an HTTP request synchronously as InputStream using the specified authentication. + * + * @param request the HTTP request to send + * @param auth the authentication data for this request + * @return the HTTP response with InputStream body + */ + public HttpResponse sendAsStream(HttpRequest request, HxAuth auth) { + return sendWithRetry(request, auth, HttpResponse.BodyHandlers.ofInputStream()); + } + + /** + * Sends an HTTP request asynchronously using the specified authentication. + * + * @param the response body type + * @param request the HTTP request to send + * @param auth the authentication data for this request + * @param responseBodyHandler the response body handler + * @return a CompletableFuture that will complete with the HTTP response + */ + public CompletableFuture> sendAsync(HttpRequest request, HxAuth auth, + HttpResponse.BodyHandler responseBodyHandler) { + Executor executor = httpClient.executor().orElse(java.util.concurrent.ForkJoinPool.commonPool()); + return sendWithRetryAsync(request, auth, responseBodyHandler, executor); + } + + /** + * Sends an HTTP request asynchronously using the specified authentication and executor. + * + * @param the response body type + * @param request the HTTP request to send + * @param auth the authentication data for this request + * @param responseBodyHandler the response body handler + * @param executor the executor to use for async operations + * @return a CompletableFuture that will complete with the HTTP response + */ + public CompletableFuture> sendAsync(HttpRequest request, HxAuth auth, + HttpResponse.BodyHandler responseBodyHandler, Executor executor) { + return sendWithRetryAsync(request, auth, responseBodyHandler, executor); + } + /** * Sends an HTTP request asynchronously with automatic retry logic and JWT token refresh. * @@ -322,7 +415,39 @@ public CompletableFuture> sendAsync(HttpRequest request, /** * Internal method that implements the retry logic for synchronous requests. - * + * + *

Delegates to {@link #sendWithRetry(HttpRequest, HxAuth, HttpResponse.BodyHandler)} with default auth. + * + * @param the response body type + * @param request the HTTP request to send + * @param responseBodyHandler the response body handler + * @return the HTTP response after successful execution or retry exhaustion + */ + protected HttpResponse sendWithRetry(HttpRequest request, HttpResponse.BodyHandler responseBodyHandler) { + return sendWithRetry(request, tokenManager.getDefaultAuth(), responseBodyHandler); + } + + /** + * Internal method that implements the retry logic for asynchronous requests. + * + *

Delegates to {@link #sendWithRetryAsync(HttpRequest, HxAuth, HttpResponse.BodyHandler, Executor)} with default auth. + * + * @param the response body type + * @param request the HTTP request to send + * @param responseBodyHandler the response body handler + * @param executor optional executor for async operations, may be null + * @return a CompletableFuture that completes with the HTTP response + */ + protected CompletableFuture> sendWithRetryAsync( + HttpRequest request, + HttpResponse.BodyHandler responseBodyHandler, + Executor executor) { + return sendWithRetryAsync(request, tokenManager.getDefaultAuth(), responseBodyHandler, executor); + } + + /** + * Internal method that implements the retry logic for synchronous requests. + * *

This method handles the core retry functionality including: *

    *
  • Adding authentication headers
  • @@ -330,51 +455,62 @@ public CompletableFuture> sendAsync(HttpRequest request, *
  • Attempting token refresh on 401 responses
  • *
  • Re-executing requests with refreshed tokens
  • *
- * + * + *

If auth is null, uses the default token from configuration. Otherwise uses + * the specific {@link HxAuth} for multi-user authentication scenarios. + * * @param the response body type * @param request the HTTP request to send + * @param auth the authentication data for this request, or null to use default token * @param responseBodyHandler the response body handler * @return the HTTP response after successful execution or retry exhaustion - * @throws IOException if all retry attempts fail - * @throws InterruptedException if the operation is interrupted */ - protected HttpResponse sendWithRetry(HttpRequest request, HttpResponse.BodyHandler responseBodyHandler) { + protected HttpResponse sendWithRetry(HttpRequest request, HxAuth auth, HttpResponse.BodyHandler responseBodyHandler) { final boolean[] tokenRefreshed = {false}; - + final Retryable> retry = Retryable.>of(config) .retryCondition(config.getRetryCondition()) .retryIf(this::shouldRetryOnResponse) .onRetry(event -> { - String message = event.getFailure() != null ? event.getFailure().getMessage() + String message = event.getFailure() != null ? event.getFailure().getMessage() : String.valueOf(event.getResult().statusCode()); log.debug("HTTP request retry attempt {}: {}", event.getAttempt(), message); }); return retry.apply(() -> { - final HttpRequest actualRequest = tokenManager.addAuthHeader(request); + final HttpRequest actualRequest = (auth != null) + ? tokenManager.addAuthHeader(request, auth) + : tokenManager.addAuthHeader(request); final HttpResponse response = httpClient.send(actualRequest, responseBodyHandler); - + if (response.statusCode() != 401 || tokenRefreshed[0]) { return response; } - - // Try JWT token refresh first if available - if (tokenManager.canRefreshToken()) { - log.debug("Received 401 status, attempting coordinated token refresh"); + + // Try JWT token refresh + final boolean canRefresh = (auth != null) ? tokenManager.canRefreshToken(auth) : tokenManager.canRefreshToken(); + if (canRefresh) { + final String debugKey = (auth != null) ? auth.key() : "default"; + log.debug("Received 401 status for auth key {}, attempting token refresh", debugKey); try { - if (tokenManager.getOrRefreshTokenAsync().get()) { + final boolean refreshed = (auth != null) + ? tokenManager.getOrRefreshTokenAsync(auth).get() != null + : tokenManager.getOrRefreshTokenAsync().get(); + if (refreshed) { tokenRefreshed[0] = true; - final HttpRequest refreshedRequest = tokenManager.addAuthHeader(request); + final HttpRequest refreshedRequest = (auth != null) + ? tokenManager.addAuthHeader(request, auth) + : tokenManager.addAuthHeader(request); closeResponse(response); return httpClient.send(refreshedRequest, responseBodyHandler); } } catch (Exception e) { - log.warn("Token refresh failed: " + e.getMessage()); + log.warn("Token refresh failed for auth key {}: {}", (auth != null) ? auth.key() : "default", e.getMessage()); } } - - // Try WWW-Authenticate challenge handling if enabled - if (config.isWwwAuthenticateEnabled()) { + + // Try WWW-Authenticate challenge handling if enabled (only for default auth) + if (auth == null && config.isWwwAuthenticateEnabled()) { HttpRequest authenticatedRequest = handleWwwAuthenticate(request, response); if (authenticatedRequest != null) { log.debug("Retrying request with WWW-Authenticate challenge"); @@ -382,14 +518,14 @@ protected HttpResponse sendWithRetry(HttpRequest request, HttpResponse.Bo return httpClient.send(authenticatedRequest, responseBodyHandler); } } - + return response; }); } /** * Internal method that implements the retry logic for asynchronous requests. - * + * *

This method handles the core async retry functionality including: *

    *
  • Adding authentication headers
  • @@ -397,58 +533,70 @@ protected HttpResponse sendWithRetry(HttpRequest request, HttpResponse.Bo *
  • Attempting token refresh on 401 responses
  • *
  • Re-executing requests with refreshed tokens
  • *
- * + * + *

If auth is null, uses the default token from configuration. Otherwise uses + * the specific {@link HxAuth} for multi-user authentication scenarios. + * * @param the response body type * @param request the HTTP request to send + * @param auth the authentication data for this request, or null to use default token * @param responseBodyHandler the response body handler * @param executor optional executor for async operations, may be null * @return a CompletableFuture that completes with the HTTP response */ protected CompletableFuture> sendWithRetryAsync( - HttpRequest request, - HttpResponse.BodyHandler responseBodyHandler, + HttpRequest request, + HxAuth auth, + HttpResponse.BodyHandler responseBodyHandler, Executor executor) { - + final boolean[] tokenRefreshed = {false}; - + final Retryable> retry = Retryable.>of(config) .retryCondition(config.getRetryCondition()) .retryIf(this::shouldRetryOnResponse) .onRetry(event -> { - String message = event.getFailure() != null ? event.getFailure().getMessage() + String message = event.getFailure() != null ? event.getFailure().getMessage() : String.valueOf(event.getResult().statusCode()); log.debug("HTTP async request retry attempt {}: {}", event.getAttempt(), message); }); return retry.applyAsync(() -> { - // Perform the HTTP request and coordinated JWT refresh within the retry - final HttpRequest actualRequest = tokenManager.addAuthHeader(request); - + final HttpRequest actualRequest = (auth != null) + ? tokenManager.addAuthHeader(request, auth) + : tokenManager.addAuthHeader(request); + try { final HttpResponse response = httpClient.sendAsync(actualRequest, responseBodyHandler).get(); - + if (response.statusCode() != 401 || tokenRefreshed[0]) { return response; } - - // Try JWT token refresh first if available - if (tokenManager.canRefreshToken()) { - log.debug("Received 401 status in async call, attempting coordinated token refresh"); + + // Try JWT token refresh + final boolean canRefresh = (auth != null) ? tokenManager.canRefreshToken(auth) : tokenManager.canRefreshToken(); + if (canRefresh) { + final String debugKey = (auth != null) ? auth.key() : "default"; + log.debug("Received 401 status in async call for auth key {}, attempting token refresh", debugKey); try { - final boolean refreshed = tokenManager.getOrRefreshTokenAsync().get(); + final boolean refreshed = (auth != null) + ? tokenManager.getOrRefreshTokenAsync(auth).get() != null + : tokenManager.getOrRefreshTokenAsync().get(); if (refreshed) { tokenRefreshed[0] = true; - final HttpRequest refreshedRequest = tokenManager.addAuthHeader(request); + final HttpRequest refreshedRequest = (auth != null) + ? tokenManager.addAuthHeader(request, auth) + : tokenManager.addAuthHeader(request); closeResponse(response); return httpClient.sendAsync(refreshedRequest, responseBodyHandler).get(); } } catch (Exception e) { - log.warn("Async token refresh failed: " + e.getMessage()); + log.warn("Async token refresh failed for auth key {}: {}", (auth != null) ? auth.key() : "default", e.getMessage()); } } - - // Try WWW-Authenticate challenge handling if enabled - if (config.isWwwAuthenticateEnabled()) { + + // Try WWW-Authenticate challenge handling if enabled (only for default auth) + if (auth == null && config.isWwwAuthenticateEnabled()) { HttpRequest authenticatedRequest = handleWwwAuthenticate(request, response); if (authenticatedRequest != null) { log.debug("Retrying async request with WWW-Authenticate credentials"); @@ -456,10 +604,9 @@ protected CompletableFuture> sendWithRetryAsync( return httpClient.sendAsync(authenticatedRequest, responseBodyHandler).get(); } } - + return response; } catch (java.util.concurrent.ExecutionException e) { - // Unwrap ExecutionException to get the original cause for retry mechanism if (e.getCause() instanceof IOException) { throw (IOException) e.getCause(); } else if (e.getCause() instanceof InterruptedException) { @@ -859,7 +1006,8 @@ public static class Builder { private HttpClient.Builder httpClientBuilder; private HttpClient httpClient; private HxConfig.Builder configBuilder; - + private HxTokenStore tokenStore; + /** * Creates a new Builder with default settings. */ @@ -1145,7 +1293,33 @@ public Builder refreshCookiePolicy(CookiePolicy policy) { this.configBuilder.refreshCookiePolicy(policy); return this; } - + + /** + * Sets the token store for multi-session authentication. + * + *

The token store manages JWT token pairs for multiple authentication sessions. + * By default, an in-memory {@code ConcurrentHashMap}-based store is used. For distributed + * deployments, provide a custom implementation backed by Redis, a database, or other + * distributed cache. + * + *

Usage Example: + *

{@code
+         * HxTokenStore redisStore = new RedisTokenStore();
+         * HxClient client = HxClient.newBuilder()
+         *     .tokenStore(redisStore)
+         *     .refreshTokenUrl("https://api.example.com/oauth/token")
+         *     .build();
+         * }
+ * + * @param tokenStore the token store implementation + * @return this Builder instance + * @see HxTokenStore + */ + public Builder tokenStore(HxTokenStore tokenStore) { + this.tokenStore = tokenStore; + return this; + } + /** * Builds and returns a new HxClient instance. * @@ -1155,11 +1329,11 @@ public Builder refreshCookiePolicy(CookiePolicy policy) { * @return a new HxClient instance */ public HxClient build() { - final HttpClient actualHttpClient = (httpClient != null) - ? httpClient + final HttpClient actualHttpClient = (httpClient != null) + ? httpClient : httpClientBuilder.build(); final HxConfig actualConfig = configBuilder.build(); - return new HxClient(actualHttpClient, actualConfig); + return new HxClient(actualHttpClient, actualConfig, tokenStore); } } } diff --git a/lib-httpx/src/main/java/io/seqera/http/HxMapTokenStore.java b/lib-httpx/src/main/java/io/seqera/http/HxMapTokenStore.java new file mode 100644 index 00000000..099490fd --- /dev/null +++ b/lib-httpx/src/main/java/io/seqera/http/HxMapTokenStore.java @@ -0,0 +1,50 @@ +/* + * Copyright 2025, Seqera Labs + * + * 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. + * + */ + +package io.seqera.http; + +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.ConcurrentMap; + +/** + * Default in-memory implementation of {@link HxTokenStore} using a {@link ConcurrentHashMap}. + * + *

This implementation is thread-safe and suitable for single-instance deployments. + * For distributed deployments, consider using a custom implementation backed by + * Redis, a database, or another distributed cache. + * + * @author Paolo Di Tommaso + */ +class HxMapTokenStore implements HxTokenStore { + + private final ConcurrentMap store = new ConcurrentHashMap<>(); + + @Override + public HxAuth get(String key) { + return store.get(key); + } + + @Override + public void put(String key, HxAuth auth) { + store.put(key, auth); + } + + @Override + public HxAuth remove(String key) { + return store.remove(key); + } +} diff --git a/lib-httpx/src/main/java/io/seqera/http/HxTokenManager.java b/lib-httpx/src/main/java/io/seqera/http/HxTokenManager.java index 29322853..b94947ed 100644 --- a/lib-httpx/src/main/java/io/seqera/http/HxTokenManager.java +++ b/lib-httpx/src/main/java/io/seqera/http/HxTokenManager.java @@ -27,9 +27,11 @@ import java.nio.charset.StandardCharsets; import java.util.Base64; import java.util.concurrent.CompletableFuture; -import java.util.concurrent.locks.ReentrantReadWriteLock; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.ConcurrentMap; import java.util.regex.Pattern; + import com.google.gson.JsonObject; import com.google.gson.JsonParser; import org.slf4j.Logger; @@ -91,35 +93,42 @@ * @see HxConfig * @see HxClient */ -public class HxTokenManager { +class HxTokenManager { private static final Logger log = LoggerFactory.getLogger(HxTokenManager.class); - + private static final Pattern JWT_PATTERN = Pattern.compile("^[A-Za-z0-9_-]+\\.[A-Za-z0-9_-]+\\.[A-Za-z0-9_-]+$"); private static final String BEARER_PREFIX = "Bearer "; + private static final String DEFAULT_TOKEN = "default-token"; private final HxConfig config; private final HttpClient refreshHttpClient; private final CookieManager cookieManager; - private final ReentrantReadWriteLock lock = new ReentrantReadWriteLock(); + private final HxTokenStore tokenStore; - private volatile String currentJwtToken; - - private volatile String currentRefreshToken; - - // Coordination for concurrent token refresh operations - private volatile CompletableFuture currentRefresh = null; + // Coordination for concurrent token refresh operations per key + private final ConcurrentMap> ongoingRefreshes = new ConcurrentHashMap<>(); public HxTokenManager(HxConfig config) { + this(config, new HxMapTokenStore()); + } + + public HxTokenManager(HxConfig config, HxTokenStore tokenStore) { this.config = config; - this.currentJwtToken = config.getJwtToken(); - this.currentRefreshToken = config.getRefreshToken(); - + this.tokenStore = tokenStore; + + // Store initial tokens from config using DEFAULT_KEY + final String jwtToken = config.getJwtToken(); + final String refreshToken = config.getRefreshToken(); + if (jwtToken != null && !jwtToken.isEmpty()) { + tokenStore.put(DEFAULT_TOKEN, HxAuth.of(jwtToken, refreshToken)); + } + // Validate JWT token refresh configuration validateTokenRefreshConfig(); - + // Create CookieManager with custom policy if provided - this.cookieManager = (config.getRefreshCookiePolicy() != null) + this.cookieManager = (config.getRefreshCookiePolicy() != null) ? new CookieManager(null, config.getRefreshCookiePolicy()) : new CookieManager(); this.refreshHttpClient = HttpClient.newBuilder() @@ -145,8 +154,10 @@ public HxTokenManager(HxConfig config) { * @throws IllegalArgumentException if the JWT configuration is incomplete or inconsistent */ private void validateTokenRefreshConfig() { - final boolean hasJwtToken = currentJwtToken != null && !currentJwtToken.trim().isEmpty(); - final boolean hasRefreshToken = currentRefreshToken != null && !currentRefreshToken.trim().isEmpty(); + final String jwtToken = getCurrentJwtToken(); + final String refreshToken = getCurrentRefreshToken(); + final boolean hasJwtToken = jwtToken != null && !jwtToken.trim().isEmpty(); + final boolean hasRefreshToken = refreshToken != null && !refreshToken.trim().isEmpty(); final boolean hasRefreshUrl = config.getRefreshTokenUrl() != null && !config.getRefreshTokenUrl().trim().isEmpty(); // Count how many refresh components we have @@ -227,11 +238,12 @@ public HttpRequest addAuthHeader(HttpRequest originalRequest) { /** * Checks whether token refresh is possible with the current configuration. - * + * * @return true if both refresh token and refresh URL are configured, false otherwise */ public boolean canRefreshToken() { - return currentRefreshToken != null && config.getRefreshTokenUrl() != null; + final HxAuth auth = tokenStore.get(DEFAULT_TOKEN); + return auth != null && auth.refreshToken() != null && config.getRefreshTokenUrl() != null; } /** @@ -252,21 +264,33 @@ public boolean canRefreshToken() { */ public boolean refreshToken() { if (!canRefreshToken()) { - log.warn("Cannot refresh token: refreshToken={} refreshTokenUrl={}", (currentRefreshToken != null), config.getRefreshTokenUrl()); + final HxAuth auth = tokenStore.get(DEFAULT_TOKEN); + log.warn("Cannot refresh token: refreshToken={} refreshTokenUrl={}", + (auth != null && auth.refreshToken() != null), config.getRefreshTokenUrl()); return false; } + return doRefreshToken(); + } - lock.writeLock().lock(); - try { - return doRefreshToken(); - } finally { - lock.writeLock().unlock(); + /** + * Gets or initiates a coordinated token refresh operation to prevent concurrent refreshes. + * + *

This method delegates to {@link #getOrRefreshTokenAsync(HxAuth)} using the default token. + * + * @return a CompletableFuture that completes with true if refresh was successful, false otherwise + */ + public CompletableFuture getOrRefreshTokenAsync() { + final HxAuth auth = tokenStore.get(DEFAULT_TOKEN); + if (auth == null) { + log.warn("Cannot refresh token: no default auth configured"); + return CompletableFuture.completedFuture(false); } + return getOrRefreshTokenAsync(auth).thenApply(result -> result != null); } /** - * Gets or initiates a coordinated token refresh operation to prevent concurrent refreshes. - * + * Gets or initiates a coordinated token refresh operation for the given auth. + * *

This method ensures that multiple concurrent requests that need token refresh will * share a single refresh operation instead of each performing their own refresh. This: *

    @@ -275,201 +299,67 @@ public boolean refreshToken() { *
  • Improves performance under high concurrency
  • *
  • Avoids hitting rate limits on token refresh endpoints
  • *
- * - *

The coordination mechanism: - *

    - *
  • First caller starts the refresh and gets a CompletableFuture
  • - *
  • Subsequent callers get the same CompletableFuture to wait on
  • - *
  • Once refresh completes, all waiters are notified with the same result
  • - *
  • Future state is reset after completion for next refresh cycle
  • - *
- * - * @return a CompletableFuture that completes with true if refresh was successful, false otherwise + * + * @param auth the authentication data to refresh + * @return a CompletableFuture that completes with the refreshed HxAuth, or null if refresh failed */ - public CompletableFuture getOrRefreshTokenAsync() { - if (!canRefreshToken()) { - log.warn("Cannot refresh token: refreshToken={} refreshTokenUrl={}", (currentRefreshToken != null), config.getRefreshTokenUrl()); - return CompletableFuture.completedFuture(false); + public CompletableFuture getOrRefreshTokenAsync(HxAuth auth) { + if (!canRefreshToken(auth)) { + log.warn("Cannot refresh token: refreshToken={} refreshTokenUrl={}", + (auth != null && auth.refreshToken() != null), config.getRefreshTokenUrl()); + return CompletableFuture.completedFuture(null); } - // Check if there's already a refresh in progress - CompletableFuture refresh = currentRefresh; - if (refresh != null && !refresh.isDone()) { - log.trace("Token refresh already in progress, waiting for completion"); - return refresh; - } - - // Use double-checked locking to ensure only one thread starts the refresh - synchronized(this) { - refresh = currentRefresh; - if (refresh != null && !refresh.isDone()) { - log.trace("Token refresh already in progress (double-check), waiting for completion"); - return refresh; - } - - // Start new refresh operation - log.trace("Starting coordinated token refresh"); - currentRefresh = CompletableFuture.supplyAsync(() -> { - lock.writeLock().lock(); - try { - return doRefreshToken(); - } finally { - lock.writeLock().unlock(); - } - }).whenComplete((result, throwable) -> { - // Reset the currentRefresh after completion to allow future refreshes - synchronized(this) { - if (currentRefresh != null && currentRefresh.isDone()) { - currentRefresh = null; - } - } - - if (throwable != null) { - log.error("Coordinated token refresh failed: " + throwable.getMessage(), throwable); - } else { - log.trace("Coordinated token refresh completed with result: " + result); - } - }); - - return currentRefresh; - } + final String key = auth.key(); + + // Use computeIfAbsent for atomic coordination - only first caller creates the future + return ongoingRefreshes.computeIfAbsent(key, k -> { + log.trace("Starting coordinated token refresh for key {}", k); + return CompletableFuture.supplyAsync(() -> doRefreshToken(auth)) + .whenComplete((result, throwable) -> { + // Remove from map after completion to allow future refreshes + ongoingRefreshes.remove(key); + if (throwable != null) { + log.error("Coordinated token refresh failed for key {}: {}", key, throwable.getMessage(), throwable); + } else { + log.trace("Coordinated token refresh completed for key {} with result: {}", key, (result != null)); + } + }); + }); } /** * Attempts to refresh the JWT token asynchronously using the configured refresh token. - * + * *

This method performs the same OAuth 2.0 refresh token flow as {@link #refreshToken()} * but returns a CompletableFuture for non-blocking execution. - * - *

This method is thread-safe and uses write locks to prevent concurrent modifications. - * + * * @return a CompletableFuture that completes with true if refresh was successful, false otherwise */ public CompletableFuture refreshTokenAsync() { if (!canRefreshToken()) { - log.warn("Cannot refresh token asynchronously: refreshToken={} refreshTokenUrl={}", (currentRefreshToken != null), config.getRefreshTokenUrl()); + final HxAuth auth = tokenStore.get(DEFAULT_TOKEN); + log.warn("Cannot refresh token asynchronously: refreshToken={} refreshTokenUrl={}", + (auth != null && auth.refreshToken() != null), config.getRefreshTokenUrl()); return CompletableFuture.completedFuture(false); } - - return CompletableFuture.supplyAsync(() -> { - lock.writeLock().lock(); - try { - return doRefreshToken(); - } finally { - lock.writeLock().unlock(); - } - }); + return CompletableFuture.supplyAsync(this::doRefreshToken); } /** * Internal method that performs the actual token refresh HTTP request. - * - *

This method: - *

    - *
  • Creates a POST request with form-urlencoded body
  • - *
  • Includes grant_type=refresh_token and the URL-encoded refresh token
  • - *
  • Sends the request with the configured timeout
  • - *
  • Handles both cookie-based and JSON response formats
  • - *
  • Updates internal token state on success
  • - *
- * - *

This method is called by both synchronous and asynchronous refresh methods - * and assumes the caller has acquired the appropriate write lock. - * + * + *

This method delegates to {@link #doRefreshTokenInternal(String, HxAuth)} using the default token. + * * @return true if the token refresh was successful, false otherwise */ protected boolean doRefreshToken() { - try { - final var refreshUrl = URI.create(config.getRefreshTokenUrl()); - log.trace("Attempting to refresh JWT token using refresh token at URL: {}", refreshUrl); - - final String body = "grant_type=refresh_token&refresh_token=" + - URLEncoder.encode(currentRefreshToken, StandardCharsets.UTF_8); - - final HttpRequest request = HttpRequest.newBuilder() - .uri(refreshUrl) - .header("Content-Type", "application/x-www-form-urlencoded") - .POST(HttpRequest.BodyPublishers.ofString(body)) - .timeout(config.getTokenRefreshTimeout()) - .build(); - - final HttpResponse response = refreshHttpClient.send(request, HttpResponse.BodyHandlers.ofString()); - log.trace("Token refresh response: [{}]", response.statusCode()); - - if (response.statusCode() == 200) { - final var result = handleRefreshResponse(response); - log.debug("JWT token refresh completed with result: {}", result); - return result; - } else { - log.warn("Token refresh failed with status {}: {}", response.statusCode(), response.body()); - return false; - } - } catch (Exception e) { - log.error("Error refreshing JWT token: " + e.getMessage(), e); - return false; - } - } - - /** - * Processes the HTTP response from a token refresh request and extracts new tokens. - * - *

This method supports multiple response formats: - *

    - *
  • Cookie-based: Extracts JWT and JWT_REFRESH_TOKEN from cookie store
  • - *
  • JSON-based: Parses JSON response body for access_token and refresh_token fields
  • - *
- * - *

The method validates extracted JWT tokens using {@link #isValidJwtToken(String)} - * and updates the internal token state atomically. - * - * @param response the HTTP response from the token refresh request - * @return true if tokens were successfully extracted and updated, false otherwise - */ - protected boolean handleRefreshResponse(HttpResponse response) { - try { - // First try to extract tokens from cookie store (same approach as TowerXAuth) - final HttpCookie authCookie = getCookie("JWT"); - final HttpCookie refreshCookie = getCookie("JWT_REFRESH_TOKEN"); - - if (authCookie != null && authCookie.getValue() != null) { - log.trace("Successfully refreshed JWT token"); - currentJwtToken = authCookie.getValue(); - - if (refreshCookie != null && refreshCookie.getValue() != null) { - log.trace("Successfully refreshed refresh token"); - currentRefreshToken = refreshCookie.getValue(); - } - - return true; - } else { - log.trace("No JWT token found in cookies, trying JSON response"); - - try { - final JsonObject jsonResponse = JsonParser.parseString(response.body()).getAsJsonObject(); - if (jsonResponse.has("access_token")) { - final String accessToken = jsonResponse.get("access_token").getAsString(); - if (isValidJwtToken(accessToken)) { - log.trace("Successfully extracted JWT token from JSON"); - currentJwtToken = accessToken; - - if (jsonResponse.has("refresh_token")) { - currentRefreshToken = jsonResponse.get("refresh_token").getAsString(); - log.trace("Successfully extracted refresh token from JSON"); - } - - return true; - } - } - } catch (Exception e) { - log.trace("Response is not valid JSON, trying to parse as form data"); - } - - return false; - } - } catch (Exception e) { - log.error("Error processing token refresh response: " + e.getMessage(), e); + final HxAuth auth = tokenStore.get(DEFAULT_TOKEN); + if (auth == null) { + log.warn("No auth available for default key"); return false; } + return doRefreshTokenInternal(DEFAULT_TOKEN, auth) != null; } /** @@ -512,31 +402,23 @@ protected boolean isValidJwtToken(String token) { } /** - * Gets the current JWT token in a thread-safe manner. - * + * Gets the current JWT token. + * * @return the current JWT token, or null if not set */ public String getCurrentJwtToken() { - lock.readLock().lock(); - try { - return currentJwtToken; - } finally { - lock.readLock().unlock(); - } + final HxAuth auth = tokenStore.get(DEFAULT_TOKEN); + return auth != null ? auth.accessToken() : null; } /** - * Gets the current refresh token in a thread-safe manner. - * + * Gets the current refresh token. + * * @return the current refresh token, or null if not set */ public String getCurrentRefreshToken() { - lock.readLock().lock(); - try { - return currentRefreshToken; - } finally { - lock.readLock().unlock(); - } + final HxAuth auth = tokenStore.get(DEFAULT_TOKEN); + return auth != null ? auth.refreshToken() : null; } /** @@ -568,28 +450,251 @@ public boolean hasBasicAuth() { } /** - * Updates both JWT and refresh tokens atomically in a thread-safe manner. - * + * Updates both JWT and refresh tokens atomically. + * *

This method validates the JWT token format before updating and will not * update an invalid JWT token. The refresh token is updated if provided, * regardless of format (as refresh tokens may have different formats). - * + * * @param jwtToken the new JWT token to set, may be null * @param refreshToken the new refresh token to set, may be null */ public void updateTokens(String jwtToken, String refreshToken) { - lock.writeLock().lock(); + final HxAuth currentAuth = tokenStore.get(DEFAULT_TOKEN); + String newToken = (currentAuth != null) ? currentAuth.accessToken() : null; + String newRefresh = (currentAuth != null) ? currentAuth.refreshToken() : null; + + if (jwtToken != null && isValidJwtToken(jwtToken)) { + newToken = jwtToken; + log.trace("JWT token updated"); + } + if (refreshToken != null) { + newRefresh = refreshToken; + log.trace("Refresh token updated"); + } + + if (newToken != null) { + tokenStore.put(DEFAULT_TOKEN, HxAuth.of(newToken, newRefresh)); + } + } + + // ======================================================================== + // Multi-user token management methods + // ======================================================================== + + /** + * Gets the current authentication data for the given auth from the token store. + * + *

If the auth has been refreshed, this returns the updated tokens. If not found + * in the store, the original auth is stored and returned for future use. + * + * @param auth the original authentication data + * @return the current authentication data (may contain refreshed tokens) + */ + public HxAuth getAuth(HxAuth auth) { + if (auth == null) { + return null; + } + HxAuth stored = tokenStore.get(auth.key()); + if (stored == null) { + tokenStore.put(auth.key(), auth); + return auth; + } + return stored; + } + + /** + * Adds an Authorization header to the given HTTP request using the token from the provided {@link HxAuth}. + * + *

This method retrieves the latest token for the given auth from the token store (in case it was + * refreshed) and adds the Bearer Authorization header to the request. + * + * @param originalRequest the original HTTP request + * @param auth the authentication data containing the token + * @return a new HttpRequest with Authorization header + */ + public HttpRequest addAuthHeader(HttpRequest originalRequest, HxAuth auth) { + final HxAuth currentAuth = getAuth(auth); + final String jwtToken = currentAuth != null ? currentAuth.accessToken() : null; + + if (jwtToken != null && !jwtToken.isEmpty()) { + final String headerValue = jwtToken.startsWith(BEARER_PREFIX) ? jwtToken : BEARER_PREFIX + jwtToken; + return HttpRequest.newBuilder(originalRequest, (name, value) -> true) + .header("Authorization", headerValue) + .build(); + } + + return originalRequest; + } + + /** + * Checks whether token refresh is possible for the given auth. + * + * @param auth the authentication data + * @return true if both refresh token and refresh URL are configured, false otherwise + */ + public boolean canRefreshToken(HxAuth auth) { + if (auth == null) { + return false; + } + final HxAuth currentAuth = getAuth(auth); + return currentAuth.refreshToken() != null && config.getRefreshTokenUrl() != null; + } + + /** + * Attempts to refresh the JWT token synchronously for the given auth. + * + *

This method performs an OAuth 2.0 refresh token flow for a specific user session. + * On success, the new tokens are stored in the token store automatically. + * + * @param auth the authentication data containing the refresh token + * @return the updated {@link HxAuth} with new tokens, or null if refresh failed + */ + public HxAuth refreshToken(HxAuth auth) { + if (!canRefreshToken(auth)) { + log.warn("Cannot refresh token for auth: refreshToken={} refreshTokenUrl={}", + (auth != null && auth.refreshToken() != null), config.getRefreshTokenUrl()); + return null; + } + return doRefreshToken(auth); + } + + /** + * Attempts to refresh the JWT token asynchronously for the given auth. + * + * @param auth the authentication data containing the refresh token + * @return a CompletableFuture that completes with the updated {@link HxAuth}, or null if refresh failed + */ + public CompletableFuture refreshTokenAsync(HxAuth auth) { + if (!canRefreshToken(auth)) { + log.warn("Cannot refresh token asynchronously for auth: refreshToken={} refreshTokenUrl={}", + (auth != null && auth.refreshToken() != null), config.getRefreshTokenUrl()); + return CompletableFuture.completedFuture(null); + } + return CompletableFuture.supplyAsync(() -> doRefreshToken(auth)); + } + + /** + * Performs the actual token refresh for a specific auth. + * + *

This method delegates to {@link #doRefreshTokenInternal(String, HxAuth)} using the auth's key. + * + * @param auth the authentication data containing the refresh token + * @return the updated {@link HxAuth} with new tokens, or null if refresh failed + */ + protected HxAuth doRefreshToken(HxAuth auth) { + final HxAuth currentAuth = getAuth(auth); + return doRefreshTokenInternal(auth.key(), currentAuth); + } + + /** + * Internal method that performs the actual token refresh HTTP request. + * + * @param key the key to use for storing the refreshed token + * @param auth the authentication data containing the refresh token + * @return the updated {@link HxAuth} with new tokens, or null if refresh failed + */ + protected HxAuth doRefreshTokenInternal(String key, HxAuth auth) { try { - if (jwtToken != null && isValidJwtToken(jwtToken)) { - this.currentJwtToken = jwtToken; - log.trace("JWT token updated"); + final var refreshUrl = URI.create(config.getRefreshTokenUrl()); + log.trace("Attempting to refresh JWT token for key {} at URL: {}", key, refreshUrl); + + final String body = "grant_type=refresh_token&refresh_token=" + + URLEncoder.encode(auth.refreshToken(), StandardCharsets.UTF_8); + + final HttpRequest request = HttpRequest.newBuilder() + .uri(refreshUrl) + .header("Content-Type", "application/x-www-form-urlencoded") + .POST(HttpRequest.BodyPublishers.ofString(body)) + .timeout(config.getTokenRefreshTimeout()) + .build(); + + final HttpResponse response = refreshHttpClient.send(request, HttpResponse.BodyHandlers.ofString()); + log.trace("Token refresh response for key {}: [{}]", key, response.statusCode()); + + if (response.statusCode() == 200) { + final HxAuth newAuth = extractAuthFromResponse(response, auth); + if (newAuth != null) { + log.debug("JWT token refresh completed for key {}", key); + tokenStore.put(key, newAuth); + return newAuth; + } + } else { + log.warn("Token refresh failed for key {} with status {}: {}", + key, response.statusCode(), response.body()); } - if (refreshToken != null) { - this.currentRefreshToken = refreshToken; - log.trace("Refresh token updated"); + return null; + } catch (Exception e) { + log.error("Error refreshing JWT token for key {}: {}", key, e.getMessage(), e); + return null; + } + } + + /** + * Extracts tokens from the HTTP response and creates a new {@link HxAuth}. + * + * @param response the HTTP response from the token refresh request + * @param originalAuth the original authentication data (used to preserve refresh token if not returned) + * @return a new {@link HxAuth} with updated tokens, or null if extraction failed + */ + protected HxAuth extractAuthFromResponse(HttpResponse response, HxAuth originalAuth) { + try { + // First try to extract tokens from cookie store + final HttpCookie authCookie = getCookie("JWT"); + final HttpCookie refreshCookie = getCookie("JWT_REFRESH_TOKEN"); + + if (authCookie != null && authCookie.getValue() != null) { + log.trace("Successfully extracted JWT token from cookies"); + final String newToken = authCookie.getValue(); + final String newRefresh = (refreshCookie != null && refreshCookie.getValue() != null) + ? refreshCookie.getValue() + : originalAuth.refreshToken(); + return HxAuth.of(newToken, newRefresh); + } else { + log.trace("No JWT token found in cookies, trying JSON response"); + + try { + final JsonObject jsonResponse = JsonParser.parseString(response.body()).getAsJsonObject(); + if (jsonResponse.has("access_token")) { + final String accessToken = jsonResponse.get("access_token").getAsString(); + if (isValidJwtToken(accessToken)) { + log.trace("Successfully extracted JWT token from JSON"); + final String newRefresh = jsonResponse.has("refresh_token") + ? jsonResponse.get("refresh_token").getAsString() + : originalAuth.refreshToken(); + return HxAuth.of(accessToken, newRefresh); + } + } + } catch (Exception e) { + log.trace("Response is not valid JSON"); + } + + return null; } - } finally { - lock.writeLock().unlock(); + } catch (Exception e) { + log.error("Error extracting tokens from response: {}", e.getMessage(), e); + return null; } } + + /** + * Returns the token store used by this manager. + * + * @return the {@link HxTokenStore} instance + */ + public HxTokenStore getTokenStore() { + return tokenStore; + } + + /** + * Returns the default authentication data configured from HxConfig. + * + *

This is the auth stored under the default key, initialized from + * the JWT token and refresh token configured in HxConfig. + * + * @return the default {@link HxAuth}, or null if no default token is configured + */ + public HxAuth getDefaultAuth() { + return tokenStore.get(DEFAULT_TOKEN); + } } diff --git a/lib-httpx/src/main/java/io/seqera/http/HxTokenStore.java b/lib-httpx/src/main/java/io/seqera/http/HxTokenStore.java new file mode 100644 index 00000000..437cf772 --- /dev/null +++ b/lib-httpx/src/main/java/io/seqera/http/HxTokenStore.java @@ -0,0 +1,57 @@ +/* + * Copyright 2025, Seqera Labs + * + * 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. + * + */ + +package io.seqera.http; + +/** + * Interface for storing and retrieving JWT token pairs by key. + * + *

This interface allows for different storage strategies for managing + * multiple user sessions, each with their own token-refresh pair. The key + * is typically derived from the token itself (e.g., SHA-256 hash). + * + *

Implementations should be thread-safe as they may be accessed + * concurrently by multiple requests. + * + * @author Paolo Di Tommaso + */ +public interface HxTokenStore { + + /** + * Retrieves the authentication data for the given key. + * + * @param key the unique key identifying the token pair (typically SHA-256 of the token) + * @return the {@link HxAuth} containing the token pair, or null if not found + */ + HxAuth get(String key); + + /** + * Stores the authentication data for the given key. + * + * @param key the unique key identifying the token pair (typically SHA-256 of the token) + * @param auth the {@link HxAuth} containing the token pair to store + */ + void put(String key, HxAuth auth); + + /** + * Removes the authentication data for the given key. + * + * @param key the unique key identifying the token pair to remove + * @return the removed {@link HxAuth}, or null if not found + */ + HxAuth remove(String key); +} diff --git a/lib-httpx/src/test/groovy/io/seqera/http/HxAuthTest.groovy b/lib-httpx/src/test/groovy/io/seqera/http/HxAuthTest.groovy new file mode 100644 index 00000000..4eaf08a2 --- /dev/null +++ b/lib-httpx/src/test/groovy/io/seqera/http/HxAuthTest.groovy @@ -0,0 +1,71 @@ +/* + * Copyright 2025, Seqera Labs + * + * 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. + * + */ + +package io.seqera.http + +import spock.lang.Specification + +/** + * Unit tests for HxAuth + * + * @author Paolo Di Tommaso + */ +class HxAuthTest extends Specification { + + def 'should create auth with token only'() { + when: + def auth = HxAuth.of('my.jwt.token') + + then: + auth.accessToken() == 'my.jwt.token' + auth.refreshToken() == null + } + + def 'should create auth with token and refresh'() { + when: + def auth = HxAuth.of('my.jwt.token', 'my-refresh-token') + + then: + auth.accessToken() == 'my.jwt.token' + auth.refreshToken() == 'my-refresh-token' + } + + def 'should compute consistent key from token'() { + given: + def auth1 = HxAuth.of('my.jwt.token', 'refresh1') + def auth2 = HxAuth.of('my.jwt.token', 'refresh2') + def auth3 = HxAuth.of('different.jwt.token', 'refresh1') + + expect: + auth1.key() == auth2.key() // same token = same key + auth1.key() != auth3.key() // different token = different key + auth1.key().length() == 64 // SHA-256 hex = 64 chars + } + + def 'should implement equals and hashCode correctly'() { + expect: + HxAuth.of(token1, refresh1) == HxAuth.of(token2, refresh2) == expected + (HxAuth.of(token1, refresh1).hashCode() == HxAuth.of(token2, refresh2).hashCode()) == expected + + where: + token1 | refresh1 | token2 | refresh2 | expected + 'a.b.c' | 'r1' | 'a.b.c' | 'r1' | true + 'a.b.c' | null | 'a.b.c' | null | true + 'a.b.c' | 'r1' | 'a.b.c' | 'r2' | false + 'a.b.c' | 'r1' | 'x.y.z' | 'r1' | false + } +} diff --git a/lib-httpx/src/test/groovy/io/seqera/http/HxClientTest.groovy b/lib-httpx/src/test/groovy/io/seqera/http/HxClientTest.groovy index d4ad1865..808dd8d9 100644 --- a/lib-httpx/src/test/groovy/io/seqera/http/HxClientTest.groovy +++ b/lib-httpx/src/test/groovy/io/seqera/http/HxClientTest.groovy @@ -384,4 +384,17 @@ class HxClientTest extends Specification { .build() client3.config.refreshCookiePolicy == CookiePolicy.ACCEPT_ORIGINAL_SERVER } + + def 'should configure custom token store via builder'() { + given: + def customStore = new HxMapTokenStore() + + when: + def client = HxClient.newBuilder() + .tokenStore(customStore) + .build() + + then: + client.tokenManager.getTokenStore() == customStore + } } diff --git a/lib-httpx/src/test/groovy/io/seqera/http/HxMapTokenStoreTest.groovy b/lib-httpx/src/test/groovy/io/seqera/http/HxMapTokenStoreTest.groovy new file mode 100644 index 00000000..34b8b458 --- /dev/null +++ b/lib-httpx/src/test/groovy/io/seqera/http/HxMapTokenStoreTest.groovy @@ -0,0 +1,59 @@ +/* + * Copyright 2025, Seqera Labs + * + * 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. + * + */ + +package io.seqera.http + +import java.util.concurrent.CountDownLatch +import java.util.concurrent.Executors + +import spock.lang.Specification + +/** + * Unit tests for HxMapTokenStore + * + * @author Paolo Di Tommaso + */ +class HxMapTokenStoreTest extends Specification { + + def 'should store and retrieve auth by key'() { + given: + def store = new HxMapTokenStore() + def auth = HxAuth.of('my.jwt.token', 'refresh') + + when: + store.put('key1', auth) + + then: + store.get('key1') == auth + store.get('unknown') == null + } + + def 'should remove auth'() { + given: + def store = new HxMapTokenStore() + def auth = HxAuth.of('my.jwt.token', 'refresh') + store.put('key1', auth) + + when: + def removed = store.remove('key1') + + then: + removed == auth + store.get('key1') == null + store.remove('key1') == null + } +} diff --git a/lib-httpx/src/test/groovy/io/seqera/http/HxTokenManagerTest.groovy b/lib-httpx/src/test/groovy/io/seqera/http/HxTokenManagerTest.groovy index 73b76902..7784b81e 100644 --- a/lib-httpx/src/test/groovy/io/seqera/http/HxTokenManagerTest.groovy +++ b/lib-httpx/src/test/groovy/io/seqera/http/HxTokenManagerTest.groovy @@ -280,4 +280,77 @@ class HxTokenManagerTest extends Specification { tokenManager2.cookieManager != tokenManager3.cookieManager tokenManager1.cookieManager != tokenManager3.cookieManager } + + // --- Multi-token support tests --- + + def 'getAuth should store and return auth on first call'() { + given: + def config = HxConfig.newBuilder().build() + def tokenManager = new HxTokenManager(config) + def auth = HxAuth.of('my.jwt.token', 'refresh') + + when: + def result = tokenManager.getAuth(auth) + + then: + result == auth + tokenManager.getAuth(auth) == auth // subsequent calls return same + } + + def 'getAuth should return null for null input'() { + given: + def config = HxConfig.newBuilder().build() + def tokenManager = new HxTokenManager(config) + + expect: + tokenManager.getAuth(null) == null + } + + def 'addAuthHeader should work with HxAuth parameter'() { + given: + def config = HxConfig.newBuilder().build() + def tokenManager = new HxTokenManager(config) + def auth = HxAuth.of('custom.jwt.token', 'refresh') + def request = HttpRequest.newBuilder() + .uri(URI.create('https://example.com/api')) + .GET() + .build() + + when: + def result = tokenManager.addAuthHeader(request, auth) + + then: + result.headers().firstValue('Authorization').orElse(null) == 'Bearer custom.jwt.token' + } + + def 'canRefreshToken should check HxAuth configuration'() { + given: + def configWithUrl = HxConfig.newBuilder() + .bearerToken('default.jwt.token') + .refreshToken('default-refresh') + .refreshTokenUrl('https://example.com/oauth/token') + .build() + def configWithoutUrl = HxConfig.newBuilder().build() + + expect: + new HxTokenManager(configWithUrl).canRefreshToken(HxAuth.of('a.b.c', 'refresh')) == true + new HxTokenManager(configWithUrl).canRefreshToken(HxAuth.of('a.b.c', null)) == false + new HxTokenManager(configWithUrl).canRefreshToken(null) == false + new HxTokenManager(configWithoutUrl).canRefreshToken(HxAuth.of('a.b.c', 'refresh')) == false + } + + def 'should accept custom token store'() { + given: + def customStore = new HxMapTokenStore() + def config = HxConfig.newBuilder().build() + def tokenManager = new HxTokenManager(config, customStore) + def auth = HxAuth.of('my.jwt.token', 'refresh') + + when: + tokenManager.getAuth(auth) + + then: + customStore.get(auth.key()) == auth + tokenManager.getTokenStore() == customStore + } } From 97f7e818608a5b6a06328e9bfe65e200e407726a Mon Sep 17 00:00:00 2001 From: Paolo Di Tommaso Date: Mon, 5 Jan 2026 19:08:48 +0700 Subject: [PATCH 2/9] Refactor key computation to HxAuth static methods MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - Move key() method from HxTokenStore to HxAuth as static method - Add keyOrDefault(auth, defaultValue) for null-safe key computation - Remove key() default method from HxTokenStore interface - key() now throws IllegalArgumentException for null auth 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude Opus 4.5 --- .../src/main/java/io/seqera/http/HxAuth.java | 31 ++++++++++++++----- .../main/java/io/seqera/http/HxClient.java | 8 ++--- .../java/io/seqera/http/HxTokenManager.java | 9 +++--- .../groovy/io/seqera/http/HxAuthTest.groovy | 13 ++++++-- .../io/seqera/http/HxMapTokenStoreTest.groovy | 4 +-- .../io/seqera/http/HxTokenManagerTest.groovy | 2 +- 6 files changed, 45 insertions(+), 22 deletions(-) diff --git a/lib-httpx/src/main/java/io/seqera/http/HxAuth.java b/lib-httpx/src/main/java/io/seqera/http/HxAuth.java index 8f3e2642..895739e5 100644 --- a/lib-httpx/src/main/java/io/seqera/http/HxAuth.java +++ b/lib-httpx/src/main/java/io/seqera/http/HxAuth.java @@ -27,9 +27,8 @@ * Immutable container for JWT authentication credentials. * *

This class holds a JWT access token and an optional refresh token as a pair. - * It provides a {@link #key()} method that computes a SHA-256 hash of the token, - * which can be used as a unique identifier for storing and retrieving token pairs - * in an {@link HxTokenStore}. + * The storage key can be computed using {@link #key(HxAuth)} which returns the + * SHA-256 hash of the access token. * *

Instances are created using the factory methods {@link #of(String)} or * {@link #of(String, String)}. @@ -68,14 +67,21 @@ public static HxAuth of(String token, String refresh) { } /** - * Computes the SHA-256 hash of the access token. + * Computes the storage key for the given authentication object. * - * @return the SHA-256 hash as a hexadecimal string + *

Returns the SHA-256 hash of the access token as a hexadecimal string. + * + * @param auth the authentication object (must not be null) + * @return the computed key as a 64-character hexadecimal string + * @throws IllegalArgumentException if auth is null */ - public String key() { + public static String key(HxAuth auth) { + if (auth == null) { + throw new IllegalArgumentException("auth cannot be null"); + } try { final MessageDigest digest = MessageDigest.getInstance("SHA-256"); - final byte[] hash = digest.digest(accessToken.getBytes(StandardCharsets.UTF_8)); + final byte[] hash = digest.digest(auth.accessToken().getBytes(StandardCharsets.UTF_8)); return HexFormat.of().formatHex(hash); } catch (NoSuchAlgorithmException e) { @@ -83,6 +89,17 @@ public String key() { } } + /** + * Computes the storage key for the given authentication object, or returns a default value if null. + * + * @param auth the authentication object, may be null + * @param defaultValue the value to return if auth is null + * @return the computed key, or defaultValue if auth is null + */ + public static String keyOrDefault(HxAuth auth, String defaultValue) { + return auth != null ? key(auth) : defaultValue; + } + /** * Returns the JWT access token. * diff --git a/lib-httpx/src/main/java/io/seqera/http/HxClient.java b/lib-httpx/src/main/java/io/seqera/http/HxClient.java index 849062d4..ee9bffe0 100644 --- a/lib-httpx/src/main/java/io/seqera/http/HxClient.java +++ b/lib-httpx/src/main/java/io/seqera/http/HxClient.java @@ -490,7 +490,7 @@ protected HttpResponse sendWithRetry(HttpRequest request, HxAuth auth, Ht // Try JWT token refresh final boolean canRefresh = (auth != null) ? tokenManager.canRefreshToken(auth) : tokenManager.canRefreshToken(); if (canRefresh) { - final String debugKey = (auth != null) ? auth.key() : "default"; + final String debugKey = HxAuth.keyOrDefault(auth, "-"); log.debug("Received 401 status for auth key {}, attempting token refresh", debugKey); try { final boolean refreshed = (auth != null) @@ -505,7 +505,7 @@ protected HttpResponse sendWithRetry(HttpRequest request, HxAuth auth, Ht return httpClient.send(refreshedRequest, responseBodyHandler); } } catch (Exception e) { - log.warn("Token refresh failed for auth key {}: {}", (auth != null) ? auth.key() : "default", e.getMessage()); + log.warn("Token refresh failed for auth key {}: {}", debugKey, e.getMessage()); } } @@ -576,7 +576,7 @@ protected CompletableFuture> sendWithRetryAsync( // Try JWT token refresh final boolean canRefresh = (auth != null) ? tokenManager.canRefreshToken(auth) : tokenManager.canRefreshToken(); if (canRefresh) { - final String debugKey = (auth != null) ? auth.key() : "default"; + final String debugKey = HxAuth.keyOrDefault(auth, "-"); log.debug("Received 401 status in async call for auth key {}, attempting token refresh", debugKey); try { final boolean refreshed = (auth != null) @@ -591,7 +591,7 @@ protected CompletableFuture> sendWithRetryAsync( return httpClient.sendAsync(refreshedRequest, responseBodyHandler).get(); } } catch (Exception e) { - log.warn("Async token refresh failed for auth key {}: {}", (auth != null) ? auth.key() : "default", e.getMessage()); + log.warn("Async token refresh failed for auth key {}: {}", debugKey, e.getMessage()); } } diff --git a/lib-httpx/src/main/java/io/seqera/http/HxTokenManager.java b/lib-httpx/src/main/java/io/seqera/http/HxTokenManager.java index b94947ed..81e15768 100644 --- a/lib-httpx/src/main/java/io/seqera/http/HxTokenManager.java +++ b/lib-httpx/src/main/java/io/seqera/http/HxTokenManager.java @@ -310,7 +310,7 @@ public CompletableFuture getOrRefreshTokenAsync(HxAuth auth) { return CompletableFuture.completedFuture(null); } - final String key = auth.key(); + final String key = HxAuth.key(auth); // Use computeIfAbsent for atomic coordination - only first caller creates the future return ongoingRefreshes.computeIfAbsent(key, k -> { @@ -495,9 +495,10 @@ public HxAuth getAuth(HxAuth auth) { if (auth == null) { return null; } - HxAuth stored = tokenStore.get(auth.key()); + final String key = HxAuth.key(auth); + HxAuth stored = tokenStore.get(key); if (stored == null) { - tokenStore.put(auth.key(), auth); + tokenStore.put(key, auth); return auth; } return stored; @@ -584,7 +585,7 @@ public CompletableFuture refreshTokenAsync(HxAuth auth) { */ protected HxAuth doRefreshToken(HxAuth auth) { final HxAuth currentAuth = getAuth(auth); - return doRefreshTokenInternal(auth.key(), currentAuth); + return doRefreshTokenInternal(HxAuth.key(auth), currentAuth); } /** diff --git a/lib-httpx/src/test/groovy/io/seqera/http/HxAuthTest.groovy b/lib-httpx/src/test/groovy/io/seqera/http/HxAuthTest.groovy index 4eaf08a2..ebe1d3df 100644 --- a/lib-httpx/src/test/groovy/io/seqera/http/HxAuthTest.groovy +++ b/lib-httpx/src/test/groovy/io/seqera/http/HxAuthTest.groovy @@ -51,9 +51,16 @@ class HxAuthTest extends Specification { def auth3 = HxAuth.of('different.jwt.token', 'refresh1') expect: - auth1.key() == auth2.key() // same token = same key - auth1.key() != auth3.key() // different token = different key - auth1.key().length() == 64 // SHA-256 hex = 64 chars + HxAuth.key(auth1) == HxAuth.key(auth2) // same token = same key + HxAuth.key(auth1) != HxAuth.key(auth3) // different token = different key + HxAuth.key(auth1).length() == 64 // SHA-256 hex = 64 chars + } + + def 'should return default key for null auth'() { + expect: + HxAuth.keyOrDefault(null, 'default') == 'default' + HxAuth.keyOrDefault(HxAuth.of('token'), 'default') != 'default' + HxAuth.keyOrDefault(null, 'custom') == 'custom' } def 'should implement equals and hashCode correctly'() { diff --git a/lib-httpx/src/test/groovy/io/seqera/http/HxMapTokenStoreTest.groovy b/lib-httpx/src/test/groovy/io/seqera/http/HxMapTokenStoreTest.groovy index 34b8b458..ca078c70 100644 --- a/lib-httpx/src/test/groovy/io/seqera/http/HxMapTokenStoreTest.groovy +++ b/lib-httpx/src/test/groovy/io/seqera/http/HxMapTokenStoreTest.groovy @@ -17,9 +17,6 @@ package io.seqera.http -import java.util.concurrent.CountDownLatch -import java.util.concurrent.Executors - import spock.lang.Specification /** @@ -56,4 +53,5 @@ class HxMapTokenStoreTest extends Specification { store.get('key1') == null store.remove('key1') == null } + } diff --git a/lib-httpx/src/test/groovy/io/seqera/http/HxTokenManagerTest.groovy b/lib-httpx/src/test/groovy/io/seqera/http/HxTokenManagerTest.groovy index 7784b81e..4982f225 100644 --- a/lib-httpx/src/test/groovy/io/seqera/http/HxTokenManagerTest.groovy +++ b/lib-httpx/src/test/groovy/io/seqera/http/HxTokenManagerTest.groovy @@ -350,7 +350,7 @@ class HxTokenManagerTest extends Specification { tokenManager.getAuth(auth) then: - customStore.get(auth.key()) == auth + customStore.get(HxAuth.key(auth)) == auth tokenManager.getTokenStore() == customStore } } From 1651e4f09d0bd9a84d8068827b682e4e607c4f98 Mon Sep 17 00:00:00 2001 From: Paolo Di Tommaso Date: Mon, 5 Jan 2026 19:36:36 +0700 Subject: [PATCH 3/9] Reduce duplication in HxTokenManager by delegating to HxAuth methods MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Refactored no-arg methods to delegate to their HxAuth counterparts: - addAuthHeader() - delegates with basic auth fallback - canRefreshToken() - delegates to canRefreshToken(HxAuth) - refreshToken() - delegates to refreshToken(HxAuth) - doRefreshToken() - delegates to doRefreshToken(HxAuth) - refreshTokenAsync() - delegates to refreshTokenAsync(HxAuth) - getOrRefreshTokenAsync() - delegates to getOrRefreshTokenAsync(HxAuth) 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude Opus 4.5 --- .../java/io/seqera/http/HxTokenManager.java | 52 ++++--------------- 1 file changed, 11 insertions(+), 41 deletions(-) diff --git a/lib-httpx/src/main/java/io/seqera/http/HxTokenManager.java b/lib-httpx/src/main/java/io/seqera/http/HxTokenManager.java index 81e15768..f71e3f9f 100644 --- a/lib-httpx/src/main/java/io/seqera/http/HxTokenManager.java +++ b/lib-httpx/src/main/java/io/seqera/http/HxTokenManager.java @@ -215,25 +215,17 @@ private void validateTokenRefreshConfig() { */ public HttpRequest addAuthHeader(HttpRequest originalRequest) { // Priority 1: JWT Bearer token - final String jwtToken = getCurrentJwtToken(); - if (jwtToken != null && !jwtToken.isEmpty()) { - final String headerValue = jwtToken.startsWith(BEARER_PREFIX) ? jwtToken : BEARER_PREFIX + jwtToken; - return HttpRequest.newBuilder(originalRequest, (name, value) -> true) - .header("Authorization", headerValue) - .build(); - } + HttpRequest result = addAuthHeader(originalRequest, getDefaultAuth()); - // Priority 2: Basic authentication - if (config.getBasicAuthToken() != null && !config.getBasicAuthToken().isEmpty()) { + // Priority 2: Basic authentication fallback (if no JWT auth was applied) + if (result == originalRequest && hasBasicAuth()) { final String encodedCredentials = Base64.getEncoder().encodeToString(config.getBasicAuthToken().getBytes()); - final String headerValue = "Basic " + encodedCredentials; return HttpRequest.newBuilder(originalRequest, (name, value) -> true) - .header("Authorization", headerValue) + .header("Authorization", "Basic " + encodedCredentials) .build(); } - // No authentication configured - return originalRequest; + return result; } /** @@ -242,8 +234,7 @@ public HttpRequest addAuthHeader(HttpRequest originalRequest) { * @return true if both refresh token and refresh URL are configured, false otherwise */ public boolean canRefreshToken() { - final HxAuth auth = tokenStore.get(DEFAULT_TOKEN); - return auth != null && auth.refreshToken() != null && config.getRefreshTokenUrl() != null; + return canRefreshToken(getDefaultAuth()); } /** @@ -263,13 +254,7 @@ public boolean canRefreshToken() { * @return true if token refresh was successful, false otherwise */ public boolean refreshToken() { - if (!canRefreshToken()) { - final HxAuth auth = tokenStore.get(DEFAULT_TOKEN); - log.warn("Cannot refresh token: refreshToken={} refreshTokenUrl={}", - (auth != null && auth.refreshToken() != null), config.getRefreshTokenUrl()); - return false; - } - return doRefreshToken(); + return refreshToken(getDefaultAuth()) != null; } /** @@ -280,12 +265,7 @@ public boolean refreshToken() { * @return a CompletableFuture that completes with true if refresh was successful, false otherwise */ public CompletableFuture getOrRefreshTokenAsync() { - final HxAuth auth = tokenStore.get(DEFAULT_TOKEN); - if (auth == null) { - log.warn("Cannot refresh token: no default auth configured"); - return CompletableFuture.completedFuture(false); - } - return getOrRefreshTokenAsync(auth).thenApply(result -> result != null); + return getOrRefreshTokenAsync(getDefaultAuth()).thenApply(result -> result != null); } /** @@ -337,13 +317,7 @@ public CompletableFuture getOrRefreshTokenAsync(HxAuth auth) { * @return a CompletableFuture that completes with true if refresh was successful, false otherwise */ public CompletableFuture refreshTokenAsync() { - if (!canRefreshToken()) { - final HxAuth auth = tokenStore.get(DEFAULT_TOKEN); - log.warn("Cannot refresh token asynchronously: refreshToken={} refreshTokenUrl={}", - (auth != null && auth.refreshToken() != null), config.getRefreshTokenUrl()); - return CompletableFuture.completedFuture(false); - } - return CompletableFuture.supplyAsync(this::doRefreshToken); + return refreshTokenAsync(getDefaultAuth()).thenApply(result -> result != null); } /** @@ -354,12 +328,8 @@ public CompletableFuture refreshTokenAsync() { * @return true if the token refresh was successful, false otherwise */ protected boolean doRefreshToken() { - final HxAuth auth = tokenStore.get(DEFAULT_TOKEN); - if (auth == null) { - log.warn("No auth available for default key"); - return false; - } - return doRefreshTokenInternal(DEFAULT_TOKEN, auth) != null; + final HxAuth auth = getDefaultAuth(); + return auth != null && doRefreshToken(auth) != null; } /** From 85c9b8aed5e1557237e55ccd049016eaffa9798e Mon Sep 17 00:00:00 2001 From: Paolo Di Tommaso Date: Fri, 20 Feb 2026 21:57:39 +0100 Subject: [PATCH 4/9] Fix thread safety, token validation, and security issues in lib-httpx multi-token support - Add synchronized to updateTokens to prevent read-modify-write race - Add putIfAbsent to HxTokenStore interface for atomic check-and-set in getAuth - Create per-refresh CookieManager/HttpClient to prevent cross-user cookie leaking - Mask tokens in HxAuth.toString() to prevent credential leaking in logs - Reject null access token in HxAuth constructor - Update stale Javadoc referencing removed ReentrantReadWriteLock - Fix README putIfAbsent example to match actual interface signature - Reduce updateTokens visibility to package-private Co-Authored-By: Claude Opus 4.6 --- lib-httpx/README.md | 9 +-- .../src/main/java/io/seqera/http/HxAuth.java | 15 ++++- .../java/io/seqera/http/HxMapTokenStore.java | 6 ++ .../java/io/seqera/http/HxTokenManager.java | 62 ++++++++----------- .../java/io/seqera/http/HxTokenStore.java | 16 +++++ .../groovy/io/seqera/http/HxAuthTest.groovy | 26 ++++++++ .../groovy/io/seqera/http/HxClientTest.groovy | 6 +- .../io/seqera/http/HxMapTokenStoreTest.groovy | 28 +++++++++ .../io/seqera/http/HxTokenManagerTest.groovy | 55 ++++------------ 9 files changed, 133 insertions(+), 90 deletions(-) diff --git a/lib-httpx/README.md b/lib-httpx/README.md index a20f6bf9..9e2a8cdf 100644 --- a/lib-httpx/README.md +++ b/lib-httpx/README.md @@ -188,12 +188,13 @@ public class RedisTokenStore implements HxTokenStore { public void put(String key, HxAuth auth) { /* Redis SET */ } @Override - public HxAuth remove(String key) { /* Redis DEL */ } + public HxAuth putIfAbsent(String key, HxAuth auth) { + // Use Redis SETNX for atomic check-and-set + // Return existing value if present, otherwise store and return auth + } @Override - public HxAuth putIfAbsent(HxAuth auth) { - // Use Redis SETNX for atomic operation - } + public HxAuth remove(String key) { /* Redis DEL */ } } // Use custom store diff --git a/lib-httpx/src/main/java/io/seqera/http/HxAuth.java b/lib-httpx/src/main/java/io/seqera/http/HxAuth.java index 895739e5..324b040a 100644 --- a/lib-httpx/src/main/java/io/seqera/http/HxAuth.java +++ b/lib-httpx/src/main/java/io/seqera/http/HxAuth.java @@ -41,6 +41,9 @@ public final class HxAuth { private final String refreshToken; private HxAuth(String accessToken, String refreshToken) { + if (accessToken == null) { + throw new IllegalArgumentException("accessToken cannot be null"); + } this.accessToken = accessToken; this.refreshToken = refreshToken; } @@ -135,8 +138,14 @@ public int hashCode() { @Override public String toString() { return "HxAuth[" + - "accessToken=" + accessToken + - ", refreshToken=" + refreshToken + + "accessToken=" + mask(accessToken) + + ", refreshToken=" + mask(refreshToken) + ']'; } -} \ No newline at end of file + + private static String mask(String value) { + if (value == null) return "null"; + if (value.length() <= 8) return "***"; + return value.substring(0, 4) + "***" + value.substring(value.length() - 4); + } +} diff --git a/lib-httpx/src/main/java/io/seqera/http/HxMapTokenStore.java b/lib-httpx/src/main/java/io/seqera/http/HxMapTokenStore.java index 099490fd..8240b036 100644 --- a/lib-httpx/src/main/java/io/seqera/http/HxMapTokenStore.java +++ b/lib-httpx/src/main/java/io/seqera/http/HxMapTokenStore.java @@ -43,6 +43,12 @@ public void put(String key, HxAuth auth) { store.put(key, auth); } + @Override + public HxAuth putIfAbsent(String key, HxAuth auth) { + final HxAuth existing = store.putIfAbsent(key, auth); + return existing != null ? existing : auth; + } + @Override public HxAuth remove(String key) { return store.remove(key); diff --git a/lib-httpx/src/main/java/io/seqera/http/HxTokenManager.java b/lib-httpx/src/main/java/io/seqera/http/HxTokenManager.java index f71e3f9f..6d09bf5f 100644 --- a/lib-httpx/src/main/java/io/seqera/http/HxTokenManager.java +++ b/lib-httpx/src/main/java/io/seqera/http/HxTokenManager.java @@ -63,11 +63,11 @@ * * *

Thread Safety:
- * All public methods are thread-safe using a {@link ReentrantReadWriteLock}: + * All public methods are thread-safe: *

    - *
  • Token reads use shared read locks for high concurrency
  • - *
  • Token updates use exclusive write locks for consistency
  • - *
  • Token refresh operations are synchronized to prevent duplicate refreshes
  • + *
  • Token storage is managed through {@link HxTokenStore} (default: {@link HxMapTokenStore} backed by ConcurrentHashMap)
  • + *
  • Token updates use {@code synchronized} to ensure atomic read-modify-write
  • + *
  • Concurrent token refresh operations are coordinated per-key using {@link ConcurrentHashMap#computeIfAbsent}
  • *
* *

Usage Example: @@ -102,8 +102,6 @@ class HxTokenManager { private static final String DEFAULT_TOKEN = "default-token"; private final HxConfig config; - private final HttpClient refreshHttpClient; - private final CookieManager cookieManager; private final HxTokenStore tokenStore; // Coordination for concurrent token refresh operations per key @@ -126,17 +124,6 @@ public HxTokenManager(HxConfig config, HxTokenStore tokenStore) { // Validate JWT token refresh configuration validateTokenRefreshConfig(); - - // Create CookieManager with custom policy if provided - this.cookieManager = (config.getRefreshCookiePolicy() != null) - ? new CookieManager(null, config.getRefreshCookiePolicy()) - : new CookieManager(); - this.refreshHttpClient = HttpClient.newBuilder() - .version(HttpClient.Version.HTTP_1_1) - .followRedirects(HttpClient.Redirect.NORMAL) - .cookieHandler(cookieManager) - .connectTimeout(config.getTokenRefreshTimeout()) - .build(); } /** @@ -333,16 +320,14 @@ protected boolean doRefreshToken() { } /** - * Extracts a cookie from the cookie store by name (same approach as TowerXAuth). - * - *

This method searches through the cookie store for a cookie with the - * specified name and returns the HttpCookie object if found. - * + * Extracts a cookie from the given cookie manager by name. + * + * @param cookies the cookie manager to search * @param cookieName the name of the cookie to extract (e.g., "JWT", "JWT_REFRESH_TOKEN") * @return the HttpCookie if found, null otherwise */ - protected HttpCookie getCookie(String cookieName) { - for (HttpCookie cookie : cookieManager.getCookieStore().getCookies()) { + protected HttpCookie getCookie(CookieManager cookies, String cookieName) { + for (HttpCookie cookie : cookies.getCookieStore().getCookies()) { if (cookieName.equals(cookie.getName())) { return cookie; } @@ -429,7 +414,7 @@ public boolean hasBasicAuth() { * @param jwtToken the new JWT token to set, may be null * @param refreshToken the new refresh token to set, may be null */ - public void updateTokens(String jwtToken, String refreshToken) { + synchronized void updateTokens(String jwtToken, String refreshToken) { final HxAuth currentAuth = tokenStore.get(DEFAULT_TOKEN); String newToken = (currentAuth != null) ? currentAuth.accessToken() : null; String newRefresh = (currentAuth != null) ? currentAuth.refreshToken() : null; @@ -466,12 +451,7 @@ public HxAuth getAuth(HxAuth auth) { return null; } final String key = HxAuth.key(auth); - HxAuth stored = tokenStore.get(key); - if (stored == null) { - tokenStore.put(key, auth); - return auth; - } - return stored; + return tokenStore.putIfAbsent(key, auth); } /** @@ -570,6 +550,17 @@ protected HxAuth doRefreshTokenInternal(String key, HxAuth auth) { final var refreshUrl = URI.create(config.getRefreshTokenUrl()); log.trace("Attempting to refresh JWT token for key {} at URL: {}", key, refreshUrl); + // Create per-refresh CookieManager and HttpClient to avoid cross-user cookie leaking + final CookieManager cookieManager = (config.getRefreshCookiePolicy() != null) + ? new CookieManager(null, config.getRefreshCookiePolicy()) + : new CookieManager(); + final HttpClient refreshHttpClient = HttpClient.newBuilder() + .version(HttpClient.Version.HTTP_1_1) + .followRedirects(HttpClient.Redirect.NORMAL) + .cookieHandler(cookieManager) + .connectTimeout(config.getTokenRefreshTimeout()) + .build(); + final String body = "grant_type=refresh_token&refresh_token=" + URLEncoder.encode(auth.refreshToken(), StandardCharsets.UTF_8); @@ -584,7 +575,7 @@ protected HxAuth doRefreshTokenInternal(String key, HxAuth auth) { log.trace("Token refresh response for key {}: [{}]", key, response.statusCode()); if (response.statusCode() == 200) { - final HxAuth newAuth = extractAuthFromResponse(response, auth); + final HxAuth newAuth = extractAuthFromResponse(response, cookieManager, auth); if (newAuth != null) { log.debug("JWT token refresh completed for key {}", key); tokenStore.put(key, newAuth); @@ -605,14 +596,15 @@ protected HxAuth doRefreshTokenInternal(String key, HxAuth auth) { * Extracts tokens from the HTTP response and creates a new {@link HxAuth}. * * @param response the HTTP response from the token refresh request + * @param cookieManager the cookie manager used for the refresh request * @param originalAuth the original authentication data (used to preserve refresh token if not returned) * @return a new {@link HxAuth} with updated tokens, or null if extraction failed */ - protected HxAuth extractAuthFromResponse(HttpResponse response, HxAuth originalAuth) { + protected HxAuth extractAuthFromResponse(HttpResponse response, CookieManager cookieManager, HxAuth originalAuth) { try { // First try to extract tokens from cookie store - final HttpCookie authCookie = getCookie("JWT"); - final HttpCookie refreshCookie = getCookie("JWT_REFRESH_TOKEN"); + final HttpCookie authCookie = getCookie(cookieManager, "JWT"); + final HttpCookie refreshCookie = getCookie(cookieManager, "JWT_REFRESH_TOKEN"); if (authCookie != null && authCookie.getValue() != null) { log.trace("Successfully extracted JWT token from cookies"); diff --git a/lib-httpx/src/main/java/io/seqera/http/HxTokenStore.java b/lib-httpx/src/main/java/io/seqera/http/HxTokenStore.java index 437cf772..ebd26a71 100644 --- a/lib-httpx/src/main/java/io/seqera/http/HxTokenStore.java +++ b/lib-httpx/src/main/java/io/seqera/http/HxTokenStore.java @@ -47,6 +47,22 @@ public interface HxTokenStore { */ void put(String key, HxAuth auth); + /** + * Stores the authentication data for the given key if no value is already associated with it. + * + *

This method provides atomic check-and-set semantics. If the key already has a value, + * the existing value is returned and no update is performed. If the key has no value, + * the provided auth is stored and returned. + * + *

Implementations should ensure this operation is atomic to prevent race conditions + * in concurrent environments. + * + * @param key the unique key identifying the token pair + * @param auth the {@link HxAuth} to store if no value exists for the key + * @return the existing {@link HxAuth} if present, otherwise the newly stored auth + */ + HxAuth putIfAbsent(String key, HxAuth auth); + /** * Removes the authentication data for the given key. * diff --git a/lib-httpx/src/test/groovy/io/seqera/http/HxAuthTest.groovy b/lib-httpx/src/test/groovy/io/seqera/http/HxAuthTest.groovy index ebe1d3df..0759fc63 100644 --- a/lib-httpx/src/test/groovy/io/seqera/http/HxAuthTest.groovy +++ b/lib-httpx/src/test/groovy/io/seqera/http/HxAuthTest.groovy @@ -63,6 +63,32 @@ class HxAuthTest extends Specification { HxAuth.keyOrDefault(null, 'custom') == 'custom' } + def 'should reject null access token'() { + when: + HxAuth.of(null) + + then: + thrown(IllegalArgumentException) + } + + def 'should reject null access token with refresh'() { + when: + HxAuth.of(null, 'refresh') + + then: + thrown(IllegalArgumentException) + } + + def 'should mask tokens in toString'() { + when: + def auth = HxAuth.of('eyJhbGciOiJIUzI1NiJ9.payload.signature', 'my-refresh-token-value') + + then: + !auth.toString().contains('eyJhbGciOiJIUzI1NiJ9.payload.signature') + !auth.toString().contains('my-refresh-token-value') + auth.toString().startsWith('HxAuth[') + } + def 'should implement equals and hashCode correctly'() { expect: HxAuth.of(token1, refresh1) == HxAuth.of(token2, refresh2) == expected diff --git a/lib-httpx/src/test/groovy/io/seqera/http/HxClientTest.groovy b/lib-httpx/src/test/groovy/io/seqera/http/HxClientTest.groovy index 808dd8d9..5ae3013d 100644 --- a/lib-httpx/src/test/groovy/io/seqera/http/HxClientTest.groovy +++ b/lib-httpx/src/test/groovy/io/seqera/http/HxClientTest.groovy @@ -349,22 +349,20 @@ class HxClientTest extends Specification { client.config.jwtToken == 'test-token' client.httpClient != null client.tokenManager != null - client.tokenManager.cookieManager != null } - + def 'should handle null refreshCookiePolicy via builder'() { when: def client = HxClient.newBuilder() .refreshCookiePolicy(null) .bearerToken('test-token') .build() - + then: client.config.refreshCookiePolicy == null client.config.jwtToken == 'test-token' client.httpClient != null client.tokenManager != null - client.tokenManager.cookieManager != null } def 'should configure different cookie policies via builder'() { diff --git a/lib-httpx/src/test/groovy/io/seqera/http/HxMapTokenStoreTest.groovy b/lib-httpx/src/test/groovy/io/seqera/http/HxMapTokenStoreTest.groovy index ca078c70..8be83038 100644 --- a/lib-httpx/src/test/groovy/io/seqera/http/HxMapTokenStoreTest.groovy +++ b/lib-httpx/src/test/groovy/io/seqera/http/HxMapTokenStoreTest.groovy @@ -54,4 +54,32 @@ class HxMapTokenStoreTest extends Specification { store.remove('key1') == null } + def 'putIfAbsent should store and return auth when key is absent'() { + given: + def store = new HxMapTokenStore() + def auth = HxAuth.of('my.jwt.token', 'refresh') + + when: + def result = store.putIfAbsent('key1', auth) + + then: + result == auth + store.get('key1') == auth + } + + def 'putIfAbsent should return existing auth when key is present'() { + given: + def store = new HxMapTokenStore() + def existing = HxAuth.of('existing.jwt.token', 'refresh1') + def newAuth = HxAuth.of('new.jwt.token', 'refresh2') + store.put('key1', existing) + + when: + def result = store.putIfAbsent('key1', newAuth) + + then: + result == existing + store.get('key1') == existing + } + } diff --git a/lib-httpx/src/test/groovy/io/seqera/http/HxTokenManagerTest.groovy b/lib-httpx/src/test/groovy/io/seqera/http/HxTokenManagerTest.groovy index 4982f225..12e5e7b0 100644 --- a/lib-httpx/src/test/groovy/io/seqera/http/HxTokenManagerTest.groovy +++ b/lib-httpx/src/test/groovy/io/seqera/http/HxTokenManagerTest.groovy @@ -17,7 +17,6 @@ package io.seqera.http -import java.net.CookieManager import java.net.CookiePolicy import java.net.http.HttpRequest @@ -225,60 +224,28 @@ class HxTokenManagerTest extends Specification { !noJwtManager.canRefreshToken() } - def 'should use custom cookie policy when provided'() { - given: + def 'should accept custom cookie policy configuration'() { + when: def config = HxConfig.newBuilder() .refreshCookiePolicy(CookiePolicy.ACCEPT_ALL) .build() - - when: def tokenManager = new HxTokenManager(config) - + then: - tokenManager.cookieManager != null - tokenManager.cookieManager instanceof CookieManager - // We can't directly access the policy, but we can verify the CookieManager was created - // This verifies that the construction succeeded with the custom policy + // Cookie managers are now created per-refresh operation; + // this verifies the configuration is accepted without errors noExceptionThrown() + tokenManager != null } - - def 'should use default cookie policy when none provided'() { - given: - def config = HxConfig.newBuilder().build() - + + def 'should accept default cookie policy configuration'() { when: + def config = HxConfig.newBuilder().build() def tokenManager = new HxTokenManager(config) - + then: - tokenManager.cookieManager != null - tokenManager.cookieManager instanceof CookieManager - // This verifies that the default CookieManager construction works noExceptionThrown() - } - - def 'should create different cookie managers for different policies'() { - given: - def configAcceptAll = HxConfig.newBuilder() - .refreshCookiePolicy(CookiePolicy.ACCEPT_ALL) - .build() - def configAcceptNone = HxConfig.newBuilder() - .refreshCookiePolicy(CookiePolicy.ACCEPT_NONE) - .build() - def configDefault = HxConfig.newBuilder().build() - - when: - def tokenManager1 = new HxTokenManager(configAcceptAll) - def tokenManager2 = new HxTokenManager(configAcceptNone) - def tokenManager3 = new HxTokenManager(configDefault) - - then: - tokenManager1.cookieManager != null - tokenManager2.cookieManager != null - tokenManager3.cookieManager != null - // Each should have their own distinct CookieManager instance - tokenManager1.cookieManager != tokenManager2.cookieManager - tokenManager2.cookieManager != tokenManager3.cookieManager - tokenManager1.cookieManager != tokenManager3.cookieManager + tokenManager != null } // --- Multi-token support tests --- From 0e1f86c268059f664b73846b0d1fbba3236eaeae Mon Sep 17 00:00:00 2001 From: Paolo Di Tommaso Date: Fri, 20 Feb 2026 22:31:33 +0100 Subject: [PATCH 5/9] Extract auth helpers in HxClient to reduce null-branching duplication Add private applyAuthHeader, canRefreshToken, and refreshToken helpers that accept nullable HxAuth and delegate to the appropriate tokenManager method, simplifying sendWithRetry and sendWithRetryAsync. Co-Authored-By: Claude Opus 4.6 --- .../main/java/io/seqera/http/HxClient.java | 73 ++++++++----------- 1 file changed, 29 insertions(+), 44 deletions(-) diff --git a/lib-httpx/src/main/java/io/seqera/http/HxClient.java b/lib-httpx/src/main/java/io/seqera/http/HxClient.java index ee9bffe0..edaf1eb7 100644 --- a/lib-httpx/src/main/java/io/seqera/http/HxClient.java +++ b/lib-httpx/src/main/java/io/seqera/http/HxClient.java @@ -417,11 +417,6 @@ public CompletableFuture> sendAsync(HttpRequest request, * Internal method that implements the retry logic for synchronous requests. * *

Delegates to {@link #sendWithRetry(HttpRequest, HxAuth, HttpResponse.BodyHandler)} with default auth. - * - * @param the response body type - * @param request the HTTP request to send - * @param responseBodyHandler the response body handler - * @return the HTTP response after successful execution or retry exhaustion */ protected HttpResponse sendWithRetry(HttpRequest request, HttpResponse.BodyHandler responseBodyHandler) { return sendWithRetry(request, tokenManager.getDefaultAuth(), responseBodyHandler); @@ -431,12 +426,6 @@ protected HttpResponse sendWithRetry(HttpRequest request, HttpResponse.Bo * Internal method that implements the retry logic for asynchronous requests. * *

Delegates to {@link #sendWithRetryAsync(HttpRequest, HxAuth, HttpResponse.BodyHandler, Executor)} with default auth. - * - * @param the response body type - * @param request the HTTP request to send - * @param responseBodyHandler the response body handler - * @param executor optional executor for async operations, may be null - * @return a CompletableFuture that completes with the HTTP response */ protected CompletableFuture> sendWithRetryAsync( HttpRequest request, @@ -445,6 +434,27 @@ protected CompletableFuture> sendWithRetryAsync( return sendWithRetryAsync(request, tokenManager.getDefaultAuth(), responseBodyHandler, executor); } + // -- Auth helpers that accept nullable HxAuth and delegate to the right tokenManager method -- + + private HttpRequest applyAuthHeader(HttpRequest request, HxAuth auth) { + return (auth != null) + ? tokenManager.addAuthHeader(request, auth) + : tokenManager.addAuthHeader(request); + } + + private boolean canRefreshToken(HxAuth auth) { + return (auth != null) + ? tokenManager.canRefreshToken(auth) + : tokenManager.canRefreshToken(); + } + + private boolean refreshToken(HxAuth auth) throws Exception { + if (auth != null) { + return tokenManager.getOrRefreshTokenAsync(auth).get() != null; + } + return tokenManager.getOrRefreshTokenAsync().get(); + } + /** * Internal method that implements the retry logic for synchronous requests. * @@ -456,9 +466,6 @@ protected CompletableFuture> sendWithRetryAsync( *

  • Re-executing requests with refreshed tokens
  • * * - *

    If auth is null, uses the default token from configuration. Otherwise uses - * the specific {@link HxAuth} for multi-user authentication scenarios. - * * @param the response body type * @param request the HTTP request to send * @param auth the authentication data for this request, or null to use default token @@ -478,9 +485,7 @@ protected HttpResponse sendWithRetry(HttpRequest request, HxAuth auth, Ht }); return retry.apply(() -> { - final HttpRequest actualRequest = (auth != null) - ? tokenManager.addAuthHeader(request, auth) - : tokenManager.addAuthHeader(request); + final HttpRequest actualRequest = applyAuthHeader(request, auth); final HttpResponse response = httpClient.send(actualRequest, responseBodyHandler); if (response.statusCode() != 401 || tokenRefreshed[0]) { @@ -488,21 +493,14 @@ protected HttpResponse sendWithRetry(HttpRequest request, HxAuth auth, Ht } // Try JWT token refresh - final boolean canRefresh = (auth != null) ? tokenManager.canRefreshToken(auth) : tokenManager.canRefreshToken(); - if (canRefresh) { + if (canRefreshToken(auth)) { final String debugKey = HxAuth.keyOrDefault(auth, "-"); log.debug("Received 401 status for auth key {}, attempting token refresh", debugKey); try { - final boolean refreshed = (auth != null) - ? tokenManager.getOrRefreshTokenAsync(auth).get() != null - : tokenManager.getOrRefreshTokenAsync().get(); - if (refreshed) { + if (refreshToken(auth)) { tokenRefreshed[0] = true; - final HttpRequest refreshedRequest = (auth != null) - ? tokenManager.addAuthHeader(request, auth) - : tokenManager.addAuthHeader(request); closeResponse(response); - return httpClient.send(refreshedRequest, responseBodyHandler); + return httpClient.send(applyAuthHeader(request, auth), responseBodyHandler); } } catch (Exception e) { log.warn("Token refresh failed for auth key {}: {}", debugKey, e.getMessage()); @@ -534,9 +532,6 @@ protected HttpResponse sendWithRetry(HttpRequest request, HxAuth auth, Ht *

  • Re-executing requests with refreshed tokens
  • * * - *

    If auth is null, uses the default token from configuration. Otherwise uses - * the specific {@link HxAuth} for multi-user authentication scenarios. - * * @param the response body type * @param request the HTTP request to send * @param auth the authentication data for this request, or null to use default token @@ -562,10 +557,7 @@ protected CompletableFuture> sendWithRetryAsync( }); return retry.applyAsync(() -> { - final HttpRequest actualRequest = (auth != null) - ? tokenManager.addAuthHeader(request, auth) - : tokenManager.addAuthHeader(request); - + final HttpRequest actualRequest = applyAuthHeader(request, auth); try { final HttpResponse response = httpClient.sendAsync(actualRequest, responseBodyHandler).get(); @@ -574,21 +566,14 @@ protected CompletableFuture> sendWithRetryAsync( } // Try JWT token refresh - final boolean canRefresh = (auth != null) ? tokenManager.canRefreshToken(auth) : tokenManager.canRefreshToken(); - if (canRefresh) { + if (canRefreshToken(auth)) { final String debugKey = HxAuth.keyOrDefault(auth, "-"); log.debug("Received 401 status in async call for auth key {}, attempting token refresh", debugKey); try { - final boolean refreshed = (auth != null) - ? tokenManager.getOrRefreshTokenAsync(auth).get() != null - : tokenManager.getOrRefreshTokenAsync().get(); - if (refreshed) { + if (refreshToken(auth)) { tokenRefreshed[0] = true; - final HttpRequest refreshedRequest = (auth != null) - ? tokenManager.addAuthHeader(request, auth) - : tokenManager.addAuthHeader(request); closeResponse(response); - return httpClient.sendAsync(refreshedRequest, responseBodyHandler).get(); + return httpClient.sendAsync(applyAuthHeader(request, auth), responseBodyHandler).get(); } } catch (Exception e) { log.warn("Async token refresh failed for auth key {}: {}", debugKey, e.getMessage()); From 43ee2badccd690654a1bf56c8b86f8ad98202a9f Mon Sep 17 00:00:00 2001 From: Paolo Di Tommaso Date: Sat, 21 Feb 2026 00:20:55 +0100 Subject: [PATCH 6/9] Refactor HxAuth to interface with immutable DefaultHxAuth record - Extract HxAuth from final class to interface with stable id() contract - Add DefaultHxAuth as immutable record with UUID-based identity preserved across withToken/withRefresh - Add per-auth refreshUrl with fallback to global config - Remove static factory methods and keyOrDefault helper - Replace SHA-256 key derivation with stable UUID identity - Update README with new interface design and usage examples Co-Authored-By: Claude Opus 4.6 --- lib-httpx/README.md | 147 ++++++++++-------- .../java/io/seqera/http/DefaultHxAuth.java | 75 +++++++++ .../src/main/java/io/seqera/http/HxAuth.java | 133 ++++------------ .../main/java/io/seqera/http/HxClient.java | 4 +- .../java/io/seqera/http/HxTokenManager.java | 100 +++++++----- .../groovy/io/seqera/http/HxAuthTest.groovy | 58 +++---- .../io/seqera/http/HxMapTokenStoreTest.groovy | 10 +- .../io/seqera/http/HxTokenManagerTest.groovy | 20 ++- 8 files changed, 296 insertions(+), 251 deletions(-) create mode 100644 lib-httpx/src/main/java/io/seqera/http/DefaultHxAuth.java diff --git a/lib-httpx/README.md b/lib-httpx/README.md index 9e2a8cdf..3c4dae95 100644 --- a/lib-httpx/README.md +++ b/lib-httpx/README.md @@ -21,7 +21,7 @@ dependencies { - **Retry Logic**: Automatic retry for configurable HTTP status codes (default: 429, 500, 502, 503, 504) - **Authentication Support**: Built-in support for JWT Bearer tokens and HTTP Basic authentication - **JWT Token Refresh**: Automatic JWT token refresh when receiving 401 Unauthorized responses with configurable cookie policies -- **Multi-Session Auth**: Support for multiple concurrent authentication sessions with per-request token management +- **Multi-Session Auth**: Support for multiple concurrent authentication sessions via the `HxAuth` interface - **Custom Token Storage**: Pluggable token store interface for distributed deployments (Redis, database, etc.) - **WWW-Authenticate Support**: Automatic handling of HTTP authentication challenges (Basic and Bearer schemes) - **Anonymous Authentication**: Fallback to anonymous authentication when credentials aren't provided @@ -63,13 +63,12 @@ HxClient client = HxClient.newBuilder() .bearerToken("your-jwt-token") .refreshToken("your-refresh-token") .refreshTokenUrl("https://api.example.com/oauth/token") - .refreshCookiePolicy(CookiePolicy.ACCEPT_ALL) // New: Configure cookie handling for token refresh + .refreshCookiePolicy(CookiePolicy.ACCEPT_ALL) .build(); -// Using HxConfig directly (deprecated methods shown for compatibility) +// Using HxConfig directly HxConfig config = HxConfig.newBuilder() - .bearerToken("your-jwt-token") // Recommended - // .withBearerToken("your-jwt-token") // Deprecated but still works + .bearerToken("your-jwt-token") .refreshToken("your-refresh-token") .refreshTokenUrl("https://api.example.com/oauth/token") .build(); @@ -99,7 +98,7 @@ HxClient client = HxClient.newBuilder().config(config).build(); ``` **Authentication Constraints:** -- Cannot configure both JWT and Basic authentication simultaneously +- Cannot configure both JWT and Basic authentication simultaneously - Choose one authentication method - the configuration builder will reject conflicting setups - Use JWT tokens for modern APIs, Basic auth for legacy systems @@ -120,10 +119,8 @@ HxConfig config = HxConfig.newBuilder() .wwwAuthentication(true) .wwwAuthenticationCallback((scheme, realm) -> { if (scheme == AuthenticationScheme.BASIC) { - // Return base64-encoded credentials for Basic auth return Base64.getEncoder().encodeToString("user:pass".getBytes()); } else if (scheme == AuthenticationScheme.BEARER) { - // Return bearer token return "your-bearer-token"; } return null; // Fall back to anonymous auth @@ -143,17 +140,32 @@ HxClient client = HxClient.newBuilder().config(config).build(); ### Multi-Session Authentication -For applications managing multiple users or authentication contexts, use `HxAuth` to handle per-request authentication with automatic token refresh: +For applications managing multiple users or authentication contexts, use the `HxAuth` interface for per-request authentication with automatic token refresh. + +#### The `HxAuth` Interface + +`HxAuth` represents an authentication session. The `id()` uniquely identifies the session and **must remain the same for the entire lifecycle** of the auth — even as the access token and refresh token change over time due to token refresh operations. This allows the client to track and coordinate refreshes for the same logical session. + +| Method | Description | +|--------|-------------| +| `id()` | Stable identifier, constant for the auth lifecycle | +| `accessToken()` | The current JWT access token | +| `refreshToken()` | The refresh token (nullable) | +| `refreshUrl()` | Per-auth refresh URL override (nullable, falls back to global config) | +| `withToken(token)` | Returns an `HxAuth` with the updated access token (same `id`) | +| `withRefresh(refresh)` | Returns an `HxAuth` with the updated refresh token (same `id`) | + +The default implementation `DefaultHxAuth` is an immutable record that auto-generates a UUID as `id()`. The `withToken` and `withRefresh` methods return new instances preserving the same `id`. + +#### Basic Multi-Session Usage ```java -// Create a shared client with refresh URL configured -HxClient client = HxClient.newBuilder() - .refreshTokenUrl("https://api.example.com/oauth/token") - .build(); +// Create a shared client +HxClient client = HxClient.newBuilder().build(); -// Create auth for each user session -HxAuth user1Auth = HxAuth.of("user1.jwt.token", "user1-refresh-token"); -HxAuth user2Auth = HxAuth.of("user2.jwt.token", "user2-refresh-token"); +// Create auth for each user session (each gets a unique id) +HxAuth user1Auth = new DefaultHxAuth("user1.jwt.token", "user1-refresh-token", "https://api.example.com/oauth/token"); +HxAuth user2Auth = new DefaultHxAuth("user2.jwt.token", "user2-refresh-token", "https://api.example.com/oauth/token"); // Make requests with per-user authentication HttpRequest request = HttpRequest.newBuilder() @@ -168,11 +180,48 @@ HttpResponse response2 = client.send(request, user2Auth, HttpResponse.Bo CompletableFuture> future = client.sendAsync(request, user1Auth, HttpResponse.BodyHandlers.ofString()); ``` -**Features:** -- Each `HxAuth` maintains its own token pair (access + refresh) -- Automatic token refresh on 401 responses, scoped to each auth session -- Thread-safe concurrent refresh coordination per auth key -- Tokens are identified by SHA-256 hash of the access token +#### Per-Auth Refresh URL + +Each `HxAuth` can carry its own `refreshUrl`, allowing different auth sessions to refresh against different endpoints. If `refreshUrl()` returns null, the global `refreshTokenUrl` from `HxConfig` is used as fallback. + +```java +// Different users refresh against different endpoints +HxAuth user1 = new DefaultHxAuth("user1.jwt.token", "user1-refresh", "https://region1.example.com/oauth/token"); +HxAuth user2 = new DefaultHxAuth("user2.jwt.token", "user2-refresh", "https://region2.example.com/oauth/token"); +``` + +#### Custom `HxAuth` Implementation + +Implement `HxAuth` to customise the identity strategy (e.g., key by user ID or tenant): + +```java +public class TenantAuth implements HxAuth { + private final String tenantId; + private final String accessToken; + private final String refreshToken; + + public TenantAuth(String tenantId, String accessToken, String refreshToken) { + this.tenantId = tenantId; + this.accessToken = accessToken; + this.refreshToken = refreshToken; + } + + @Override public String id() { return tenantId; } // stable across refreshes + @Override public String accessToken() { return accessToken; } + @Override public String refreshToken() { return refreshToken; } + @Override public String refreshUrl() { return null; } // use global config + + @Override + public HxAuth withToken(String token) { + return new TenantAuth(tenantId, token, refreshToken); + } + + @Override + public HxAuth withRefresh(String refresh) { + return new TenantAuth(tenantId, accessToken, refresh); + } +} +``` #### Custom Token Store @@ -201,7 +250,6 @@ public class RedisTokenStore implements HxTokenStore { HxTokenStore customStore = new RedisTokenStore(); HxClient client = HxClient.newBuilder() .tokenStore(customStore) - .refreshTokenUrl("https://api.example.com/oauth/token") .build(); ``` @@ -247,45 +295,15 @@ HxConfig config = HxConfig.newBuilder() HxClient client = HxClient.newBuilder().config(config).build(); ``` -### New Cookie Policy Configuration (v2.1.0+) +### Cookie Policy Configuration Configure cookie handling for JWT token refresh operations: ```java -// Configure cookie policy for token refresh operations HxClient client = HxClient.newBuilder() .bearerToken("your-jwt-token") - .refreshToken("your-refresh-token") + .refreshToken("your-refresh-token") .refreshTokenUrl("https://api.example.com/oauth/token") - .refreshCookiePolicy(CookiePolicy.ACCEPT_ALL) // Accept all cookies - // .refreshCookiePolicy(CookiePolicy.ACCEPT_NONE) // Accept no cookies - // .refreshCookiePolicy(CookiePolicy.ACCEPT_ORIGINAL_SERVER) // Accept only from original server - .build(); -``` - -## Migration Guide (v2.0.0 → v2.1.0) - -Version 2.1.0 introduces new setter methods without the `with` prefix to align with HxClient.Builder patterns. The old `with` prefixed methods are deprecated but still work: - -```java -// ❌ Deprecated (still works with warnings) -HxConfig config = HxConfig.newBuilder() - .withBearerToken("token") - .withMaxAttempts(3) - .withRefreshCookiePolicy(CookiePolicy.ACCEPT_ALL) - .build(); - -// ✅ Recommended (new in v2.1.0) -HxConfig config = HxConfig.newBuilder() - .bearerToken("token") - .maxAttempts(3) - .refreshCookiePolicy(CookiePolicy.ACCEPT_ALL) - .build(); - -// ✅ Best practice: Use HxClient.Builder directly -HxClient client = HxClient.newBuilder() - .bearerToken("token") - .maxAttempts(3) .refreshCookiePolicy(CookiePolicy.ACCEPT_ALL) .build(); ``` @@ -306,25 +324,16 @@ HxClient client = HxClient.newBuilder() | `tokenRefreshTimeout` | Timeout for token refresh requests | 30s | | `tokenStore` | Custom token store for multi-session authentication | HxMapTokenStore | | `basicAuthToken` | Token for HTTP Basic authentication (username:password format) | null | -| `refreshCookiePolicy` | Cookie policy for JWT token refresh operations (ACCEPT_ALL, ACCEPT_NONE, ACCEPT_ORIGINAL_SERVER) | null | +| `refreshCookiePolicy` | Cookie policy for JWT token refresh operations | null | | `wwwAuthentication` | Enable WWW-Authenticate challenge handling | false | | `wwwAuthenticationCallback` | Callback for providing authentication credentials | null | -## API Documentation - -All classes and methods include comprehensive Javadoc documentation covering: - -- **Class-level documentation**: Complete overview of functionality and usage patterns -- **Method documentation**: Detailed parameter descriptions, return values, and behavior -- **Usage examples**: Code samples showing common use cases -- **Thread safety notes**: Concurrency guarantees and synchronization details -- **Error handling**: Exception types and retry behavior - -### Key Classes +## Key Classes -- **`HxClient`** (Http eXtended Client): Main client class with retry, JWT, and WWW-Authenticate functionality -- **`HxConfig`**: Configuration builder with all available options including Retryable.Config integration -- **`HxAuth`**: Immutable container for JWT access token and refresh token pairs +- **`HxClient`**: Main HTTP client with retry, JWT, and WWW-Authenticate functionality +- **`HxConfig`**: Configuration builder with all available options +- **`HxAuth`**: Interface for authentication credentials with stable identity across refreshes +- **`DefaultHxAuth`**: Immutable record implementation of `HxAuth` with UUID-based identity - **`HxTokenStore`**: Interface for pluggable token storage (default: in-memory ConcurrentHashMap) - **`HxTokenManager`**: Thread-safe JWT token lifecycle management with multi-session support - **`AuthenticationChallenge`**: Represents a parsed WWW-Authenticate challenge diff --git a/lib-httpx/src/main/java/io/seqera/http/DefaultHxAuth.java b/lib-httpx/src/main/java/io/seqera/http/DefaultHxAuth.java new file mode 100644 index 00000000..8526ef93 --- /dev/null +++ b/lib-httpx/src/main/java/io/seqera/http/DefaultHxAuth.java @@ -0,0 +1,75 @@ +/* + * Copyright 2025, Seqera Labs + * + * 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. + * + */ + +package io.seqera.http; + +import java.util.UUID; + +/** + * Default immutable implementation of {@link HxAuth}. + * + *

    Stores JWT access token, refresh token, and refresh URL. + * A stable {@link #id()} is assigned at creation and preserved + * through {@link #withToken(String)} and {@link #withRefresh(String)}. + * + * @author Paolo Di Tommaso + */ +record DefaultHxAuth(String id, String accessToken, String refreshToken, String refreshUrl) implements HxAuth { + + DefaultHxAuth { + if (accessToken == null) { + throw new IllegalArgumentException("accessToken cannot be null"); + } + if (id == null) { + throw new IllegalArgumentException("id cannot be null"); + } + } + + DefaultHxAuth(String accessToken, String refreshToken, String refreshUrl) { + this(UUID.randomUUID().toString(), accessToken, refreshToken, refreshUrl); + } + + DefaultHxAuth(String accessToken, String refreshToken) { + this(accessToken, refreshToken, null); + } + + @Override + public HxAuth withToken(String token) { + return new DefaultHxAuth(id, token, refreshToken, refreshUrl); + } + + @Override + public HxAuth withRefresh(String refresh) { + return new DefaultHxAuth(id, accessToken, refresh, refreshUrl); + } + + @Override + public String toString() { + return "HxAuth[" + + "id=" + id + + ", accessToken=" + mask(accessToken) + + ", refreshToken=" + mask(refreshToken) + + ", refreshUrl=" + refreshUrl + + ']'; + } + + private static String mask(String value) { + if (value == null) return "null"; + if (value.length() <= 8) return "***"; + return value.substring(0, 4) + "***" + value.substring(value.length() - 4); + } +} diff --git a/lib-httpx/src/main/java/io/seqera/http/HxAuth.java b/lib-httpx/src/main/java/io/seqera/http/HxAuth.java index 324b040a..32e6d335 100644 --- a/lib-httpx/src/main/java/io/seqera/http/HxAuth.java +++ b/lib-httpx/src/main/java/io/seqera/http/HxAuth.java @@ -17,135 +17,68 @@ package io.seqera.http; -import java.nio.charset.StandardCharsets; -import java.security.MessageDigest; -import java.security.NoSuchAlgorithmException; -import java.util.HexFormat; -import java.util.Objects; - /** - * Immutable container for JWT authentication credentials. + * Interface for JWT authentication credentials. + * + *

    Provides access to the JWT access token, optional refresh token, and optional + * refresh URL. The {@link #id()} method returns a stable stable identifier for the token + * store that persists across token refreshes. * - *

    This class holds a JWT access token and an optional refresh token as a pair. - * The storage key can be computed using {@link #key(HxAuth)} which returns the - * SHA-256 hash of the access token. + *

    The {@link #withToken(String)} and {@link #withRefresh(String)} methods return + * an {@link HxAuth} with the updated token after a refresh operation. * - *

    Instances are created using the factory methods {@link #of(String)} or - * {@link #of(String, String)}. + *

    A default implementation is provided by {@link DefaultHxAuth}. * * @author Paolo Di Tommaso */ -public final class HxAuth { - - private final String accessToken; - private final String refreshToken; - - private HxAuth(String accessToken, String refreshToken) { - if (accessToken == null) { - throw new IllegalArgumentException("accessToken cannot be null"); - } - this.accessToken = accessToken; - this.refreshToken = refreshToken; - } +public interface HxAuth { /** - * Creates an HxAuth instance. + * Returns the JWT access token. * - * @param token the authentication token - * @return a new HxAuth instance with null refresh token + * @return the access token, never null */ - public static HxAuth of(String token) { - return new HxAuth(token, null); - } + String accessToken(); /** - * Creates an HxAuth instance. + * Returns the refresh token. * - * @param token the authentication token - * @param refresh the refresh token - * @return a new HxAuth instance + * @return the refresh token, or null if not set */ - public static HxAuth of(String token, String refresh) { - return new HxAuth(token, refresh); - } + String refreshToken(); /** - * Computes the storage key for the given authentication object. - * - *

    Returns the SHA-256 hash of the access token as a hexadecimal string. + * Returns the refresh URL for this auth context. * - * @param auth the authentication object (must not be null) - * @return the computed key as a 64-character hexadecimal string - * @throws IllegalArgumentException if auth is null + * @return the refresh URL, or null to use the global config default */ - public static String key(HxAuth auth) { - if (auth == null) { - throw new IllegalArgumentException("auth cannot be null"); - } - try { - final MessageDigest digest = MessageDigest.getInstance("SHA-256"); - final byte[] hash = digest.digest(auth.accessToken().getBytes(StandardCharsets.UTF_8)); - return HexFormat.of().formatHex(hash); - } - catch (NoSuchAlgorithmException e) { - throw new RuntimeException("SHA-256 algorithm not available", e); - } - } + String refreshUrl(); /** - * Computes the storage key for the given authentication object, or returns a default value if null. + * Returns a stable identifier for this auth in the token store. * - * @param auth the authentication object, may be null - * @param defaultValue the value to return if auth is null - * @return the computed key, or defaultValue if auth is null + *

    The key must remain constant across token refreshes so the same + * auth session can be tracked after {@link #withToken(String)} or + * {@link #withRefresh(String)} updates. + * + * @return the stable identifier */ - public static String keyOrDefault(HxAuth auth, String defaultValue) { - return auth != null ? key(auth) : defaultValue; - } + String id(); /** - * Returns the JWT access token. + * Returns an {@link HxAuth} with the given access token. * - * @return the access token + * @param token the new access token + * @return an {@link HxAuth} with the updated token */ - public String accessToken() { - return accessToken; - } + HxAuth withToken(String token); /** - * Returns the refresh token. + * Returns an {@link HxAuth} with the given refresh token. * - * @return the refresh token, or null if not set + * @param refresh the new refresh token + * @return an {@link HxAuth} with the updated refresh token */ - public String refreshToken() { - return refreshToken; - } - - @Override - public boolean equals(Object o) { - if (this == o) return true; - if (o == null || getClass() != o.getClass()) return false; - HxAuth hxAuth = (HxAuth) o; - return Objects.equals(accessToken, hxAuth.accessToken) - && Objects.equals(refreshToken, hxAuth.refreshToken); - } - - @Override - public int hashCode() { - return Objects.hash(accessToken, refreshToken); - } - - @Override - public String toString() { - return "HxAuth[" + - "accessToken=" + mask(accessToken) + - ", refreshToken=" + mask(refreshToken) + - ']'; - } + HxAuth withRefresh(String refresh); - private static String mask(String value) { - if (value == null) return "null"; - if (value.length() <= 8) return "***"; - return value.substring(0, 4) + "***" + value.substring(value.length() - 4); - } } diff --git a/lib-httpx/src/main/java/io/seqera/http/HxClient.java b/lib-httpx/src/main/java/io/seqera/http/HxClient.java index edaf1eb7..bc05b9ac 100644 --- a/lib-httpx/src/main/java/io/seqera/http/HxClient.java +++ b/lib-httpx/src/main/java/io/seqera/http/HxClient.java @@ -494,7 +494,7 @@ protected HttpResponse sendWithRetry(HttpRequest request, HxAuth auth, Ht // Try JWT token refresh if (canRefreshToken(auth)) { - final String debugKey = HxAuth.keyOrDefault(auth, "-"); + final String debugKey = auth.id(); log.debug("Received 401 status for auth key {}, attempting token refresh", debugKey); try { if (refreshToken(auth)) { @@ -567,7 +567,7 @@ protected CompletableFuture> sendWithRetryAsync( // Try JWT token refresh if (canRefreshToken(auth)) { - final String debugKey = HxAuth.keyOrDefault(auth, "-"); + final String debugKey = auth.id(); log.debug("Received 401 status in async call for auth key {}, attempting token refresh", debugKey); try { if (refreshToken(auth)) { diff --git a/lib-httpx/src/main/java/io/seqera/http/HxTokenManager.java b/lib-httpx/src/main/java/io/seqera/http/HxTokenManager.java index 6d09bf5f..b1223a1f 100644 --- a/lib-httpx/src/main/java/io/seqera/http/HxTokenManager.java +++ b/lib-httpx/src/main/java/io/seqera/http/HxTokenManager.java @@ -119,7 +119,7 @@ public HxTokenManager(HxConfig config, HxTokenStore tokenStore) { final String jwtToken = config.getJwtToken(); final String refreshToken = config.getRefreshToken(); if (jwtToken != null && !jwtToken.isEmpty()) { - tokenStore.put(DEFAULT_TOKEN, HxAuth.of(jwtToken, refreshToken)); + tokenStore.put(DEFAULT_TOKEN, new DefaultHxAuth(jwtToken, refreshToken, config.getRefreshTokenUrl())); } // Validate JWT token refresh configuration @@ -277,7 +277,7 @@ public CompletableFuture getOrRefreshTokenAsync(HxAuth auth) { return CompletableFuture.completedFuture(null); } - final String key = HxAuth.key(auth); + final String key = auth.id(); // Use computeIfAbsent for atomic coordination - only first caller creates the future return ongoingRefreshes.computeIfAbsent(key, k -> { @@ -429,7 +429,7 @@ synchronized void updateTokens(String jwtToken, String refreshToken) { } if (newToken != null) { - tokenStore.put(DEFAULT_TOKEN, HxAuth.of(newToken, newRefresh)); + tokenStore.put(DEFAULT_TOKEN, new DefaultHxAuth(newToken, newRefresh, config.getRefreshTokenUrl())); } } @@ -450,7 +450,7 @@ public HxAuth getAuth(HxAuth auth) { if (auth == null) { return null; } - final String key = HxAuth.key(auth); + final String key = auth.id(); return tokenStore.putIfAbsent(key, auth); } @@ -489,7 +489,20 @@ public boolean canRefreshToken(HxAuth auth) { return false; } final HxAuth currentAuth = getAuth(auth); - return currentAuth.refreshToken() != null && config.getRefreshTokenUrl() != null; + return currentAuth.refreshToken() != null && resolveRefreshUrl(currentAuth) != null; + } + + /** + * Resolves the refresh URL for the given auth, falling back to the global config. + * + * @param auth the authentication data + * @return the refresh URL, or null if none is configured + */ + private String resolveRefreshUrl(HxAuth auth) { + if (auth != null && auth.refreshUrl() != null) { + return auth.refreshUrl(); + } + return config.getRefreshTokenUrl(); } /** @@ -535,7 +548,7 @@ public CompletableFuture refreshTokenAsync(HxAuth auth) { */ protected HxAuth doRefreshToken(HxAuth auth) { final HxAuth currentAuth = getAuth(auth); - return doRefreshTokenInternal(HxAuth.key(auth), currentAuth); + return doRefreshTokenInternal(auth.id(), currentAuth); } /** @@ -547,7 +560,7 @@ protected HxAuth doRefreshToken(HxAuth auth) { */ protected HxAuth doRefreshTokenInternal(String key, HxAuth auth) { try { - final var refreshUrl = URI.create(config.getRefreshTokenUrl()); + final var refreshUrl = URI.create(resolveRefreshUrl(auth)); log.trace("Attempting to refresh JWT token for key {} at URL: {}", key, refreshUrl); // Create per-refresh CookieManager and HttpClient to avoid cross-user cookie leaking @@ -597,45 +610,52 @@ protected HxAuth doRefreshTokenInternal(String key, HxAuth auth) { * * @param response the HTTP response from the token refresh request * @param cookieManager the cookie manager used for the refresh request - * @param originalAuth the original authentication data (used to preserve refresh token if not returned) + * @param auth the original authentication data (used to preserve refresh token if not returned) * @return a new {@link HxAuth} with updated tokens, or null if extraction failed */ - protected HxAuth extractAuthFromResponse(HttpResponse response, CookieManager cookieManager, HxAuth originalAuth) { - try { - // First try to extract tokens from cookie store - final HttpCookie authCookie = getCookie(cookieManager, "JWT"); - final HttpCookie refreshCookie = getCookie(cookieManager, "JWT_REFRESH_TOKEN"); - - if (authCookie != null && authCookie.getValue() != null) { - log.trace("Successfully extracted JWT token from cookies"); - final String newToken = authCookie.getValue(); - final String newRefresh = (refreshCookie != null && refreshCookie.getValue() != null) - ? refreshCookie.getValue() - : originalAuth.refreshToken(); - return HxAuth.of(newToken, newRefresh); - } else { - log.trace("No JWT token found in cookies, trying JSON response"); - - try { - final JsonObject jsonResponse = JsonParser.parseString(response.body()).getAsJsonObject(); - if (jsonResponse.has("access_token")) { - final String accessToken = jsonResponse.get("access_token").getAsString(); - if (isValidJwtToken(accessToken)) { - log.trace("Successfully extracted JWT token from JSON"); - final String newRefresh = jsonResponse.has("refresh_token") - ? jsonResponse.get("refresh_token").getAsString() - : originalAuth.refreshToken(); - return HxAuth.of(accessToken, newRefresh); - } - } - } catch (Exception e) { - log.trace("Response is not valid JSON"); - } + protected HxAuth extractAuthFromResponse(HttpResponse response, CookieManager cookieManager, HxAuth auth) { + // Try cookies first + final String newToken = extractTokenFromCookies(cookieManager); + if (newToken != null) { + final String newRefresh = extractRefreshFromCookies(cookieManager); + HxAuth result = auth.withToken(newToken); + if (newRefresh != null) { + result = result.withRefresh(newRefresh); + } + return result; + } + + // Fall back to JSON response + return extractAuthFromJson(response, auth); + } + + private String extractTokenFromCookies(CookieManager cookieManager) { + final HttpCookie cookie = getCookie(cookieManager, "JWT"); + return (cookie != null) ? cookie.getValue() : null; + } + private String extractRefreshFromCookies(CookieManager cookieManager) { + final HttpCookie cookie = getCookie(cookieManager, "JWT_REFRESH_TOKEN"); + return (cookie != null) ? cookie.getValue() : null; + } + + private HxAuth extractAuthFromJson(HttpResponse response, HxAuth auth) { + try { + final JsonObject json = JsonParser.parseString(response.body()).getAsJsonObject(); + if (!json.has("access_token")) { return null; } + final String accessToken = json.get("access_token").getAsString(); + if (!isValidJwtToken(accessToken)) { + return null; + } + HxAuth result = auth.withToken(accessToken); + if (json.has("refresh_token")) { + result = result.withRefresh(json.get("refresh_token").getAsString()); + } + return result; } catch (Exception e) { - log.error("Error extracting tokens from response: {}", e.getMessage(), e); + log.trace("Response is not valid JSON"); return null; } } diff --git a/lib-httpx/src/test/groovy/io/seqera/http/HxAuthTest.groovy b/lib-httpx/src/test/groovy/io/seqera/http/HxAuthTest.groovy index 0759fc63..5018a275 100644 --- a/lib-httpx/src/test/groovy/io/seqera/http/HxAuthTest.groovy +++ b/lib-httpx/src/test/groovy/io/seqera/http/HxAuthTest.groovy @@ -28,44 +28,48 @@ class HxAuthTest extends Specification { def 'should create auth with token only'() { when: - def auth = HxAuth.of('my.jwt.token') + def auth = new DefaultHxAuth('my.jwt.token', null) then: auth.accessToken() == 'my.jwt.token' auth.refreshToken() == null + auth.refreshUrl() == null } def 'should create auth with token and refresh'() { when: - def auth = HxAuth.of('my.jwt.token', 'my-refresh-token') + def auth = new DefaultHxAuth('my.jwt.token', 'my-refresh-token') then: auth.accessToken() == 'my.jwt.token' auth.refreshToken() == 'my-refresh-token' + auth.refreshUrl() == null } - def 'should compute consistent key from token'() { - given: - def auth1 = HxAuth.of('my.jwt.token', 'refresh1') - def auth2 = HxAuth.of('my.jwt.token', 'refresh2') - def auth3 = HxAuth.of('different.jwt.token', 'refresh1') + def 'should create auth with token, refresh, and refreshUrl'() { + when: + def auth = new DefaultHxAuth('my.jwt.token', 'my-refresh-token', 'https://example.com/oauth/token') - expect: - HxAuth.key(auth1) == HxAuth.key(auth2) // same token = same key - HxAuth.key(auth1) != HxAuth.key(auth3) // different token = different key - HxAuth.key(auth1).length() == 64 // SHA-256 hex = 64 chars + then: + auth.accessToken() == 'my.jwt.token' + auth.refreshToken() == 'my-refresh-token' + auth.refreshUrl() == 'https://example.com/oauth/token' } - def 'should return default key for null auth'() { + def 'should assign unique stable key'() { + given: + def auth1 = new DefaultHxAuth('my.jwt.token', 'refresh1') + def auth2 = new DefaultHxAuth('my.jwt.token', 'refresh2') + expect: - HxAuth.keyOrDefault(null, 'default') == 'default' - HxAuth.keyOrDefault(HxAuth.of('token'), 'default') != 'default' - HxAuth.keyOrDefault(null, 'custom') == 'custom' + auth1.id() != auth2.id() // each instance gets a unique key + auth1.id() == auth1.withToken('new.jwt.token').id() // key is stable across withToken + auth1.id() == auth1.withRefresh('new-refresh').id() // key is stable across withRefresh } def 'should reject null access token'() { when: - HxAuth.of(null) + new DefaultHxAuth(null, null) then: thrown(IllegalArgumentException) @@ -73,7 +77,7 @@ class HxAuthTest extends Specification { def 'should reject null access token with refresh'() { when: - HxAuth.of(null, 'refresh') + new DefaultHxAuth(null, 'refresh') then: thrown(IllegalArgumentException) @@ -81,7 +85,7 @@ class HxAuthTest extends Specification { def 'should mask tokens in toString'() { when: - def auth = HxAuth.of('eyJhbGciOiJIUzI1NiJ9.payload.signature', 'my-refresh-token-value') + def auth = new DefaultHxAuth('eyJhbGciOiJIUzI1NiJ9.payload.signature', 'my-refresh-token-value') then: !auth.toString().contains('eyJhbGciOiJIUzI1NiJ9.payload.signature') @@ -89,16 +93,14 @@ class HxAuthTest extends Specification { auth.toString().startsWith('HxAuth[') } - def 'should implement equals and hashCode correctly'() { + def 'each instance should have unique identity'() { + given: + def auth1 = new DefaultHxAuth('a.b.c', 'r1') + def auth2 = new DefaultHxAuth('a.b.c', 'r1') + expect: - HxAuth.of(token1, refresh1) == HxAuth.of(token2, refresh2) == expected - (HxAuth.of(token1, refresh1).hashCode() == HxAuth.of(token2, refresh2).hashCode()) == expected - - where: - token1 | refresh1 | token2 | refresh2 | expected - 'a.b.c' | 'r1' | 'a.b.c' | 'r1' | true - 'a.b.c' | null | 'a.b.c' | null | true - 'a.b.c' | 'r1' | 'a.b.c' | 'r2' | false - 'a.b.c' | 'r1' | 'x.y.z' | 'r1' | false + auth1.id() != auth2.id() // different instances have different keys + auth1.id() == auth1.withToken('x.y.z').id() // key preserved after withToken + auth1.id() == auth1.withRefresh('r2').id() // key preserved after withRefresh } } diff --git a/lib-httpx/src/test/groovy/io/seqera/http/HxMapTokenStoreTest.groovy b/lib-httpx/src/test/groovy/io/seqera/http/HxMapTokenStoreTest.groovy index 8be83038..49049b00 100644 --- a/lib-httpx/src/test/groovy/io/seqera/http/HxMapTokenStoreTest.groovy +++ b/lib-httpx/src/test/groovy/io/seqera/http/HxMapTokenStoreTest.groovy @@ -29,7 +29,7 @@ class HxMapTokenStoreTest extends Specification { def 'should store and retrieve auth by key'() { given: def store = new HxMapTokenStore() - def auth = HxAuth.of('my.jwt.token', 'refresh') + def auth = new DefaultHxAuth('my.jwt.token', 'refresh') when: store.put('key1', auth) @@ -42,7 +42,7 @@ class HxMapTokenStoreTest extends Specification { def 'should remove auth'() { given: def store = new HxMapTokenStore() - def auth = HxAuth.of('my.jwt.token', 'refresh') + def auth = new DefaultHxAuth('my.jwt.token', 'refresh') store.put('key1', auth) when: @@ -57,7 +57,7 @@ class HxMapTokenStoreTest extends Specification { def 'putIfAbsent should store and return auth when key is absent'() { given: def store = new HxMapTokenStore() - def auth = HxAuth.of('my.jwt.token', 'refresh') + def auth = new DefaultHxAuth('my.jwt.token', 'refresh') when: def result = store.putIfAbsent('key1', auth) @@ -70,8 +70,8 @@ class HxMapTokenStoreTest extends Specification { def 'putIfAbsent should return existing auth when key is present'() { given: def store = new HxMapTokenStore() - def existing = HxAuth.of('existing.jwt.token', 'refresh1') - def newAuth = HxAuth.of('new.jwt.token', 'refresh2') + def existing = new DefaultHxAuth('existing.jwt.token', 'refresh1') + def newAuth = new DefaultHxAuth('new.jwt.token', 'refresh2') store.put('key1', existing) when: diff --git a/lib-httpx/src/test/groovy/io/seqera/http/HxTokenManagerTest.groovy b/lib-httpx/src/test/groovy/io/seqera/http/HxTokenManagerTest.groovy index 12e5e7b0..20c04078 100644 --- a/lib-httpx/src/test/groovy/io/seqera/http/HxTokenManagerTest.groovy +++ b/lib-httpx/src/test/groovy/io/seqera/http/HxTokenManagerTest.groovy @@ -254,7 +254,7 @@ class HxTokenManagerTest extends Specification { given: def config = HxConfig.newBuilder().build() def tokenManager = new HxTokenManager(config) - def auth = HxAuth.of('my.jwt.token', 'refresh') + def auth = new DefaultHxAuth('my.jwt.token', 'refresh') when: def result = tokenManager.getAuth(auth) @@ -277,7 +277,7 @@ class HxTokenManagerTest extends Specification { given: def config = HxConfig.newBuilder().build() def tokenManager = new HxTokenManager(config) - def auth = HxAuth.of('custom.jwt.token', 'refresh') + def auth = new DefaultHxAuth('custom.jwt.token', 'refresh') def request = HttpRequest.newBuilder() .uri(URI.create('https://example.com/api')) .GET() @@ -300,10 +300,16 @@ class HxTokenManagerTest extends Specification { def configWithoutUrl = HxConfig.newBuilder().build() expect: - new HxTokenManager(configWithUrl).canRefreshToken(HxAuth.of('a.b.c', 'refresh')) == true - new HxTokenManager(configWithUrl).canRefreshToken(HxAuth.of('a.b.c', null)) == false + // config has refreshUrl → can refresh if auth has refresh token + new HxTokenManager(configWithUrl).canRefreshToken(new DefaultHxAuth('a.b.c', 'refresh')) == true + new HxTokenManager(configWithUrl).canRefreshToken(new DefaultHxAuth('a.b.c', null)) == false new HxTokenManager(configWithUrl).canRefreshToken(null) == false - new HxTokenManager(configWithoutUrl).canRefreshToken(HxAuth.of('a.b.c', 'refresh')) == false + // config has no refreshUrl, auth has no refreshUrl → cannot refresh + new HxTokenManager(configWithoutUrl).canRefreshToken(new DefaultHxAuth('a.b.c', 'refresh')) == false + // config has no refreshUrl, but auth carries its own refreshUrl → can refresh + new HxTokenManager(configWithoutUrl).canRefreshToken(new DefaultHxAuth('a.b.c', 'refresh', 'https://other.com/oauth/token')) == true + // auth has refreshUrl but no refresh token → cannot refresh + new HxTokenManager(configWithoutUrl).canRefreshToken(new DefaultHxAuth('a.b.c', null, 'https://other.com/oauth/token')) == false } def 'should accept custom token store'() { @@ -311,13 +317,13 @@ class HxTokenManagerTest extends Specification { def customStore = new HxMapTokenStore() def config = HxConfig.newBuilder().build() def tokenManager = new HxTokenManager(config, customStore) - def auth = HxAuth.of('my.jwt.token', 'refresh') + def auth = new DefaultHxAuth('my.jwt.token', 'refresh') when: tokenManager.getAuth(auth) then: - customStore.get(HxAuth.key(auth)) == auth + customStore.get(auth.id()) == auth tokenManager.getTokenStore() == customStore } } From 5d3b0ee075df59dc2e0b89320b407170bf4fed0a Mon Sep 17 00:00:00 2001 From: Paolo Di Tommaso Date: Sat, 21 Feb 2026 00:32:46 +0100 Subject: [PATCH 7/9] Fix review issues: stale docs, refresh race, canRefreshToken side effect - Fix stable stable typo in HxAuth Javadoc - Update HxTokenStore Javadoc to reference HxAuth.id() instead of SHA-256 - Use two-arg remove(key, future) in refresh coordination to prevent accidental removal of a concurrent callers future - Make canRefreshToken(HxAuth) side-effect-free by using tokenStore.get() instead of getAuth() which calls putIfAbsent - Add comment clarifying updateTokens synchronized scope - Update HxTokenManager class Javadoc with current API example - Remove DefaultHxAuth references from README (package-private) Co-Authored-By: Claude Opus 4.6 --- lib-httpx/README.md | 57 +++++++------------ .../src/main/java/io/seqera/http/HxAuth.java | 2 +- .../java/io/seqera/http/HxTokenManager.java | 45 ++++++++------- .../java/io/seqera/http/HxTokenStore.java | 14 ++--- 4 files changed, 55 insertions(+), 63 deletions(-) diff --git a/lib-httpx/README.md b/lib-httpx/README.md index 3c4dae95..5bc7ce76 100644 --- a/lib-httpx/README.md +++ b/lib-httpx/README.md @@ -155,44 +155,11 @@ For applications managing multiple users or authentication contexts, use the `Hx | `withToken(token)` | Returns an `HxAuth` with the updated access token (same `id`) | | `withRefresh(refresh)` | Returns an `HxAuth` with the updated refresh token (same `id`) | -The default implementation `DefaultHxAuth` is an immutable record that auto-generates a UUID as `id()`. The `withToken` and `withRefresh` methods return new instances preserving the same `id`. - -#### Basic Multi-Session Usage - -```java -// Create a shared client -HxClient client = HxClient.newBuilder().build(); - -// Create auth for each user session (each gets a unique id) -HxAuth user1Auth = new DefaultHxAuth("user1.jwt.token", "user1-refresh-token", "https://api.example.com/oauth/token"); -HxAuth user2Auth = new DefaultHxAuth("user2.jwt.token", "user2-refresh-token", "https://api.example.com/oauth/token"); - -// Make requests with per-user authentication -HttpRequest request = HttpRequest.newBuilder() - .uri(URI.create("https://api.example.com/data")) - .GET() - .build(); - -HttpResponse response1 = client.send(request, user1Auth, HttpResponse.BodyHandlers.ofString()); -HttpResponse response2 = client.send(request, user2Auth, HttpResponse.BodyHandlers.ofString()); - -// Async requests also supported -CompletableFuture> future = client.sendAsync(request, user1Auth, HttpResponse.BodyHandlers.ofString()); -``` - -#### Per-Auth Refresh URL - -Each `HxAuth` can carry its own `refreshUrl`, allowing different auth sessions to refresh against different endpoints. If `refreshUrl()` returns null, the global `refreshTokenUrl` from `HxConfig` is used as fallback. - -```java -// Different users refresh against different endpoints -HxAuth user1 = new DefaultHxAuth("user1.jwt.token", "user1-refresh", "https://region1.example.com/oauth/token"); -HxAuth user2 = new DefaultHxAuth("user2.jwt.token", "user2-refresh", "https://region2.example.com/oauth/token"); -``` +Implementations must ensure `id()` remains constant — `withToken` and `withRefresh` return new instances preserving the same `id`. #### Custom `HxAuth` Implementation -Implement `HxAuth` to customise the identity strategy (e.g., key by user ID or tenant): +Implement `HxAuth` to define the identity strategy and token lifecycle for your application (e.g., key by user ID or tenant). Each `HxAuth` can also carry its own `refreshUrl`, allowing different auth sessions to refresh against different endpoints. If `refreshUrl()` returns null, the global `refreshTokenUrl` from `HxConfig` is used as fallback. ```java public class TenantAuth implements HxAuth { @@ -221,6 +188,25 @@ public class TenantAuth implements HxAuth { return new TenantAuth(tenantId, accessToken, refresh); } } + +// Create a shared client +HxClient client = HxClient.newBuilder().build(); + +// Create auth for each user/tenant session +HxAuth user1Auth = new TenantAuth("tenant-1", "user1.jwt.token", "user1-refresh-token"); +HxAuth user2Auth = new TenantAuth("tenant-2", "user2.jwt.token", "user2-refresh-token"); + +// Make requests with per-user authentication +HttpRequest request = HttpRequest.newBuilder() + .uri(URI.create("https://api.example.com/data")) + .GET() + .build(); + +HttpResponse response1 = client.send(request, user1Auth, HttpResponse.BodyHandlers.ofString()); +HttpResponse response2 = client.send(request, user2Auth, HttpResponse.BodyHandlers.ofString()); + +// Async requests also supported +CompletableFuture> future = client.sendAsync(request, user1Auth, HttpResponse.BodyHandlers.ofString()); ``` #### Custom Token Store @@ -333,7 +319,6 @@ HxClient client = HxClient.newBuilder() - **`HxClient`**: Main HTTP client with retry, JWT, and WWW-Authenticate functionality - **`HxConfig`**: Configuration builder with all available options - **`HxAuth`**: Interface for authentication credentials with stable identity across refreshes -- **`DefaultHxAuth`**: Immutable record implementation of `HxAuth` with UUID-based identity - **`HxTokenStore`**: Interface for pluggable token storage (default: in-memory ConcurrentHashMap) - **`HxTokenManager`**: Thread-safe JWT token lifecycle management with multi-session support - **`AuthenticationChallenge`**: Represents a parsed WWW-Authenticate challenge diff --git a/lib-httpx/src/main/java/io/seqera/http/HxAuth.java b/lib-httpx/src/main/java/io/seqera/http/HxAuth.java index 32e6d335..55716d2f 100644 --- a/lib-httpx/src/main/java/io/seqera/http/HxAuth.java +++ b/lib-httpx/src/main/java/io/seqera/http/HxAuth.java @@ -21,7 +21,7 @@ * Interface for JWT authentication credentials. * *

    Provides access to the JWT access token, optional refresh token, and optional - * refresh URL. The {@link #id()} method returns a stable stable identifier for the token + * refresh URL. The {@link #id()} method returns a stable identifier for the token * store that persists across token refreshes. * *

    The {@link #withToken(String)} and {@link #withRefresh(String)} methods return diff --git a/lib-httpx/src/main/java/io/seqera/http/HxTokenManager.java b/lib-httpx/src/main/java/io/seqera/http/HxTokenManager.java index b1223a1f..27e11616 100644 --- a/lib-httpx/src/main/java/io/seqera/http/HxTokenManager.java +++ b/lib-httpx/src/main/java/io/seqera/http/HxTokenManager.java @@ -45,7 +45,7 @@ *

  • Header Injection: Automatically adds Authorization headers to HTTP requests
  • *
  • Token Validation: Validates JWT token format (header.payload.signature)
  • *
  • Token Refresh: Implements OAuth 2.0 refresh token flow
  • - *
  • Thread Safety: Uses read/write locks for safe concurrent access
  • + *
  • Thread Safety: Uses synchronized blocks and ConcurrentHashMap for safe concurrent access
  • * * *

    Token Refresh Process:
    @@ -72,21 +72,21 @@ * *

    Usage Example: *

    {@code
    - * HttpClientConfig config = HttpClientConfig.builder()
    - *     .withJwtToken("eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...")
    - *     .withRefreshToken("your-refresh-token")
    - *     .withRefreshTokenUrl("https://api.example.com/oauth/token")
    + * HxConfig config = HxConfig.newBuilder()
    + *     .bearerToken("eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...")
    + *     .refreshToken("your-refresh-token")
    + *     .refreshTokenUrl("https://api.example.com/oauth/token")
      *     .build();
    - *     
    - * JwtTokenManager manager = new JwtTokenManager(config);
    - * 
    + *
    + * HxTokenManager manager = new HxTokenManager(config);
    + *
      * // Add auth header to requests
      * HttpRequest authenticatedRequest = manager.addAuthHeader(originalRequest);
    - * 
    - * // Refresh tokens when needed
    - * if (manager.canRefreshToken()) {
    - *     boolean success = manager.refreshToken();
    - * }
    + *
    + * // Multi-session: use HxAuth for per-user token management
    + * HxAuth userAuth = new DefaultHxAuth("user.jwt.token", "refresh-token", "https://example.com/oauth/token");
    + * HxAuth current = manager.getAuth(userAuth);
    + * HttpRequest userRequest = manager.addAuthHeader(originalRequest, current);
      * }
    * * @author Paolo Di Tommaso @@ -282,16 +282,18 @@ public CompletableFuture getOrRefreshTokenAsync(HxAuth auth) { // Use computeIfAbsent for atomic coordination - only first caller creates the future return ongoingRefreshes.computeIfAbsent(key, k -> { log.trace("Starting coordinated token refresh for key {}", k); - return CompletableFuture.supplyAsync(() -> doRefreshToken(auth)) - .whenComplete((result, throwable) -> { - // Remove from map after completion to allow future refreshes - ongoingRefreshes.remove(key); + CompletableFuture future = CompletableFuture.supplyAsync(() -> doRefreshToken(auth)); + future.whenComplete((result, throwable) -> { + // Use two-arg remove to only remove if still our future, + // avoiding accidental removal of a concurrent caller's future + ongoingRefreshes.remove(key, future); if (throwable != null) { log.error("Coordinated token refresh failed for key {}: {}", key, throwable.getMessage(), throwable); } else { log.trace("Coordinated token refresh completed for key {} with result: {}", key, (result != null)); } }); + return future; }); } @@ -414,6 +416,9 @@ public boolean hasBasicAuth() { * @param jwtToken the new JWT token to set, may be null * @param refreshToken the new refresh token to set, may be null */ + // Note: synchronized protects the read-modify-write on DEFAULT_TOKEN only. + // Multi-session refreshes (doRefreshTokenInternal) operate on separate keys + // and are coordinated via ongoingRefreshes/computeIfAbsent. synchronized void updateTokens(String jwtToken, String refreshToken) { final HxAuth currentAuth = tokenStore.get(DEFAULT_TOKEN); String newToken = (currentAuth != null) ? currentAuth.accessToken() : null; @@ -488,8 +493,10 @@ public boolean canRefreshToken(HxAuth auth) { if (auth == null) { return false; } - final HxAuth currentAuth = getAuth(auth); - return currentAuth.refreshToken() != null && resolveRefreshUrl(currentAuth) != null; + // Use tokenStore.get() to avoid the side effect of storing the auth + final HxAuth currentAuth = tokenStore.get(auth.id()); + final HxAuth effectiveAuth = currentAuth != null ? currentAuth : auth; + return effectiveAuth.refreshToken() != null && resolveRefreshUrl(effectiveAuth) != null; } /** diff --git a/lib-httpx/src/main/java/io/seqera/http/HxTokenStore.java b/lib-httpx/src/main/java/io/seqera/http/HxTokenStore.java index ebd26a71..b36867ab 100644 --- a/lib-httpx/src/main/java/io/seqera/http/HxTokenStore.java +++ b/lib-httpx/src/main/java/io/seqera/http/HxTokenStore.java @@ -18,11 +18,11 @@ package io.seqera.http; /** - * Interface for storing and retrieving JWT token pairs by key. + * Interface for storing and retrieving {@link HxAuth} instances by key. * *

    This interface allows for different storage strategies for managing - * multiple user sessions, each with their own token-refresh pair. The key - * is typically derived from the token itself (e.g., SHA-256 hash). + * multiple authentication sessions. The key is typically derived from + * {@link HxAuth#id()}. * *

    Implementations should be thread-safe as they may be accessed * concurrently by multiple requests. @@ -34,7 +34,7 @@ public interface HxTokenStore { /** * Retrieves the authentication data for the given key. * - * @param key the unique key identifying the token pair (typically SHA-256 of the token) + * @param key the unique key identifying the auth session (typically {@link HxAuth#id()}) * @return the {@link HxAuth} containing the token pair, or null if not found */ HxAuth get(String key); @@ -42,7 +42,7 @@ public interface HxTokenStore { /** * Stores the authentication data for the given key. * - * @param key the unique key identifying the token pair (typically SHA-256 of the token) + * @param key the unique key identifying the auth session (typically {@link HxAuth#id()}) * @param auth the {@link HxAuth} containing the token pair to store */ void put(String key, HxAuth auth); @@ -57,7 +57,7 @@ public interface HxTokenStore { *

    Implementations should ensure this operation is atomic to prevent race conditions * in concurrent environments. * - * @param key the unique key identifying the token pair + * @param key the unique key identifying the auth session * @param auth the {@link HxAuth} to store if no value exists for the key * @return the existing {@link HxAuth} if present, otherwise the newly stored auth */ @@ -66,7 +66,7 @@ public interface HxTokenStore { /** * Removes the authentication data for the given key. * - * @param key the unique key identifying the token pair to remove + * @param key the unique key identifying the auth session to remove * @return the removed {@link HxAuth}, or null if not found */ HxAuth remove(String key); From c5f7fb76106a473b00092abdd3b09155294187a1 Mon Sep 17 00:00:00 2001 From: Paolo Di Tommaso Date: Sat, 21 Feb 2026 09:19:24 +0100 Subject: [PATCH 8/9] Remove dead code, use deterministic hashCode-based id, add stateless auth test - Remove 8 unused methods from HxTokenManager (refreshToken, refreshTokenAsync, doRefreshToken, getBasicAuthToken, getTokenStore, updateTokens and their overloads) - Replace UUID-based HxAuth id with deterministic id derived from accessToken and refreshUrl using Objects.hash, so stateless requests always resolve to the same token store entry - Simplify HxClient.refreshToken to use getDefaultAuth fallback - Add test verifying stateless requests resolve refreshed tokens by same id Co-Authored-By: Claude Opus 4.6 --- .../java/io/seqera/http/DefaultHxAuth.java | 18 ++- .../main/java/io/seqera/http/HxClient.java | 6 +- .../java/io/seqera/http/HxTokenManager.java | 144 +----------------- .../groovy/io/seqera/http/HxAuthTest.groovy | 23 +-- .../seqera/http/HxClientBasicAuthTest.groovy | 4 +- .../groovy/io/seqera/http/HxClientTest.groovy | 2 +- .../io/seqera/http/HxTokenManagerTest.groovy | 68 ++++----- 7 files changed, 68 insertions(+), 197 deletions(-) diff --git a/lib-httpx/src/main/java/io/seqera/http/DefaultHxAuth.java b/lib-httpx/src/main/java/io/seqera/http/DefaultHxAuth.java index 8526ef93..5a615e16 100644 --- a/lib-httpx/src/main/java/io/seqera/http/DefaultHxAuth.java +++ b/lib-httpx/src/main/java/io/seqera/http/DefaultHxAuth.java @@ -17,14 +17,16 @@ package io.seqera.http; -import java.util.UUID; +import java.util.Objects; /** * Default immutable implementation of {@link HxAuth}. * *

    Stores JWT access token, refresh token, and refresh URL. - * A stable {@link #id()} is assigned at creation and preserved - * through {@link #withToken(String)} and {@link #withRefresh(String)}. + * A stable {@link #id()} is derived from the initial {@code accessToken} + * and {@code refreshUrl}, so that identical credentials always produce + * the same id. The id is preserved through {@link #withToken(String)} + * and {@link #withRefresh(String)}. * * @author Paolo Di Tommaso */ @@ -40,7 +42,7 @@ record DefaultHxAuth(String id, String accessToken, String refreshToken, String } DefaultHxAuth(String accessToken, String refreshToken, String refreshUrl) { - this(UUID.randomUUID().toString(), accessToken, refreshToken, refreshUrl); + this(computeId(accessToken, refreshUrl), accessToken, refreshToken, refreshUrl); } DefaultHxAuth(String accessToken, String refreshToken) { @@ -67,6 +69,14 @@ public String toString() { ']'; } + private static String computeId(String accessToken, String refreshUrl) { + if (accessToken == null) { + throw new IllegalArgumentException("accessToken cannot be null"); + } + int hash = Objects.hash(accessToken, refreshUrl); + return Integer.toHexString(hash); + } + private static String mask(String value) { if (value == null) return "null"; if (value.length() <= 8) return "***"; diff --git a/lib-httpx/src/main/java/io/seqera/http/HxClient.java b/lib-httpx/src/main/java/io/seqera/http/HxClient.java index bc05b9ac..704e108a 100644 --- a/lib-httpx/src/main/java/io/seqera/http/HxClient.java +++ b/lib-httpx/src/main/java/io/seqera/http/HxClient.java @@ -449,10 +449,8 @@ private boolean canRefreshToken(HxAuth auth) { } private boolean refreshToken(HxAuth auth) throws Exception { - if (auth != null) { - return tokenManager.getOrRefreshTokenAsync(auth).get() != null; - } - return tokenManager.getOrRefreshTokenAsync().get(); + final HxAuth effective = (auth != null) ? auth : tokenManager.getDefaultAuth(); + return effective != null && tokenManager.getOrRefreshTokenAsync(effective).get() != null; } /** diff --git a/lib-httpx/src/main/java/io/seqera/http/HxTokenManager.java b/lib-httpx/src/main/java/io/seqera/http/HxTokenManager.java index 27e11616..464ef905 100644 --- a/lib-httpx/src/main/java/io/seqera/http/HxTokenManager.java +++ b/lib-httpx/src/main/java/io/seqera/http/HxTokenManager.java @@ -49,7 +49,7 @@ * * *

    Token Refresh Process:
    - * When {@link #refreshToken()} or {@link #refreshTokenAsync()} is called, the manager: + * When {@link #getOrRefreshTokenAsync(HxAuth)} is called, the manager: *

      *
    1. Sends a POST request to the configured refresh URL
    2. *
    3. Uses {@code grant_type=refresh_token} with the current refresh token
    4. @@ -224,37 +224,6 @@ public boolean canRefreshToken() { return canRefreshToken(getDefaultAuth()); } - /** - * Attempts to refresh the JWT token synchronously using the configured refresh token. - * - *

      This method performs an OAuth 2.0 refresh token flow: - *

        - *
      • Sends a POST request to the configured refresh token URL
      • - *
      • Uses application/x-www-form-urlencoded content type
      • - *
      • Includes grant_type=refresh_token and the current refresh token
      • - *
      • Extracts new tokens from response cookies or JSON body
      • - *
      • Updates the current JWT and refresh tokens if successful
      • - *
      - * - *

      This method is thread-safe and uses write locks to prevent concurrent modifications. - * - * @return true if token refresh was successful, false otherwise - */ - public boolean refreshToken() { - return refreshToken(getDefaultAuth()) != null; - } - - /** - * Gets or initiates a coordinated token refresh operation to prevent concurrent refreshes. - * - *

      This method delegates to {@link #getOrRefreshTokenAsync(HxAuth)} using the default token. - * - * @return a CompletableFuture that completes with true if refresh was successful, false otherwise - */ - public CompletableFuture getOrRefreshTokenAsync() { - return getOrRefreshTokenAsync(getDefaultAuth()).thenApply(result -> result != null); - } - /** * Gets or initiates a coordinated token refresh operation for the given auth. * @@ -297,30 +266,6 @@ public CompletableFuture getOrRefreshTokenAsync(HxAuth auth) { }); } - /** - * Attempts to refresh the JWT token asynchronously using the configured refresh token. - * - *

      This method performs the same OAuth 2.0 refresh token flow as {@link #refreshToken()} - * but returns a CompletableFuture for non-blocking execution. - * - * @return a CompletableFuture that completes with true if refresh was successful, false otherwise - */ - public CompletableFuture refreshTokenAsync() { - return refreshTokenAsync(getDefaultAuth()).thenApply(result -> result != null); - } - - /** - * Internal method that performs the actual token refresh HTTP request. - * - *

      This method delegates to {@link #doRefreshTokenInternal(String, HxAuth)} using the default token. - * - * @return true if the token refresh was successful, false otherwise - */ - protected boolean doRefreshToken() { - final HxAuth auth = getDefaultAuth(); - return auth != null && doRefreshToken(auth) != null; - } - /** * Extracts a cookie from the given cookie manager by name. * @@ -378,19 +323,6 @@ public String getCurrentRefreshToken() { return auth != null ? auth.refreshToken() : null; } - /** - * Returns the configured basic authentication token, if any. - * - *

      This method provides read-only access to the basic authentication token - * configured in the HxConfig. This can be useful for logging, debugging, or - * conditional authentication logic. - * - * @return the basic authentication token in "username:password" format, or null if not configured - */ - public String getBasicAuthToken() { - return config.getBasicAuthToken(); - } - /** * Checks if basic authentication is properly configured. * @@ -406,38 +338,6 @@ public boolean hasBasicAuth() { !":".equals(config.getBasicAuthToken()); } - /** - * Updates both JWT and refresh tokens atomically. - * - *

      This method validates the JWT token format before updating and will not - * update an invalid JWT token. The refresh token is updated if provided, - * regardless of format (as refresh tokens may have different formats). - * - * @param jwtToken the new JWT token to set, may be null - * @param refreshToken the new refresh token to set, may be null - */ - // Note: synchronized protects the read-modify-write on DEFAULT_TOKEN only. - // Multi-session refreshes (doRefreshTokenInternal) operate on separate keys - // and are coordinated via ongoingRefreshes/computeIfAbsent. - synchronized void updateTokens(String jwtToken, String refreshToken) { - final HxAuth currentAuth = tokenStore.get(DEFAULT_TOKEN); - String newToken = (currentAuth != null) ? currentAuth.accessToken() : null; - String newRefresh = (currentAuth != null) ? currentAuth.refreshToken() : null; - - if (jwtToken != null && isValidJwtToken(jwtToken)) { - newToken = jwtToken; - log.trace("JWT token updated"); - } - if (refreshToken != null) { - newRefresh = refreshToken; - log.trace("Refresh token updated"); - } - - if (newToken != null) { - tokenStore.put(DEFAULT_TOKEN, new DefaultHxAuth(newToken, newRefresh, config.getRefreshTokenUrl())); - } - } - // ======================================================================== // Multi-user token management methods // ======================================================================== @@ -512,39 +412,6 @@ private String resolveRefreshUrl(HxAuth auth) { return config.getRefreshTokenUrl(); } - /** - * Attempts to refresh the JWT token synchronously for the given auth. - * - *

      This method performs an OAuth 2.0 refresh token flow for a specific user session. - * On success, the new tokens are stored in the token store automatically. - * - * @param auth the authentication data containing the refresh token - * @return the updated {@link HxAuth} with new tokens, or null if refresh failed - */ - public HxAuth refreshToken(HxAuth auth) { - if (!canRefreshToken(auth)) { - log.warn("Cannot refresh token for auth: refreshToken={} refreshTokenUrl={}", - (auth != null && auth.refreshToken() != null), config.getRefreshTokenUrl()); - return null; - } - return doRefreshToken(auth); - } - - /** - * Attempts to refresh the JWT token asynchronously for the given auth. - * - * @param auth the authentication data containing the refresh token - * @return a CompletableFuture that completes with the updated {@link HxAuth}, or null if refresh failed - */ - public CompletableFuture refreshTokenAsync(HxAuth auth) { - if (!canRefreshToken(auth)) { - log.warn("Cannot refresh token asynchronously for auth: refreshToken={} refreshTokenUrl={}", - (auth != null && auth.refreshToken() != null), config.getRefreshTokenUrl()); - return CompletableFuture.completedFuture(null); - } - return CompletableFuture.supplyAsync(() -> doRefreshToken(auth)); - } - /** * Performs the actual token refresh for a specific auth. * @@ -667,15 +534,6 @@ private HxAuth extractAuthFromJson(HttpResponse response, HxAuth auth) { } } - /** - * Returns the token store used by this manager. - * - * @return the {@link HxTokenStore} instance - */ - public HxTokenStore getTokenStore() { - return tokenStore; - } - /** * Returns the default authentication data configured from HxConfig. * diff --git a/lib-httpx/src/test/groovy/io/seqera/http/HxAuthTest.groovy b/lib-httpx/src/test/groovy/io/seqera/http/HxAuthTest.groovy index 5018a275..b719173e 100644 --- a/lib-httpx/src/test/groovy/io/seqera/http/HxAuthTest.groovy +++ b/lib-httpx/src/test/groovy/io/seqera/http/HxAuthTest.groovy @@ -56,15 +56,21 @@ class HxAuthTest extends Specification { auth.refreshUrl() == 'https://example.com/oauth/token' } - def 'should assign unique stable key'() { + def 'should compute deterministic stable id'() { given: def auth1 = new DefaultHxAuth('my.jwt.token', 'refresh1') def auth2 = new DefaultHxAuth('my.jwt.token', 'refresh2') + def auth3 = new DefaultHxAuth('different.jwt.token', 'refresh1') + def auth4 = new DefaultHxAuth('my.jwt.token', 'refresh1', 'https://example.com/oauth') + def auth5 = new DefaultHxAuth('my.jwt.token', 'refresh1', 'https://other.com/oauth') expect: - auth1.id() != auth2.id() // each instance gets a unique key - auth1.id() == auth1.withToken('new.jwt.token').id() // key is stable across withToken - auth1.id() == auth1.withRefresh('new-refresh').id() // key is stable across withRefresh + auth1.id() == auth2.id() // same accessToken + refreshUrl = same id + auth1.id() != auth3.id() // different accessToken = different id + auth1.id() != auth4.id() // different refreshUrl = different id + auth4.id() != auth5.id() // different refreshUrl = different id + auth1.id() == auth1.withToken('new.jwt.token').id() // id stable across withToken + auth1.id() == auth1.withRefresh('new-refresh').id() // id stable across withRefresh } def 'should reject null access token'() { @@ -93,14 +99,13 @@ class HxAuthTest extends Specification { auth.toString().startsWith('HxAuth[') } - def 'each instance should have unique identity'() { + def 'same credentials should produce same id'() { given: def auth1 = new DefaultHxAuth('a.b.c', 'r1') - def auth2 = new DefaultHxAuth('a.b.c', 'r1') + def auth2 = new DefaultHxAuth('a.b.c', 'r2') expect: - auth1.id() != auth2.id() // different instances have different keys - auth1.id() == auth1.withToken('x.y.z').id() // key preserved after withToken - auth1.id() == auth1.withRefresh('r2').id() // key preserved after withRefresh + auth1.id() == auth2.id() // same accessToken + refreshUrl = same id + auth1.id() != null && !auth1.id().isEmpty() } } diff --git a/lib-httpx/src/test/groovy/io/seqera/http/HxClientBasicAuthTest.groovy b/lib-httpx/src/test/groovy/io/seqera/http/HxClientBasicAuthTest.groovy index 433fd32f..fc07e321 100644 --- a/lib-httpx/src/test/groovy/io/seqera/http/HxClientBasicAuthTest.groovy +++ b/lib-httpx/src/test/groovy/io/seqera/http/HxClientBasicAuthTest.groovy @@ -185,14 +185,14 @@ class HxClientBasicAuthTest extends Specification { then: client1.tokenManager.hasBasicAuth() - client1.tokenManager.basicAuthToken == "user:pass" + client1.config.basicAuthToken == "user:pass" when: def client2 = HxClient.newHxClient() // No basic auth then: !client2.tokenManager.hasBasicAuth() - client2.tokenManager.basicAuthToken == null + client2.config.basicAuthToken == null } def "should preserve request properties when adding auth header"() { diff --git a/lib-httpx/src/test/groovy/io/seqera/http/HxClientTest.groovy b/lib-httpx/src/test/groovy/io/seqera/http/HxClientTest.groovy index 5ae3013d..9f49d1c0 100644 --- a/lib-httpx/src/test/groovy/io/seqera/http/HxClientTest.groovy +++ b/lib-httpx/src/test/groovy/io/seqera/http/HxClientTest.groovy @@ -393,6 +393,6 @@ class HxClientTest extends Specification { .build() then: - client.tokenManager.getTokenStore() == customStore + client.tokenManager.tokenStore == customStore } } diff --git a/lib-httpx/src/test/groovy/io/seqera/http/HxTokenManagerTest.groovy b/lib-httpx/src/test/groovy/io/seqera/http/HxTokenManagerTest.groovy index 20c04078..87076fab 100644 --- a/lib-httpx/src/test/groovy/io/seqera/http/HxTokenManagerTest.groovy +++ b/lib-httpx/src/test/groovy/io/seqera/http/HxTokenManagerTest.groovy @@ -122,39 +122,6 @@ class HxTokenManagerTest extends Specification { // Note: Skipping this test as HttpHeaders is a final class that cannot be easily mocked in Spock // This functionality is covered by integration tests - def 'should update tokens thread-safely'() { - given: - def config = HxConfig.newBuilder() - .bearerToken('fake.jwt.token') - .refreshToken('fake-refresh-token') - .refreshTokenUrl('https://example.com/oauth/token') - .build() - def tokenManager = new HxTokenManager(config) - - when: - tokenManager.updateTokens('new-jwt-token.new.token', 'new-refresh-token') - - then: - tokenManager.getCurrentJwtToken() == 'new-jwt-token.new.token' - tokenManager.getCurrentRefreshToken() == 'new-refresh-token' - } - - def 'should not update invalid JWT token'() { - given: - def config = HxConfig.newBuilder() - .bearerToken('fake.jwt.token') - .build() - def tokenManager = new HxTokenManager(config) - def originalToken = tokenManager.getCurrentJwtToken() - - when: - tokenManager.updateTokens('invalid-token', 'new-refresh-token') - - then: - tokenManager.getCurrentJwtToken() == originalToken - tokenManager.getCurrentRefreshToken() == 'new-refresh-token' - } - def 'should validate JWT token refresh configuration'() { when: 'creating with JWT token + refresh token but missing refresh URL' def config1 = HxConfig.newBuilder() @@ -324,6 +291,39 @@ class HxTokenManagerTest extends Specification { then: customStore.get(auth.id()) == auth - tokenManager.getTokenStore() == customStore + } + + def 'stateless request should resolve refreshed token by same id'() { + given: 'a token manager with a store' + def store = new HxMapTokenStore() + def config = HxConfig.newBuilder().build() + def tokenManager = new HxTokenManager(config, store) + def request = HttpRequest.newBuilder() + .uri(URI.create('https://example.com/api')) + .GET() + .build() + + and: 'initial auth is registered' + def originalAuth = new DefaultHxAuth('original.jwt.token', 'refresh1', 'https://example.com/oauth') + tokenManager.getAuth(originalAuth) + + when: 'a token refresh updates the stored auth' + def refreshedAuth = originalAuth.withToken('refreshed.jwt.token').withRefresh('refresh2') + store.put(originalAuth.id(), refreshedAuth) + + and: 'a new stateless request creates auth from the same original credentials' + def newRequestAuth = new DefaultHxAuth('original.jwt.token', 'refresh1', 'https://example.com/oauth') + + then: 'same credentials produce the same id' + newRequestAuth.id() == originalAuth.id() + + and: 'getAuth returns the refreshed tokens from the store' + def resolved = tokenManager.getAuth(newRequestAuth) + resolved.accessToken() == 'refreshed.jwt.token' + resolved.refreshToken() == 'refresh2' + + and: 'a request made with the old credentials is authenticated with the refreshed token' + def authedRequest = tokenManager.addAuthHeader(request, newRequestAuth) + authedRequest.headers().firstValue('Authorization').orElse(null) == 'Bearer refreshed.jwt.token' } } From 7002cf712771828017402fedbc18c25179aa725f Mon Sep 17 00:00:00 2001 From: Paolo Di Tommaso Date: Sun, 22 Feb 2026 15:58:11 +0100 Subject: [PATCH 9/9] Review fixes: rename withToken/withRefresh, remove timestamps from interface, update docs MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - Rename withToken → withAccessToken, withRefresh → withRefreshToken for clarity - Remove createdAt/updatedAt from HxAuth interface (kept in DefaultHxAuth only) - Add Future Improvements section in README for refresh HttpClient reuse - Add README note about DefaultHxAuth 32-bit hash limitation and stronger alternatives - Fix DEFAULT_KEY → DEFAULT_TOKEN comment typo in HxTokenManager Co-Authored-By: Claude Opus 4.6 --- lib-httpx/README.md | 17 ++++++++++++----- .../main/java/io/seqera/http/DefaultHxAuth.java | 17 +++++++++-------- .../src/main/java/io/seqera/http/HxAuth.java | 11 ++++++----- .../java/io/seqera/http/HxTokenManager.java | 10 +++++----- .../groovy/io/seqera/http/HxAuthTest.groovy | 4 ++-- .../io/seqera/http/HxTokenManagerTest.groovy | 2 +- 6 files changed, 35 insertions(+), 26 deletions(-) diff --git a/lib-httpx/README.md b/lib-httpx/README.md index 5bc7ce76..7d1ec889 100644 --- a/lib-httpx/README.md +++ b/lib-httpx/README.md @@ -152,10 +152,12 @@ For applications managing multiple users or authentication contexts, use the `Hx | `accessToken()` | The current JWT access token | | `refreshToken()` | The refresh token (nullable) | | `refreshUrl()` | Per-auth refresh URL override (nullable, falls back to global config) | -| `withToken(token)` | Returns an `HxAuth` with the updated access token (same `id`) | -| `withRefresh(refresh)` | Returns an `HxAuth` with the updated refresh token (same `id`) | +| `withAccessToken(token)` | Returns an `HxAuth` with the updated access token (same `id`) | +| `withRefreshToken(refresh)` | Returns an `HxAuth` with the updated refresh token (same `id`) | -Implementations must ensure `id()` remains constant — `withToken` and `withRefresh` return new instances preserving the same `id`. +Implementations must ensure `id()` remains constant — `withAccessToken` and `withRefreshToken` return new instances preserving the same `id`. + +**Note:** The built-in `DefaultHxAuth` derives its `id()` from a 32-bit hash of the access token and refresh URL. This is suitable for simple scenarios with a small number of auth sessions. For production multi-tenant deployments, provide a custom `HxAuth` implementation with explicit, collision-free identifiers (e.g., user ID or tenant ID) to prevent token store collisions. Alternatively, a custom implementation could use a stronger hash such as SHA-256 or SipHash-2-4 (64-bit) for better collision resistance when explicit IDs are not practical. #### Custom `HxAuth` Implementation @@ -179,12 +181,12 @@ public class TenantAuth implements HxAuth { @Override public String refreshUrl() { return null; } // use global config @Override - public HxAuth withToken(String token) { + public HxAuth withAccessToken(String token) { return new TenantAuth(tenantId, token, refreshToken); } @Override - public HxAuth withRefresh(String refresh) { + public HxAuth withRefreshToken(String refresh) { return new TenantAuth(tenantId, accessToken, refresh); } } @@ -326,6 +328,11 @@ HxClient client = HxClient.newBuilder() - **`AuthenticationCallback`**: Interface for providing authentication credentials - **`WwwAuthenticateParser`**: RFC 7235 compliant parser for WWW-Authenticate headers +## Future Improvements + +- **Inherit HTTP settings for token refresh client**: The internal `HttpClient` used for token refresh currently hardcodes `HTTP/1.1` and `Redirect.NORMAL`. It should inherit HTTP version, redirect policy, and other settings from the main client configuration. +- **Reuse refresh `HttpClient` instances**: A new `HttpClient` (with its own thread pool) is created for each token refresh to prevent cross-user cookie leakage in multi-tenant scenarios. Under high concurrency with many auth sessions refreshing simultaneously, this could cause thread and file descriptor pressure. A per-auth-key cached client or a shared client with per-request cookie isolation could reduce this overhead. + ## Dependencies - `lib-retry`: Provides the underlying retry mechanism using Failsafe diff --git a/lib-httpx/src/main/java/io/seqera/http/DefaultHxAuth.java b/lib-httpx/src/main/java/io/seqera/http/DefaultHxAuth.java index 5a615e16..1d49e8d4 100644 --- a/lib-httpx/src/main/java/io/seqera/http/DefaultHxAuth.java +++ b/lib-httpx/src/main/java/io/seqera/http/DefaultHxAuth.java @@ -17,6 +17,7 @@ package io.seqera.http; +import java.time.Instant; import java.util.Objects; /** @@ -25,12 +26,12 @@ *

      Stores JWT access token, refresh token, and refresh URL. * A stable {@link #id()} is derived from the initial {@code accessToken} * and {@code refreshUrl}, so that identical credentials always produce - * the same id. The id is preserved through {@link #withToken(String)} - * and {@link #withRefresh(String)}. + * the same id. The id is preserved through {@link #withAccessToken(String)} + * and {@link #withRefreshToken(String)}. * * @author Paolo Di Tommaso */ -record DefaultHxAuth(String id, String accessToken, String refreshToken, String refreshUrl) implements HxAuth { +record DefaultHxAuth(String id, String accessToken, String refreshToken, String refreshUrl, Instant createdAt, Instant updatedAt) implements HxAuth { DefaultHxAuth { if (accessToken == null) { @@ -42,7 +43,7 @@ record DefaultHxAuth(String id, String accessToken, String refreshToken, String } DefaultHxAuth(String accessToken, String refreshToken, String refreshUrl) { - this(computeId(accessToken, refreshUrl), accessToken, refreshToken, refreshUrl); + this(computeId(accessToken, refreshUrl), accessToken, refreshToken, refreshUrl, Instant.now(), Instant.now()); } DefaultHxAuth(String accessToken, String refreshToken) { @@ -50,13 +51,13 @@ record DefaultHxAuth(String id, String accessToken, String refreshToken, String } @Override - public HxAuth withToken(String token) { - return new DefaultHxAuth(id, token, refreshToken, refreshUrl); + public HxAuth withAccessToken(String token) { + return new DefaultHxAuth(id, token, refreshToken, refreshUrl, createdAt, Instant.now()); } @Override - public HxAuth withRefresh(String refresh) { - return new DefaultHxAuth(id, accessToken, refresh, refreshUrl); + public HxAuth withRefreshToken(String refresh) { + return new DefaultHxAuth(id, accessToken, refresh, refreshUrl, createdAt, Instant.now()); } @Override diff --git a/lib-httpx/src/main/java/io/seqera/http/HxAuth.java b/lib-httpx/src/main/java/io/seqera/http/HxAuth.java index 55716d2f..0069f287 100644 --- a/lib-httpx/src/main/java/io/seqera/http/HxAuth.java +++ b/lib-httpx/src/main/java/io/seqera/http/HxAuth.java @@ -17,6 +17,7 @@ package io.seqera.http; + /** * Interface for JWT authentication credentials. * @@ -24,7 +25,7 @@ * refresh URL. The {@link #id()} method returns a stable identifier for the token * store that persists across token refreshes. * - *

      The {@link #withToken(String)} and {@link #withRefresh(String)} methods return + *

      The {@link #withAccessToken(String)} and {@link #withRefreshToken(String)} methods return * an {@link HxAuth} with the updated token after a refresh operation. * *

      A default implementation is provided by {@link DefaultHxAuth}. @@ -58,8 +59,8 @@ public interface HxAuth { * Returns a stable identifier for this auth in the token store. * *

      The key must remain constant across token refreshes so the same - * auth session can be tracked after {@link #withToken(String)} or - * {@link #withRefresh(String)} updates. + * auth session can be tracked after {@link #withAccessToken(String)} or + * {@link #withRefreshToken(String)} updates. * * @return the stable identifier */ @@ -71,7 +72,7 @@ public interface HxAuth { * @param token the new access token * @return an {@link HxAuth} with the updated token */ - HxAuth withToken(String token); + HxAuth withAccessToken(String token); /** * Returns an {@link HxAuth} with the given refresh token. @@ -79,6 +80,6 @@ public interface HxAuth { * @param refresh the new refresh token * @return an {@link HxAuth} with the updated refresh token */ - HxAuth withRefresh(String refresh); + HxAuth withRefreshToken(String refresh); } diff --git a/lib-httpx/src/main/java/io/seqera/http/HxTokenManager.java b/lib-httpx/src/main/java/io/seqera/http/HxTokenManager.java index 464ef905..ed876c9f 100644 --- a/lib-httpx/src/main/java/io/seqera/http/HxTokenManager.java +++ b/lib-httpx/src/main/java/io/seqera/http/HxTokenManager.java @@ -115,7 +115,7 @@ public HxTokenManager(HxConfig config, HxTokenStore tokenStore) { this.config = config; this.tokenStore = tokenStore; - // Store initial tokens from config using DEFAULT_KEY + // Store initial tokens from config using DEFAULT_TOKEN final String jwtToken = config.getJwtToken(); final String refreshToken = config.getRefreshToken(); if (jwtToken != null && !jwtToken.isEmpty()) { @@ -492,9 +492,9 @@ protected HxAuth extractAuthFromResponse(HttpResponse response, CookieMa final String newToken = extractTokenFromCookies(cookieManager); if (newToken != null) { final String newRefresh = extractRefreshFromCookies(cookieManager); - HxAuth result = auth.withToken(newToken); + HxAuth result = auth.withAccessToken(newToken); if (newRefresh != null) { - result = result.withRefresh(newRefresh); + result = result.withRefreshToken(newRefresh); } return result; } @@ -523,9 +523,9 @@ private HxAuth extractAuthFromJson(HttpResponse response, HxAuth auth) { if (!isValidJwtToken(accessToken)) { return null; } - HxAuth result = auth.withToken(accessToken); + HxAuth result = auth.withAccessToken(accessToken); if (json.has("refresh_token")) { - result = result.withRefresh(json.get("refresh_token").getAsString()); + result = result.withRefreshToken(json.get("refresh_token").getAsString()); } return result; } catch (Exception e) { diff --git a/lib-httpx/src/test/groovy/io/seqera/http/HxAuthTest.groovy b/lib-httpx/src/test/groovy/io/seqera/http/HxAuthTest.groovy index b719173e..3c4863ca 100644 --- a/lib-httpx/src/test/groovy/io/seqera/http/HxAuthTest.groovy +++ b/lib-httpx/src/test/groovy/io/seqera/http/HxAuthTest.groovy @@ -69,8 +69,8 @@ class HxAuthTest extends Specification { auth1.id() != auth3.id() // different accessToken = different id auth1.id() != auth4.id() // different refreshUrl = different id auth4.id() != auth5.id() // different refreshUrl = different id - auth1.id() == auth1.withToken('new.jwt.token').id() // id stable across withToken - auth1.id() == auth1.withRefresh('new-refresh').id() // id stable across withRefresh + auth1.id() == auth1.withAccessToken('new.jwt.token').id() // id stable across withToken + auth1.id() == auth1.withRefreshToken('new-refresh').id() // id stable across withRefresh } def 'should reject null access token'() { diff --git a/lib-httpx/src/test/groovy/io/seqera/http/HxTokenManagerTest.groovy b/lib-httpx/src/test/groovy/io/seqera/http/HxTokenManagerTest.groovy index 87076fab..f24e8252 100644 --- a/lib-httpx/src/test/groovy/io/seqera/http/HxTokenManagerTest.groovy +++ b/lib-httpx/src/test/groovy/io/seqera/http/HxTokenManagerTest.groovy @@ -308,7 +308,7 @@ class HxTokenManagerTest extends Specification { tokenManager.getAuth(originalAuth) when: 'a token refresh updates the stored auth' - def refreshedAuth = originalAuth.withToken('refreshed.jwt.token').withRefresh('refresh2') + def refreshedAuth = originalAuth.withAccessToken('refreshed.jwt.token').withRefreshToken('refresh2') store.put(originalAuth.id(), refreshedAuth) and: 'a new stateless request creates auth from the same original credentials'