Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
180 changes: 125 additions & 55 deletions lib-httpx/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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();
Expand Down Expand Up @@ -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

Expand All @@ -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
Expand All @@ -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<String> response1 = client.send(request, user1Auth, HttpResponse.BodyHandlers.ofString());
HttpResponse<String> response2 = client.send(request, user2Auth, HttpResponse.BodyHandlers.ofString());

// Async requests also supported
CompletableFuture<HttpResponse<String>> 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
Expand Down Expand Up @@ -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();
```
Expand All @@ -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
Expand Down
86 changes: 86 additions & 0 deletions lib-httpx/src/main/java/io/seqera/http/DefaultHxAuth.java
Original file line number Diff line number Diff line change
@@ -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}.
*
* <p>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 <paolo.ditommaso@gmail.com>
*/
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);
}
}
Loading