diff --git a/lib-httpx/README.md b/lib-httpx/README.md index aec7cf95..7d1ec889 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 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 - **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 @@ -61,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(); @@ -97,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 @@ -118,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 @@ -139,6 +138,109 @@ 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 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) | +| `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 — `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 + +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 { + 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 withAccessToken(String token) { + return new TenantAuth(tenantId, token, refreshToken); + } + + @Override + public HxAuth withRefreshToken(String refresh) { + 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 + +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 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 remove(String key) { /* Redis DEL */ } +} + +// Use custom store +HxTokenStore customStore = new RedisTokenStore(); +HxClient client = HxClient.newBuilder() + .tokenStore(customStore) + .build(); +``` + ### Custom Retry Configuration ```java @@ -181,45 +283,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(); ``` @@ -238,31 +310,29 @@ 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 | +| `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 -- **`HxTokenManager`**: Thread-safe JWT token lifecycle management +- **`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 +- **`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 - **`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 new file mode 100644 index 00000000..1d49e8d4 --- /dev/null +++ b/lib-httpx/src/main/java/io/seqera/http/DefaultHxAuth.java @@ -0,0 +1,86 @@ +/* + * 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.time.Instant; +import java.util.Objects; + +/** + * Default immutable implementation of {@link HxAuth}. + * + *

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 #withAccessToken(String)} + * and {@link #withRefreshToken(String)}. + * + * @author Paolo Di Tommaso + */ +record DefaultHxAuth(String id, String accessToken, String refreshToken, String refreshUrl, Instant createdAt, Instant updatedAt) 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(computeId(accessToken, refreshUrl), accessToken, refreshToken, refreshUrl, Instant.now(), Instant.now()); + } + + DefaultHxAuth(String accessToken, String refreshToken) { + this(accessToken, refreshToken, null); + } + + @Override + public HxAuth withAccessToken(String token) { + return new DefaultHxAuth(id, token, refreshToken, refreshUrl, createdAt, Instant.now()); + } + + @Override + public HxAuth withRefreshToken(String refresh) { + return new DefaultHxAuth(id, accessToken, refresh, refreshUrl, createdAt, Instant.now()); + } + + @Override + public String toString() { + return "HxAuth[" + + "id=" + id + + ", accessToken=" + mask(accessToken) + + ", refreshToken=" + mask(refreshToken) + + ", refreshUrl=" + refreshUrl + + ']'; + } + + 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 "***"; + 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 new file mode 100644 index 00000000..0069f287 --- /dev/null +++ b/lib-httpx/src/main/java/io/seqera/http/HxAuth.java @@ -0,0 +1,85 @@ +/* + * 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 JWT authentication credentials. + * + *

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

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}. + * + * @author Paolo Di Tommaso + */ +public interface HxAuth { + + /** + * Returns the JWT access token. + * + * @return the access token, never null + */ + String accessToken(); + + /** + * Returns the refresh token. + * + * @return the refresh token, or null if not set + */ + String refreshToken(); + + /** + * Returns the refresh URL for this auth context. + * + * @return the refresh URL, or null to use the global config default + */ + String refreshUrl(); + + /** + * 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 #withAccessToken(String)} or + * {@link #withRefreshToken(String)} updates. + * + * @return the stable identifier + */ + String id(); + + /** + * Returns an {@link HxAuth} with the given access token. + * + * @param token the new access token + * @return an {@link HxAuth} with the updated token + */ + HxAuth withAccessToken(String token); + + /** + * Returns an {@link HxAuth} with the given refresh token. + * + * @param refresh the new refresh token + * @return an {@link HxAuth} with the updated refresh token + */ + HxAuth withRefreshToken(String refresh); + +} 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..704e108a 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,47 @@ 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. + */ + 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. + */ + protected CompletableFuture> sendWithRetryAsync( + HttpRequest request, + HttpResponse.BodyHandler responseBodyHandler, + Executor executor) { + 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 { + final HxAuth effective = (auth != null) ? auth : tokenManager.getDefaultAuth(); + return effective != null && tokenManager.getOrRefreshTokenAsync(effective).get() != null; + } + + /** + * Internal method that implements the retry logic for synchronous requests. + * *

This method handles the core retry functionality including: *

    *
  • Adding authentication headers
  • @@ -330,51 +463,50 @@ public CompletableFuture> sendAsync(HttpRequest request, *
  • Attempting token refresh on 401 responses
  • *
  • Re-executing requests with refreshed tokens
  • *
- * + * * @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 = applyAuthHeader(request, auth); 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 + if (canRefreshToken(auth)) { + final String debugKey = auth.id(); + log.debug("Received 401 status for auth key {}, attempting token refresh", debugKey); try { - if (tokenManager.getOrRefreshTokenAsync().get()) { + if (refreshToken(auth)) { tokenRefreshed[0] = true; - final HttpRequest refreshedRequest = 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: " + e.getMessage()); + log.warn("Token refresh failed for auth key {}: {}", debugKey, 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 +514,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 +529,57 @@ protected HttpResponse sendWithRetry(HttpRequest request, HttpResponse.Bo *
  • Attempting token refresh on 401 responses
  • *
  • Re-executing requests with refreshed tokens
  • *
- * + * * @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 = applyAuthHeader(request, auth); 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 + if (canRefreshToken(auth)) { + final String debugKey = auth.id(); + log.debug("Received 401 status in async call for auth key {}, attempting token refresh", debugKey); try { - final boolean refreshed = tokenManager.getOrRefreshTokenAsync().get(); - if (refreshed) { + if (refreshToken(auth)) { tokenRefreshed[0] = true; - final HttpRequest refreshedRequest = 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: " + e.getMessage()); + log.warn("Async token refresh failed for auth key {}: {}", debugKey, 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 +587,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 +989,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 +1276,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 +1312,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..8240b036 --- /dev/null +++ b/lib-httpx/src/main/java/io/seqera/http/HxMapTokenStore.java @@ -0,0 +1,56 @@ +/* + * 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 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 29322853..ed876c9f 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; @@ -43,11 +45,11 @@ *

  • 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:
    - * 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. @@ -61,73 +63,67 @@ *
    * *

    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: *

    {@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 * @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_TOKEN + final String jwtToken = config.getJwtToken(); + final String refreshToken = config.getRefreshToken(); + if (jwtToken != null && !jwtToken.isEmpty()) { + tokenStore.put(DEFAULT_TOKEN, new DefaultHxAuth(jwtToken, refreshToken, config.getRefreshTokenUrl())); + } + // 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(); } /** @@ -145,8 +141,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 @@ -204,69 +202,31 @@ 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; } /** * 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; + 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() { - if (!canRefreshToken()) { - log.warn("Cannot refresh token: refreshToken={} refreshTokenUrl={}", (currentRefreshToken != null), config.getRefreshTokenUrl()); - return false; - } - - lock.writeLock().lock(); - try { - return doRefreshToken(); - } finally { - lock.writeLock().unlock(); - } - } - - /** - * 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,214 +235,46 @@ 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 - */ - public CompletableFuture getOrRefreshTokenAsync() { - if (!canRefreshToken()) { - log.warn("Cannot refresh token: refreshToken={} refreshTokenUrl={}", (currentRefreshToken != null), config.getRefreshTokenUrl()); - return CompletableFuture.completedFuture(false); - } - - // 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; - } - } - - /** - * 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()); - return CompletableFuture.completedFuture(false); - } - - return CompletableFuture.supplyAsync(() -> { - lock.writeLock().lock(); - try { - return doRefreshToken(); - } finally { - lock.writeLock().unlock(); - } - }); - } - - /** - * 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. - * - * @return true if the token 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 */ - 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; + 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); } - } - /** - * 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; + final String key = auth.id(); + + // 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); + 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)); } - } - } 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); - return false; - } + }); + return future; + }); } /** - * 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; } @@ -512,44 +304,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(); - } - } - - /** - * 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(); + final HxAuth auth = tokenStore.get(DEFAULT_TOKEN); + return auth != null ? auth.refreshToken() : null; } /** @@ -567,29 +338,211 @@ public boolean hasBasicAuth() { !":".equals(config.getBasicAuthToken()); } + // ======================================================================== + // Multi-user token management methods + // ======================================================================== + /** - * Updates both JWT and refresh tokens atomically in a thread-safe manner. - * - *

    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 + * 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; + } + final String key = auth.id(); + return tokenStore.putIfAbsent(key, auth); + } + + /** + * 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; + } + // 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; + } + + /** + * 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 */ - public void updateTokens(String jwtToken, String refreshToken) { - lock.writeLock().lock(); + private String resolveRefreshUrl(HxAuth auth) { + if (auth != null && auth.refreshUrl() != null) { + return auth.refreshUrl(); + } + return config.getRefreshTokenUrl(); + } + + /** + * 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.id(), 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 { + 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 + 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); + + 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, cookieManager, 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()); + } + 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 cookieManager the cookie manager used for the refresh request + * @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 auth) { + // Try cookies first + final String newToken = extractTokenFromCookies(cookieManager); + if (newToken != null) { + final String newRefresh = extractRefreshFromCookies(cookieManager); + HxAuth result = auth.withAccessToken(newToken); + if (newRefresh != null) { + result = result.withRefreshToken(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 { - if (jwtToken != null && isValidJwtToken(jwtToken)) { - this.currentJwtToken = jwtToken; - log.trace("JWT token updated"); + final JsonObject json = JsonParser.parseString(response.body()).getAsJsonObject(); + if (!json.has("access_token")) { + return null; } - if (refreshToken != null) { - this.currentRefreshToken = refreshToken; - log.trace("Refresh token updated"); + final String accessToken = json.get("access_token").getAsString(); + if (!isValidJwtToken(accessToken)) { + return null; } - } finally { - lock.writeLock().unlock(); + HxAuth result = auth.withAccessToken(accessToken); + if (json.has("refresh_token")) { + result = result.withRefreshToken(json.get("refresh_token").getAsString()); + } + return result; + } catch (Exception e) { + log.trace("Response is not valid JSON"); + return null; } } + + /** + * 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..b36867ab --- /dev/null +++ b/lib-httpx/src/main/java/io/seqera/http/HxTokenStore.java @@ -0,0 +1,73 @@ +/* + * 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 {@link HxAuth} instances by key. + * + *

    This interface allows for different storage strategies for managing + * 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. + * + * @author Paolo Di Tommaso + */ +public interface HxTokenStore { + + /** + * Retrieves the authentication data for the given key. + * + * @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); + + /** + * Stores the authentication data for the given key. + * + * @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); + + /** + * 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 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 + */ + HxAuth putIfAbsent(String key, HxAuth auth); + + /** + * Removes the authentication data for the given key. + * + * @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); +} 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..3c4863ca --- /dev/null +++ b/lib-httpx/src/test/groovy/io/seqera/http/HxAuthTest.groovy @@ -0,0 +1,111 @@ +/* + * 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 = 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 = new DefaultHxAuth('my.jwt.token', 'my-refresh-token') + + then: + auth.accessToken() == 'my.jwt.token' + auth.refreshToken() == 'my-refresh-token' + auth.refreshUrl() == null + } + + 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') + + then: + auth.accessToken() == 'my.jwt.token' + auth.refreshToken() == 'my-refresh-token' + auth.refreshUrl() == 'https://example.com/oauth/token' + } + + 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() // 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.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'() { + when: + new DefaultHxAuth(null, null) + + then: + thrown(IllegalArgumentException) + } + + def 'should reject null access token with refresh'() { + when: + new DefaultHxAuth(null, 'refresh') + + then: + thrown(IllegalArgumentException) + } + + def 'should mask tokens in toString'() { + when: + def auth = new DefaultHxAuth('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 'same credentials should produce same id'() { + given: + def auth1 = new DefaultHxAuth('a.b.c', 'r1') + def auth2 = new DefaultHxAuth('a.b.c', 'r2') + + expect: + 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 d4ad1865..9f49d1c0 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'() { @@ -384,4 +382,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.tokenStore == 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..49049b00 --- /dev/null +++ b/lib-httpx/src/test/groovy/io/seqera/http/HxMapTokenStoreTest.groovy @@ -0,0 +1,85 @@ +/* + * 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 HxMapTokenStore + * + * @author Paolo Di Tommaso + */ +class HxMapTokenStoreTest extends Specification { + + def 'should store and retrieve auth by key'() { + given: + def store = new HxMapTokenStore() + def auth = new DefaultHxAuth('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 = new DefaultHxAuth('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 + } + + def 'putIfAbsent should store and return auth when key is absent'() { + given: + def store = new HxMapTokenStore() + def auth = new DefaultHxAuth('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 = new DefaultHxAuth('existing.jwt.token', 'refresh1') + def newAuth = new DefaultHxAuth('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 73b76902..f24e8252 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 @@ -123,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() @@ -225,59 +191,139 @@ 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() - + def tokenManager = new HxTokenManager(config) + + then: + // Cookie managers are now created per-refresh operation; + // this verifies the configuration is accepted without errors + noExceptionThrown() + tokenManager != null + } + + 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 - // 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 noExceptionThrown() + tokenManager != null } - - def 'should use default cookie policy when none provided'() { + + // --- Multi-token support tests --- + + def 'getAuth should store and return auth on first call'() { given: def config = HxConfig.newBuilder().build() - - when: def tokenManager = new HxTokenManager(config) - + def auth = new DefaultHxAuth('my.jwt.token', 'refresh') + + when: + def result = tokenManager.getAuth(auth) + then: - tokenManager.cookieManager != null - tokenManager.cookieManager instanceof CookieManager - // This verifies that the default CookieManager construction works - noExceptionThrown() + result == auth + tokenManager.getAuth(auth) == auth // subsequent calls return same } - - def 'should create different cookie managers for different policies'() { + + def 'getAuth should return null for null input'() { given: - def configAcceptAll = HxConfig.newBuilder() - .refreshCookiePolicy(CookiePolicy.ACCEPT_ALL) + 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 = new DefaultHxAuth('custom.jwt.token', 'refresh') + def request = HttpRequest.newBuilder() + .uri(URI.create('https://example.com/api')) + .GET() .build() - def configAcceptNone = HxConfig.newBuilder() - .refreshCookiePolicy(CookiePolicy.ACCEPT_NONE) + + 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 configDefault = HxConfig.newBuilder().build() - + def configWithoutUrl = HxConfig.newBuilder().build() + + expect: + // 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 + // 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'() { + given: + def customStore = new HxMapTokenStore() + def config = HxConfig.newBuilder().build() + def tokenManager = new HxTokenManager(config, customStore) + def auth = new DefaultHxAuth('my.jwt.token', 'refresh') + when: - def tokenManager1 = new HxTokenManager(configAcceptAll) - def tokenManager2 = new HxTokenManager(configAcceptNone) - def tokenManager3 = new HxTokenManager(configDefault) - + tokenManager.getAuth(auth) + 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 + customStore.get(auth.id()) == auth + } + + 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.withAccessToken('refreshed.jwt.token').withRefreshToken('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' } }