diff --git a/sdk/src/main/java/io/opentdf/platform/sdk/DPoPMode.java b/sdk/src/main/java/io/opentdf/platform/sdk/DPoPMode.java new file mode 100644 index 00000000..a481f6bb --- /dev/null +++ b/sdk/src/main/java/io/opentdf/platform/sdk/DPoPMode.java @@ -0,0 +1,31 @@ +package io.opentdf.platform.sdk; + +/** + * Selects the {@code htu} form of DPoP proofs sent to platform services and KAS. Both forms use + * the {@code DPoP} Authorization scheme, and token endpoint proofs always use the full URL. + * Plain Bearer tokens (an AS that did not bind the token to the DPoP key) are unaffected + * and are always sent as {@code Authorization: Bearer} without a proof. + */ +public enum DPoPMode { + /** + * Discover the style per server origin from what the server advertises: the + * {@code dpop} block or {@code dpop_signing_alg_values_supported} in the opentdf well-known + * configuration ({@code WellKnownService/GetWellKnownConfiguration}), then RFC 9728 + * {@code /.well-known/oauth-protected-resource}. Servers that advertise neither get + * {@link #LEGACY}. A discovery that gets no usable answer (a network error, timeout, redirect, + * or a status other than 200, 404, 405 and 501) uses legacy for 30 seconds before the server is + * asked again. Answers are cached per origin for a few minutes, then rediscovered, so a server + * that is upgraded or reconfigured is picked up without restarting the client. This is the + * default. + */ + AUTO, + /** + * Pre-RFC 9449 form that service releases before v0.18.0 require: an RPC's {@code htu} is its + * procedure ({@code /package.Service/Method}). + */ + LEGACY, + /** + * RFC 9449 form: the {@code htu} is the full request URL without query or fragment. + */ + RFC9449 +} diff --git a/sdk/src/main/java/io/opentdf/platform/sdk/DPoPModeResolver.java b/sdk/src/main/java/io/opentdf/platform/sdk/DPoPModeResolver.java new file mode 100644 index 00000000..312b2669 --- /dev/null +++ b/sdk/src/main/java/io/opentdf/platform/sdk/DPoPModeResolver.java @@ -0,0 +1,322 @@ +package io.opentdf.platform.sdk; + +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; +import com.google.gson.JsonParseException; +import com.google.gson.JsonParser; +import com.google.protobuf.Struct; +import com.google.protobuf.Value; +import okhttp3.Call; +import okhttp3.MediaType; +import okhttp3.OkHttpClient; +import okhttp3.Request; +import okhttp3.RequestBody; +import okhttp3.Response; +import okhttp3.ResponseBody; +import okio.BufferedSource; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import javax.annotation.Nullable; +import java.io.IOException; +import java.net.URL; +import java.time.Duration; +import java.util.Map; +import java.util.Objects; +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.ExecutionException; +import java.util.concurrent.RejectedExecutionException; +import java.util.concurrent.TimeUnit; +import java.util.function.LongSupplier; + +/** + * Decides, per server origin, whether DPoP proofs for resource requests use the RFC 9449 htu or + * the legacy htu older platforms expect (see {@link DPoPMode}). Follows the same rules as the Go + * SDK's {@code sdk/auth/dpop_mode.go}. It is thread-safe. + * + *

In {@link DPoPMode#AUTO} an origin's answer is cached for a TTL (default + * {@link #DEFAULT_CACHE_TTL}; zero disables the cache), since the KAS, gateway, and IdP in front of + * an origin can change independently of a long-lived client. A discovery that got no usable answer + * from the well-known configuration (and no RFC 9728 advertisement) falls back to legacy for + * {@link #RETRY_INTERVAL} before the origin is asked again. Concurrent requests to an origin share + * one discovery, which runs off the caller's thread so a cancelled caller doesn't abort it. + */ +class DPoPModeResolver { + static final String WELL_KNOWN_CONFIGURATION_PROCEDURE = + "/wellknownconfiguration.WellKnownService/GetWellKnownConfiguration"; + static final String PROTECTED_RESOURCE_PATH = "/.well-known/oauth-protected-resource"; + static final Duration DEFAULT_CACHE_TTL = Duration.ofMinutes(5); + static final Duration RETRY_INTERVAL = Duration.ofSeconds(30); + static final Duration DISCOVERY_TIMEOUT = Duration.ofSeconds(10); + private static final String DPOP_ALGS_KEY = "dpop_signing_alg_values_supported"; + private static final long MAX_DOCUMENT_BYTES = 1 << 20; + private static final MediaType JSON = MediaType.get("application/json"); + + private static final Logger logger = LoggerFactory.getLogger(DPoPModeResolver.class); + + private final DPoPMode configured; + @Nullable + private final OkHttpClient discoveryClient; + private final long cacheTtlNanos; + private final long discoveryTimeoutNanos; + private final LongSupplier nanoClock; + // Resolved answers only (never AUTO), keyed by origin (scheme://host:port) + private final Map modeByOrigin = new ConcurrentHashMap<>(); + private final Map> discoveries = new ConcurrentHashMap<>(); + + private static final class CachedMode { + final DPoPMode mode; + final long expiresAtNanos; + + CachedMode(DPoPMode mode, long expiresAtNanos) { + this.mode = mode; + this.expiresAtNanos = expiresAtNanos; + } + } + + /** The outcome of asking an origin whether it accepts RFC 9449 proofs. */ + private static final class Discovery { + final DPoPMode mode; + // False when the well-known configuration got no usable answer and RFC 9728 metadata did + // not advertise support, so the legacy fallback is only kept for RETRY_INTERVAL. + final boolean conclusive; + @Nullable + final IOException wellKnownError; + @Nullable + final IOException resourceError; + + Discovery(DPoPMode mode, boolean conclusive, @Nullable IOException wellKnownError, + @Nullable IOException resourceError) { + this.mode = mode; + this.conclusive = conclusive; + this.wellKnownError = wellKnownError; + this.resourceError = resourceError; + } + } + + /** + * @param configured the requested mode; anything other than AUTO is used as-is + * @param httpClient client used for discovery. It must not carry the SDK's auth + * interceptors: discovery requests are sent without Authorization or DPoP. + * May be null when {@code configured} is not AUTO. + */ + DPoPModeResolver(DPoPMode configured, @Nullable OkHttpClient httpClient) { + this(configured, httpClient, DEFAULT_CACHE_TTL, System::nanoTime, DISCOVERY_TIMEOUT); + } + + /** + * As above, with a cache lifetime ({@link Duration#ZERO} disables caching), the clock that + * ages cache entries, and the time limit for one discovery. + */ + DPoPModeResolver(DPoPMode configured, @Nullable OkHttpClient httpClient, Duration cacheTtl, + LongSupplier nanoClock, Duration discoveryTimeout) { + this.configured = Objects.requireNonNull(configured, "configured"); + if (configured == DPoPMode.AUTO && httpClient == null) { + throw new IllegalArgumentException("DPoP mode discovery requires an HTTP client"); + } + // A redirect is not the origin's own answer. + this.discoveryClient = httpClient == null ? null + : httpClient.newBuilder().followRedirects(false).followSslRedirects(false).build(); + this.cacheTtlNanos = cacheTtl.toNanos(); + this.nanoClock = Objects.requireNonNull(nanoClock, "nanoClock"); + this.discoveryTimeoutNanos = discoveryTimeout.toNanos(); + } + + static DPoPModeResolver fixed(DPoPMode mode) { + if (mode == DPoPMode.AUTO) { + throw new IllegalArgumentException("a fixed DPoP mode cannot be AUTO"); + } + return new DPoPModeResolver(mode, null); + } + + /** + * Whether an opentdf well-known configuration advertises RFC 9449. A {@code dpop} block with a + * boolean {@code rfc9449} decides the answer; otherwise a non-empty + * {@code dpop_signing_alg_values_supported} means support, since every release that publishes + * it (service v0.18.0+) accepts a full-URL htu. A false result does not rule out support + * advertised through RFC 9728 metadata. + */ + static boolean advertisesRfc9449(JsonObject config) { + JsonElement dpop = config.get("dpop"); + if (dpop != null && dpop.isJsonObject()) { + JsonElement rfc9449 = dpop.getAsJsonObject().get("rfc9449"); + if (rfc9449 != null && rfc9449.isJsonPrimitive() && rfc9449.getAsJsonPrimitive().isBoolean()) { + return rfc9449.getAsBoolean(); + } + } + return hasNonEmptyArray(config, DPOP_ALGS_KEY); + } + + /** As {@link #advertisesRfc9449(JsonObject)}, for the configuration the SDK bootstraps from. */ + static boolean advertisesRfc9449(Struct config) { + Value dpop = config.getFieldsOrDefault("dpop", null); + if (dpop != null && dpop.hasStructValue()) { + Value rfc9449 = dpop.getStructValue().getFieldsOrDefault("rfc9449", null); + if (rfc9449 != null && rfc9449.hasBoolValue()) { + return rfc9449.getBoolValue(); + } + } + Value algs = config.getFieldsOrDefault(DPOP_ALGS_KEY, null); + return algs != null && algs.hasListValue() && algs.getListValue().getValuesCount() > 0; + } + + /** + * Record that the server at {@code url} accepts RFC 9449, e.g. from the well-known + * configuration the SDK already fetched. Only positives are seeded: a server that omits the + * well-known advertisement may still publish RFC 9728 metadata. + */ + void recordRfc9449(URL url) { + if (configured == DPoPMode.AUTO) { + cache(TokenSource.getOrigin(url), DPoPMode.RFC9449, cacheTtlNanos); + } + } + + /** + * @return {@link DPoPMode#RFC9449} or {@link DPoPMode#LEGACY} for the URL's origin. In AUTO this + * may block on discovery, which is bounded by the discovery timeout. + * @throws SDKException if the thread is interrupted while waiting for discovery + */ + DPoPMode modeFor(URL url) { + if (configured != DPoPMode.AUTO) { + return configured; + } + String origin = TokenSource.getOrigin(url); + CachedMode known = modeByOrigin.get(origin); + // Compare by difference: nanoTime values may wrap. + if (known != null && nanoClock.getAsLong() - known.expiresAtNanos < 0) { + return known.mode; + } + + CompletableFuture pending = new CompletableFuture<>(); + CompletableFuture shared = discoveries.putIfAbsent(origin, pending); + if (shared == null) { + shared = pending; + try { + discoveryClient.dispatcher().executorService().execute(() -> discoverAndCache(origin, pending)); + } catch (RejectedExecutionException e) { + // The client is shutting down; discover on this thread instead. + discoverAndCache(origin, pending); + } + } + try { + return shared.get(); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + throw new SDKException("interrupted while discovering the DPoP style of " + origin, e); + } catch (ExecutionException e) { + throw new SDKException("DPoP style discovery failed for " + origin, e); + } + } + + private void discoverAndCache(String origin, CompletableFuture result) { + try { + Discovery d = discover(origin); + cache(origin, d.mode, d.conclusive ? cacheTtlNanos + : Math.min(RETRY_INTERVAL.toNanos(), cacheTtlNanos)); + if (logger.isDebugEnabled()) { + logger.debug("discovered DPoP htu form for {}: {} (conclusive={}, well-known error={}," + + " protected-resource error={})", + origin, d.mode, d.conclusive, d.wellKnownError, d.resourceError); + } + result.complete(d.mode); + } catch (RuntimeException e) { + result.completeExceptionally(e); + } finally { + discoveries.remove(origin, result); + } + } + + private void cache(String origin, DPoPMode mode, long ttlNanos) { + modeByOrigin.put(origin, new CachedMode(mode, nanoClock.getAsLong() + ttlNanos)); + } + + /** + * Ask the server at {@code origin} whether it accepts RFC 9449 proofs: the opentdf well-known + * configuration, then RFC 9728 metadata if that doesn't advertise support. Neither request + * carries credentials or a proof: a client can't authenticate in a DPoP form it hasn't chosen. + */ + private Discovery discover(String origin) { + long deadline = System.nanoTime() + discoveryTimeoutNanos; + + IOException wellKnownError = null; + try { + Request request = new Request.Builder() + .url(origin + WELL_KNOWN_CONFIGURATION_PROCEDURE) + .post(RequestBody.create("{}", JSON)) + .header("Connect-Protocol-Version", "1") + .build(); + JsonObject wellKnown = fetchJson(request, deadline); + if (wellKnown != null) { + JsonElement configuration = wellKnown.get("configuration"); + if (configuration != null && configuration.isJsonObject() + && advertisesRfc9449(configuration.getAsJsonObject())) { + return new Discovery(DPoPMode.RFC9449, true, null, null); + } + } + } catch (IOException e) { + wellKnownError = e; + } + + IOException resourceError = null; + try { + JsonObject metadata = fetchJson( + new Request.Builder().url(origin + PROTECTED_RESOURCE_PATH).get().build(), deadline); + if (metadata != null && hasNonEmptyArray(metadata, DPOP_ALGS_KEY)) { + return new Discovery(DPoPMode.RFC9449, true, wellKnownError, null); + } + } catch (IOException e) { + resourceError = e; + } + + // RFC 9728 is new, so its absence says little. Only conclude "legacy" once the well-known + // configuration itself has answered. + return new Discovery(DPoPMode.LEGACY, wellKnownError == null, wellKnownError, resourceError); + } + + /** + * Send a discovery request. + * + * @return the JSON object, or null when the server definitively serves no such document: HTTP + * 404, 405 or 501, or a 200 whose body isn't a JSON object (e.g. a catch-all page) + * @throws IOException when the server gave no usable answer: a network error, timeout, + * redirect, a body over 1 MiB, or any other status (e.g. a gateway's 401 or 429, or a 5xx) + */ + @Nullable + private JsonObject fetchJson(Request request, long deadline) throws IOException { + long remaining = deadline - System.nanoTime(); + if (remaining <= 0) { + throw new IOException("DPoP discovery timed out before " + request.url()); + } + Call call = discoveryClient.newCall(request.newBuilder().header("Accept", "application/json").build()); + call.timeout().timeout(remaining, TimeUnit.NANOSECONDS); + try (Response response = call.execute()) { + int code = response.code(); + if (code == 404 || code == 405 || code == 501) { + return null; + } + if (code != 200) { + throw new IOException(request.method() + " " + request.url() + " returned HTTP " + code); + } + ResponseBody body = response.body(); + if (body == null) { + throw new IOException(request.method() + " " + request.url() + " returned no body"); + } + BufferedSource source = body.source(); + if (source.request(MAX_DOCUMENT_BYTES + 1)) { + throw new IOException(request.method() + " " + request.url() + " returned over " + + MAX_DOCUMENT_BYTES + " bytes"); + } + try { + return JsonParser.parseString(source.readUtf8()).getAsJsonObject(); + } catch (JsonParseException | IllegalStateException e) { + return null; + } + } + } + + private static boolean hasNonEmptyArray(JsonObject object, String key) { + JsonElement value = object.get(key); + return value != null && value.isJsonArray() && value.getAsJsonArray().size() > 0; + } +} diff --git a/sdk/src/main/java/io/opentdf/platform/sdk/SDKBuilder.java b/sdk/src/main/java/io/opentdf/platform/sdk/SDKBuilder.java index dda13258..77be44c7 100644 --- a/sdk/src/main/java/io/opentdf/platform/sdk/SDKBuilder.java +++ b/sdk/src/main/java/io/opentdf/platform/sdk/SDKBuilder.java @@ -45,6 +45,8 @@ import javax.net.ssl.TrustManager; import javax.net.ssl.X509TrustManager; import java.io.IOException; +import java.net.MalformedURLException; +import java.net.URL; import java.nio.file.Path; import java.security.GeneralSecurityException; import java.security.cert.X509Certificate; @@ -68,6 +70,7 @@ public class SDKBuilder { private SrtSigner srtSigner; private JWK dpopKey; private JWSAlgorithm dpopAlg; + private DPoPMode dpopMode = DPoPMode.AUTO; private static final Logger logger = LoggerFactory.getLogger(SDKBuilder.class); @@ -247,6 +250,24 @@ public SDKBuilder dpopKey(JWK dpopKey, JWSAlgorithm dpopAlg) { return this; } + /** + * Choose how DPoP-bound tokens are presented to platform services and KAS. The default, + * {@link DPoPMode#AUTO}, discovers per server whether it accepts RFC 9449 or only the legacy + * style of older platforms; set {@link DPoPMode#RFC9449} or {@link DPoPMode#LEGACY} to skip + * discovery. + * + * @param dpopMode the DPoP presentation mode + * @return this builder instance for method chaining + * @throws IllegalArgumentException if dpopMode is null + */ + public SDKBuilder dpopMode(DPoPMode dpopMode) { + if (dpopMode == null) { + throw new IllegalArgumentException("DPoPMode cannot be null"); + } + this.dpopMode = dpopMode; + return this; + } + private AuthInterceptor getAuthInterceptor(JWK dpopJwk, JWSAlgorithm dpopAlgorithm) { if (platformEndpoint == null) { throw new SDKException("cannot build an SDK without specifying the platform endpoint"); @@ -304,7 +325,18 @@ private AuthInterceptor getAuthInterceptor(JWK dpopJwk, JWSAlgorithm dpopAlgorit if (this.authzGrant == null) { this.authzGrant = new ClientCredentialsGrant(); } - var ts = new TokenSource(clientAuth, dpopJwk, dpopAlgorithm, providerMetadata.getTokenEndpointURI(), this.authzGrant, sslSocketFactory); + // Discovery reuses the unauthenticated bootstrap client so it never sends credentials. + var dpopModeResolver = new DPoPModeResolver(dpopMode, httpClient); + // Reuse the configuration fetched above rather than discovering the platform again. Only + // a positive is seeded: RFC 9728 metadata may still advertise. + if (DPoPModeResolver.advertisesRfc9449(config.getConfiguration())) { + try { + dpopModeResolver.recordRfc9449(new URL(platformEndpoint)); + } catch (MalformedURLException e) { + throw new SDKException("invalid platform endpoint: " + platformEndpoint, e); + } + } + var ts = new TokenSource(clientAuth, dpopJwk, dpopAlgorithm, providerMetadata.getTokenEndpointURI(), this.authzGrant, sslSocketFactory, dpopModeResolver); return new AuthInterceptor(ts); } diff --git a/sdk/src/main/java/io/opentdf/platform/sdk/TokenSource.java b/sdk/src/main/java/io/opentdf/platform/sdk/TokenSource.java index 52496f06..1dabb163 100644 --- a/sdk/src/main/java/io/opentdf/platform/sdk/TokenSource.java +++ b/sdk/src/main/java/io/opentdf/platform/sdk/TokenSource.java @@ -55,6 +55,7 @@ enum TokenScheme { private final URI tokenEndpointURI; private final AuthorizationGrant authzGrant; private final SSLSocketFactory sslSocketFactory; + private final DPoPModeResolver dpopModeResolver; // Cache for server-issued nonces, keyed by origin (scheme://host:port) private final Map nonceCache = new ConcurrentHashMap<>(); private static final Logger logger = LoggerFactory.getLogger(TokenSource.class); @@ -69,7 +70,18 @@ enum TokenScheme { * @param sslSocketFactory Optional SSLSocketFactory for token endpoint requests */ public TokenSource(ClientAuthentication clientAuth, JWK dpopJwk, JWSAlgorithm dpopAlg, URI tokenEndpointURI, AuthorizationGrant authzGrant, SSLSocketFactory sslSocketFactory) { + this(clientAuth, dpopJwk, dpopAlg, tokenEndpointURI, authzGrant, sslSocketFactory, + DPoPModeResolver.fixed(DPoPMode.RFC9449)); + } + + /** + * As above, choosing per resource-server origin between the RFC 9449 and legacy DPoP htu. + * + * @param dpopModeResolver decides the DPoP style for each request URL's origin + */ + TokenSource(ClientAuthentication clientAuth, JWK dpopJwk, JWSAlgorithm dpopAlg, URI tokenEndpointURI, AuthorizationGrant authzGrant, SSLSocketFactory sslSocketFactory, DPoPModeResolver dpopModeResolver) { DpopKeyValidation.validate(dpopJwk, dpopAlg); + this.dpopModeResolver = dpopModeResolver; this.clientAuth = clientAuth; this.dpopJwk = dpopJwk; this.dpopAlg = dpopAlg; @@ -121,9 +133,10 @@ public AuthHeaders getAuthHeaders(URL url, String method) { } /** - * Get authorization headers for a request. When the token is DPoP-bound this includes - * a freshly minted DPoP proof; if the AS issued a plain Bearer token the DPoP header is - * null (see the Bearer fallback below). + * Get authorization headers for a Connect/gRPC request. When the token is DPoP-bound this + * includes a freshly minted DPoP proof; if the AS issued a plain Bearer token the DPoP header + * is null. The proof's htu follows the {@link DPoPMode} resolved for the URL's origin: the full + * URL without query or fragment for RFC 9449, or the procedure path for legacy. * * @param url The URL being accessed * @param method The HTTP method @@ -131,6 +144,17 @@ public AuthHeaders getAuthHeaders(URL url, String method) { * @return AuthHeaders with the Authorization header, and a DPoP proof header when DPoP-bound */ public AuthHeaders getAuthHeaders(URL url, String method, String nonce) { + return getAuthHeaders(url, method, nonce, null); + } + + /** + * As {@link #getAuthHeaders(URL, String, String)}, optionally forcing the htu form. + * + * @param legacyHtu true for the legacy htu, false for RFC 9449, or null to use the mode + * resolved for the URL's origin. A nonce retry passes the form of the + * challenged proof so both attempts are signed the same way. + */ + AuthHeaders getAuthHeaders(URL url, String method, String nonce, @Nullable Boolean legacyHtu) { // Snapshot the token and its scheme together under getToken()'s lock so the // Authorization value and the DPoP/Bearer decision always come from the same // token generation. @@ -144,6 +168,8 @@ public AuthHeaders getAuthHeaders(URL url, String method, String nonce) { return new AuthHeaders(TokenScheme.BEARER.headerPrefix + " " + t.getValue(), null); } + boolean legacy = legacyHtu != null ? legacyHtu : dpopModeResolver.modeFor(url) == DPoPMode.LEGACY; + // Build the DPoP proof for each request String dpopProof; try { @@ -156,7 +182,7 @@ public AuthHeaders getAuthHeaders(URL url, String method, String nonce) { } SignedJWT proof; - URI htu = htuOf(url.toURI()); + URI htu = legacy ? legacyHtuOf(url.toURI()) : htuOf(url.toURI()); if (nonce != null) { proof = dpopFactory.createDPoPJWT(method, htu, t, new Nonce(nonce)); } else { @@ -169,6 +195,7 @@ public AuthHeaders getAuthHeaders(URL url, String method, String nonce) { throw new SDKException("Error creating DPoP proof", e); } + // The DPoP scheme is accepted by legacy servers too; only the htu differs. return new AuthHeaders( TokenScheme.DPOP.headerPrefix + " " + t.getValue(), dpopProof); @@ -196,8 +223,26 @@ private static URI htuOf(URI uri) { } } - /** Get the origin (scheme://host:port) from a URL, used as the nonce cache key. */ - private String getOrigin(URL url) { + // Servers before service v0.18.0 compare an RPC's htu against its procedure + // ("/package.Service/Method"), i.e. the last two path segments, which also drops any + // reverse-proxy prefix; they reject a full URL. Trailing slashes are ignored, and a path + // with fewer than two segments keeps the full URI. + private static URI legacyHtuOf(URI uri) { + String path = uri.getRawPath() == null ? "" : uri.getRawPath(); + int end = path.length(); + while (end > 0 && path.charAt(end - 1) == '/') { + end--; + } + int methodSeparator = path.lastIndexOf('/', end - 1); + if (methodSeparator <= 0) { + return htuOf(uri); + } + int serviceSeparator = path.lastIndexOf('/', methodSeparator - 1); + return URI.create("/" + path.substring(serviceSeparator + 1, end)); + } + + /** Get the origin (scheme://host:port) from a URL, used as the nonce and DPoP mode cache key. */ + static String getOrigin(URL url) { int port = url.getPort(); if (port == -1) { port = url.getDefaultPort(); diff --git a/sdk/src/main/kotlin/io/opentdf/platform/sdk/AuthInterceptor.kt b/sdk/src/main/kotlin/io/opentdf/platform/sdk/AuthInterceptor.kt index bcaac44b..aea48d87 100644 --- a/sdk/src/main/kotlin/io/opentdf/platform/sdk/AuthInterceptor.kt +++ b/sdk/src/main/kotlin/io/opentdf/platform/sdk/AuthInterceptor.kt @@ -123,7 +123,8 @@ internal class AuthInterceptor(private val ts: TokenSource) : Interceptor { if (dpopNonce != null) { response.close() ts.cacheNonce(url, dpopNonce) - val authHeaders = ts.getAuthHeaders(url, chain.request().method) + val authHeaders = ts.getAuthHeaders(url, chain.request().method, null, + legacyHtuOf(chain.request().header("DPoP"))) val newRequestBuilder = chain.request().newBuilder() .header("Authorization", authHeaders.authHeader) .removeHeader("DPoP") @@ -169,6 +170,18 @@ internal class AuthInterceptor(private val ts: TokenSource) : Interceptor { } } + // Whether the challenged proof used the legacy (path-only) htu, so the retry is signed the + // same way even if the origin's cached DPoP mode changed in between. Null when there was no + // readable proof, leaving the choice to the origin's mode. + private fun legacyHtuOf(dpopProof: String?): Boolean? { + if (dpopProof == null) return null + return try { + SignedJWT.parse(dpopProof).jwtClaimsSet.getStringClaim("htu")?.startsWith("/") + } catch (e: java.text.ParseException) { + null + } + } + private fun isDpopNonceChallenge(response: okhttp3.Response): Boolean { return response.challenges().any { challenge -> challenge.scheme.equals("DPoP", ignoreCase = true) && diff --git a/sdk/src/test/java/io/opentdf/platform/sdk/DPoPModeTest.java b/sdk/src/test/java/io/opentdf/platform/sdk/DPoPModeTest.java new file mode 100644 index 00000000..b4f90e00 --- /dev/null +++ b/sdk/src/test/java/io/opentdf/platform/sdk/DPoPModeTest.java @@ -0,0 +1,625 @@ +package io.opentdf.platform.sdk; + +import com.google.protobuf.ListValue; +import com.google.protobuf.Struct; +import com.google.protobuf.Value; +import com.nimbusds.jose.JWSAlgorithm; +import com.nimbusds.jose.jwk.KeyUse; +import com.nimbusds.jose.jwk.RSAKey; +import com.nimbusds.jose.jwk.gen.RSAKeyGenerator; +import com.nimbusds.jwt.JWTClaimsSet; +import com.nimbusds.jwt.SignedJWT; +import com.nimbusds.oauth2.sdk.ClientCredentialsGrant; +import com.nimbusds.oauth2.sdk.auth.ClientSecretBasic; +import com.nimbusds.oauth2.sdk.auth.Secret; +import com.nimbusds.oauth2.sdk.id.ClientID; +import okhttp3.OkHttpClient; +import okhttp3.Request; +import okhttp3.RequestBody; +import okhttp3.Response; +import okhttp3.mockwebserver.Dispatcher; +import okhttp3.mockwebserver.MockResponse; +import okhttp3.mockwebserver.MockWebServer; +import okhttp3.mockwebserver.RecordedRequest; +import okhttp3.mockwebserver.SocketPolicy; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.EnumSource; +import org.junit.jupiter.params.provider.ValueSource; + +import java.net.URL; +import java.time.Duration; +import java.util.List; +import java.util.Map; +import java.util.UUID; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.Future; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicReference; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.CopyOnWriteArrayList; +import java.util.concurrent.atomic.AtomicBoolean; +import java.util.concurrent.atomic.AtomicLong; + +import static io.opentdf.platform.sdk.DPoPModeResolver.WELL_KNOWN_CONFIGURATION_PROCEDURE; +import static io.opentdf.platform.sdk.DPoPModeResolver.PROTECTED_RESOURCE_PATH; +import static io.opentdf.platform.sdk.DPoPModeResolver.RETRY_INTERVAL; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +/** + * DSPX-5640: the SDK picks RFC 9449 or legacy DPoP headers from what each server advertises. + */ +class DPoPModeTest { + private static final String RPC_PATH = "/kas.AccessService/Rewrap"; + private static final String DPOP_TOKEN_RESPONSE = + "{\"access_token\":\"test-token\",\"token_type\":\"DPoP\",\"expires_in\":3600}"; + private static final String BEARER_TOKEN_RESPONSE = + "{\"access_token\":\"test-token\",\"token_type\":\"Bearer\",\"expires_in\":3600}"; + private static final String ALGS = "\"dpop_signing_alg_values_supported\":[\"ES256\",\"RS256\"]"; + + private static RSAKey rsaKey; + + private MockWebServer tokenServer; + private MockWebServer resourceServer; + // Well-known documents the resource server publishes, keyed by path; absent paths 404. + private final Map wellKnown = new ConcurrentHashMap<>(); + private final List discoveryRequests = new CopyOnWriteArrayList<>(); + private final AtomicBoolean challengeNextCall = new AtomicBoolean(); + private static final Duration TTL = Duration.ofMinutes(5); + // Starts near overflow so expiry checks must tolerate a wrapping nanoTime. + private final AtomicLong nanos = new AtomicLong(Long.MAX_VALUE - TTL.toNanos() / 2); + + @BeforeAll + static void generateKey() throws Exception { + rsaKey = new RSAKeyGenerator(2048).keyUse(KeyUse.SIGNATURE).keyID(UUID.randomUUID().toString()).generate(); + } + + @BeforeEach + void startServers() throws Exception { + tokenServer = new MockWebServer(); + tokenServer.setDispatcher(new Dispatcher() { + @Override + public MockResponse dispatch(RecordedRequest request) { + return json(DPOP_TOKEN_RESPONSE); + } + }); + tokenServer.start(); + + resourceServer = new MockWebServer(); + resourceServer.setDispatcher(new Dispatcher() { + @Override + public MockResponse dispatch(RecordedRequest request) { + String path = request.getPath(); + if (isDiscovery(path)) { + discoveryRequests.add(request); + return wellKnown.getOrDefault(path, new MockResponse().setResponseCode(404)); + } + if (challengeNextCall.getAndSet(false)) { + return new MockResponse() + .setResponseCode(401) + .addHeader("DPoP-Nonce", "server-nonce") + .addHeader("WWW-Authenticate", "DPoP error=\"use_dpop_nonce\""); + } + return new MockResponse().setResponseCode(200); + } + }); + resourceServer.start(); + } + + @AfterEach + void stopServers() throws Exception { + tokenServer.shutdown(); + resourceServer.shutdown(); + } + + @Test + void wellKnownDpopBlockOnly() { + wellKnown.put(WELL_KNOWN_CONFIGURATION_PROCEDURE, json("{\"configuration\":{\"dpop\":{\"rfc9449\":true}}}")); + assertThat(autoResolver().modeFor(rpcUrl())).isEqualTo(DPoPMode.RFC9449); + assertThat(discoveredPaths()).containsExactly(WELL_KNOWN_CONFIGURATION_PROCEDURE); + } + + @Test + void wellKnownDpopBlockOverridesTopLevelAlgs() { + wellKnown.put(WELL_KNOWN_CONFIGURATION_PROCEDURE, + json("{\"configuration\":{\"dpop\":{\"rfc9449\":false}," + ALGS + "}}")); + assertThat(autoResolver().modeFor(rpcUrl())).isEqualTo(DPoPMode.LEGACY); + } + + @Test + void dpopBlockWithoutABooleanFallsBackToAlgs() { + wellKnown.put(WELL_KNOWN_CONFIGURATION_PROCEDURE, + json("{\"configuration\":{\"dpop\":{\"rfc9449\":\"yes\"}," + ALGS + "}}")); + assertThat(autoResolver().modeFor(rpcUrl())).isEqualTo(DPoPMode.RFC9449); + + Struct noBool = Struct.newBuilder() + .putFields("dpop", Value.newBuilder().setStructValue(Struct.getDefaultInstance()).build()) + .putFields("dpop_signing_alg_values_supported", Value.newBuilder().setListValue( + ListValue.newBuilder().addValues(Value.newBuilder().setStringValue("ES256"))).build()) + .build(); + assertThat(DPoPModeResolver.advertisesRfc9449(noBool)).isTrue(); + } + + @Test + void declinedInWellKnownStillHonorsProtectedResourceMetadata() { + wellKnown.put(WELL_KNOWN_CONFIGURATION_PROCEDURE, json("{\"configuration\":{\"dpop\":{\"rfc9449\":false}}}")); + wellKnown.put(PROTECTED_RESOURCE_PATH, json("{" + ALGS + "}")); + assertThat(autoResolver().modeFor(rpcUrl())).isEqualTo(DPoPMode.RFC9449); + } + + @ParameterizedTest + @ValueSource(ints = {404, 405, 501}) + void wellKnownWithoutTheEndpointIsConclusive(int status) { + wellKnown.put(WELL_KNOWN_CONFIGURATION_PROCEDURE, new MockResponse().setResponseCode(status)); + assertCachedFor(TTL); + } + + @ParameterizedTest + @ValueSource(ints = {401, 403, 429, 500, 503}) + void wellKnownErrorStatusIsRetried(int status) { + wellKnown.put(WELL_KNOWN_CONFIGURATION_PROCEDURE, new MockResponse().setResponseCode(status)); + assertCachedFor(RETRY_INTERVAL); + } + + @Test + void wellKnownRedirectIsNotFollowedAndIsRetried() { + wellKnown.put(WELL_KNOWN_CONFIGURATION_PROCEDURE, + new MockResponse().setResponseCode(302).setHeader("Location", "/.well-known/elsewhere")); + wellKnown.put("/.well-known/elsewhere", json("{\"configuration\":{" + ALGS + "}}")); + assertCachedFor(RETRY_INTERVAL); + assertThat(discoveredPaths()).doesNotContain("/.well-known/elsewhere"); + } + + @Test + void oversizedWellKnownIsRetried() { + String padding = "x".repeat(1 << 20); + wellKnown.put(WELL_KNOWN_CONFIGURATION_PROCEDURE, + json("{\"configuration\":{" + ALGS + "},\"padding\":\"" + padding + "\"}")); + assertCachedFor(RETRY_INTERVAL); + } + + @Test + void discoveryTimesOut() { + wellKnown.put(WELL_KNOWN_CONFIGURATION_PROCEDURE, new MockResponse().setSocketPolicy(SocketPolicy.NO_RESPONSE)); + DPoPModeResolver resolver = new DPoPModeResolver(DPoPMode.AUTO, new OkHttpClient(), TTL, nanos::get, + Duration.ofMillis(200)); + long start = System.nanoTime(); + assertThat(resolver.modeFor(rpcUrl())).isEqualTo(DPoPMode.LEGACY); + assertThat(Duration.ofNanos(System.nanoTime() - start)).isLessThan(Duration.ofSeconds(5)); + // The deadline covers the whole discovery, so the metadata request is never sent. + assertThat(discoveredPaths()).containsExactly(WELL_KNOWN_CONFIGURATION_PROCEDURE); + } + + @Test + void concurrentFirstRequestsShareOneDiscovery() throws Exception { + wellKnown.put(WELL_KNOWN_CONFIGURATION_PROCEDURE, + json("{\"configuration\":{" + ALGS + "}}").setHeadersDelay(300, TimeUnit.MILLISECONDS)); + DPoPModeResolver resolver = autoResolver(); + ExecutorService pool = Executors.newFixedThreadPool(8); + try { + CountDownLatch start = new CountDownLatch(1); + List> results = new java.util.ArrayList<>(); + for (int i = 0; i < 8; i++) { + results.add(pool.submit(() -> { + start.await(); + return resolver.modeFor(rpcUrl()); + })); + } + start.countDown(); + for (Future result : results) { + assertThat(result.get(10, TimeUnit.SECONDS)).isEqualTo(DPoPMode.RFC9449); + } + } finally { + pool.shutdownNow(); + } + assertThat(discoveredPaths()).containsExactly(WELL_KNOWN_CONFIGURATION_PROCEDURE); + } + + @Test + void interruptedCallerFailsButDiscoveryCompletes() throws Exception { + wellKnown.put(WELL_KNOWN_CONFIGURATION_PROCEDURE, + json("{\"configuration\":{" + ALGS + "}}").setHeadersDelay(500, TimeUnit.MILLISECONDS)); + DPoPModeResolver resolver = autoResolver(); + AtomicReference failure = new AtomicReference<>(); + AtomicBoolean stillInterrupted = new AtomicBoolean(); + Thread caller = new Thread(() -> { + try { + resolver.modeFor(rpcUrl()); + } catch (SDKException e) { + failure.set(e); + stillInterrupted.set(Thread.currentThread().isInterrupted()); + } + }); + caller.start(); + Thread.sleep(100); + caller.interrupt(); + caller.join(5_000); + + assertThat(failure.get()).isInstanceOf(SDKException.class).hasCauseInstanceOf(InterruptedException.class); + assertThat(stillInterrupted).isTrue(); + // The shared discovery wasn't cancelled with the caller, and its answer is cached. + assertThat(resolver.modeFor(rpcUrl())).isEqualTo(DPoPMode.RFC9449); + assertThat(discoveredPaths()).containsExactly(WELL_KNOWN_CONFIGURATION_PROCEDURE); + } + + @Test + void wellKnownTopLevelAlgsOnly() { + wellKnown.put(WELL_KNOWN_CONFIGURATION_PROCEDURE, json("{\"configuration\":{\"platform_issuer\":\"x\"," + ALGS + "}}")); + assertThat(autoResolver().modeFor(rpcUrl())).isEqualTo(DPoPMode.RFC9449); + assertThat(discoveredPaths()).containsExactly(WELL_KNOWN_CONFIGURATION_PROCEDURE); + } + + @Test + void wellKnownEmptyAlgsIsNotAnAdvertisement() { + wellKnown.put(WELL_KNOWN_CONFIGURATION_PROCEDURE, + json("{\"configuration\":{\"dpop_signing_alg_values_supported\":[]}}")); + assertThat(autoResolver().modeFor(rpcUrl())).isEqualTo(DPoPMode.LEGACY); + assertThat(discoveredPaths()).containsExactly(WELL_KNOWN_CONFIGURATION_PROCEDURE, PROTECTED_RESOURCE_PATH); + } + + @Test + void protectedResourceMetadataOnly() { + wellKnown.put(WELL_KNOWN_CONFIGURATION_PROCEDURE, json("{\"configuration\":{\"platform_issuer\":\"x\"}}")); + wellKnown.put(PROTECTED_RESOURCE_PATH, json("{\"resource\":\"x\"," + ALGS + "}")); + assertThat(autoResolver().modeFor(rpcUrl())).isEqualTo(DPoPMode.RFC9449); + assertThat(discoveredPaths()).containsExactly(WELL_KNOWN_CONFIGURATION_PROCEDURE, PROTECTED_RESOURCE_PATH); + } + + @Test + void protectedResourceMetadataWithoutOpentdfConfiguration() { + wellKnown.put(PROTECTED_RESOURCE_PATH, json("{" + ALGS + "}")); + assertThat(autoResolver().modeFor(rpcUrl())).isEqualTo(DPoPMode.RFC9449); + } + + @Test + void bothAdvertisedStopsAtWellKnown() { + wellKnown.put(WELL_KNOWN_CONFIGURATION_PROCEDURE, json("{\"configuration\":{\"dpop\":{\"rfc9449\":true}," + ALGS + "}}")); + wellKnown.put(PROTECTED_RESOURCE_PATH, json("{" + ALGS + "}")); + assertThat(autoResolver().modeFor(rpcUrl())).isEqualTo(DPoPMode.RFC9449); + assertThat(discoveredPaths()).containsExactly(WELL_KNOWN_CONFIGURATION_PROCEDURE); + } + + @Test + void neitherAdvertisedSendsLegacyHeaders() throws Exception { + wellKnown.put(WELL_KNOWN_CONFIGURATION_PROCEDURE, json("{\"configuration\":{\"platform_issuer\":\"x\"}}")); + TokenSource ts = tokenSource(autoResolver()); + + // A reverse-proxy prefix is dropped: legacy servers compare against the procedure. + TokenSource.AuthHeaders headers = ts.getAuthHeaders(resourceServer.url("/proxy" + RPC_PATH).url(), "POST"); + + // Legacy keeps the DPoP scheme; only the htu changes. + assertThat(headers.getAuthHeader()).isEqualTo("DPoP test-token"); + JWTClaimsSet proof = SignedJWT.parse(headers.getDpopHeader()).getJWTClaimsSet(); + assertThat(proof.getStringClaim("htu")).isEqualTo(RPC_PATH); + assertThat(proof.getStringClaim("htm")).isEqualTo("POST"); + assertThat(proof.getStringClaim("ath")).isNotEmpty(); + // Paths too short to be a procedure keep the full URI. + URL shortPath = resourceServer.url("/kas").url(); + assertThat(htuOf(ts.getAuthHeaders(shortPath, "POST"))).isEqualTo(shortPath.toString()); + URL trailingSlashes = resourceServer.url("/proxy" + RPC_PATH + "///").url(); + assertThat(htuOf(ts.getAuthHeaders(trailingSlashes, "POST"))).isEqualTo(RPC_PATH); + // Discovery is unauthenticated and its definitive answer is cached per origin. + assertThat(discoveredPaths()).containsExactly(WELL_KNOWN_CONFIGURATION_PROCEDURE, PROTECTED_RESOURCE_PATH); + RecordedRequest configRequest = discoveryRequests.get(0); + assertThat(configRequest.getMethod()).isEqualTo("POST"); + assertThat(configRequest.getHeader("Connect-Protocol-Version")).isEqualTo("1"); + assertThat(configRequest.getBody().readUtf8()).isEqualTo("{}"); + assertThat(discoveryRequests.get(1).getMethod()).isEqualTo("GET"); + for (RecordedRequest r : discoveryRequests) { + assertThat(r.getHeader("Authorization")).isNull(); + assertThat(r.getHeader("DPoP")).isNull(); + } + } + + @Test + void advertisedSendsRfc9449Headers() throws Exception { + wellKnown.put(WELL_KNOWN_CONFIGURATION_PROCEDURE, json("{\"configuration\":{" + ALGS + "}}")); + URL url = resourceServer.url(RPC_PATH + "?q=1").url(); + + TokenSource.AuthHeaders headers = tokenSource(autoResolver()).getAuthHeaders(url, "POST"); + + assertThat(headers.getAuthHeader()).isEqualTo("DPoP test-token"); + JWTClaimsSet proof = SignedJWT.parse(headers.getDpopHeader()).getJWTClaimsSet(); + assertThat(proof.getStringClaim("htu")).isEqualTo(resourceServer.url(RPC_PATH).toString()); + assertThat(proof.getStringClaim("ath")).isNotEmpty(); + } + + @Test + void inconclusiveDiscoveryIsLegacyUntilTheRetryInterval() throws Exception { + wellKnown.put(WELL_KNOWN_CONFIGURATION_PROCEDURE, new MockResponse().setResponseCode(503)); + TokenSource ts = tokenSource(clockedResolver()); + + assertThat(htuOf(ts.getAuthHeaders(rpcUrl(), "POST"))).isEqualTo(RPC_PATH); + + // The 5xx was no answer, so the origin is asked again once the retry interval passes. + wellKnown.put(WELL_KNOWN_CONFIGURATION_PROCEDURE, json("{\"configuration\":{" + ALGS + "}}")); + nanos.addAndGet(RETRY_INTERVAL.toNanos() - 1); + assertThat(htuOf(ts.getAuthHeaders(rpcUrl(), "POST"))).isEqualTo(RPC_PATH); + nanos.addAndGet(1); + assertThat(htuOf(ts.getAuthHeaders(rpcUrl(), "POST"))).isEqualTo(rpcUrl().toString()); + assertThat(discoveredPaths()).containsExactly( + WELL_KNOWN_CONFIGURATION_PROCEDURE, PROTECTED_RESOURCE_PATH, WELL_KNOWN_CONFIGURATION_PROCEDURE); + } + + @Test + void discoveryFailureStillHonorsProtectedResourceMetadata() { + wellKnown.put(WELL_KNOWN_CONFIGURATION_PROCEDURE, new MockResponse().setResponseCode(503)); + wellKnown.put(PROTECTED_RESOURCE_PATH, json("{" + ALGS + "}")); + DPoPModeResolver resolver = autoResolver(); + assertThat(resolver.modeFor(rpcUrl())).isEqualTo(DPoPMode.RFC9449); + assertThat(resolver.modeFor(rpcUrl())).isEqualTo(DPoPMode.RFC9449); + assertThat(discoveredPaths()).containsExactly(WELL_KNOWN_CONFIGURATION_PROCEDURE, PROTECTED_RESOURCE_PATH); + } + + @Test + void protectedResourceFailureAfterAWellKnownAnswerIsConclusive() { + // RFC 9728 is new, so once the well-known configuration has answered, its errors don't matter. + wellKnown.put(PROTECTED_RESOURCE_PATH, new MockResponse().setResponseCode(503)); + DPoPModeResolver resolver = clockedResolver(); + assertThat(resolver.modeFor(rpcUrl())).isEqualTo(DPoPMode.LEGACY); + nanos.addAndGet(RETRY_INTERVAL.toNanos()); + assertThat(resolver.modeFor(rpcUrl())).isEqualTo(DPoPMode.LEGACY); + assertThat(discoveredPaths()).containsExactly(WELL_KNOWN_CONFIGURATION_PROCEDURE, PROTECTED_RESOURCE_PATH); + } + + @Test + void unreachableServerIsLegacy() throws Exception { + URL url = resourceServer.url(RPC_PATH).url(); + resourceServer.shutdown(); + assertThat(autoResolver().modeFor(url)).isEqualTo(DPoPMode.LEGACY); + } + + @Test + void unparseableDocumentIsDefinitivelyLegacy() { + wellKnown.put(WELL_KNOWN_CONFIGURATION_PROCEDURE, json("not json")); + DPoPModeResolver resolver = autoResolver(); + assertThat(resolver.modeFor(rpcUrl())).isEqualTo(DPoPMode.LEGACY); + assertThat(resolver.modeFor(rpcUrl())).isEqualTo(DPoPMode.LEGACY); + assertThat(discoveredPaths()).containsExactly(WELL_KNOWN_CONFIGURATION_PROCEDURE, PROTECTED_RESOURCE_PATH); + } + + @Test + void notFoundIsDefinitivelyLegacy() { + // service v0.11.x: no RFC 9449 advertisement anywhere. + DPoPModeResolver resolver = autoResolver(); + assertThat(resolver.modeFor(rpcUrl())).isEqualTo(DPoPMode.LEGACY); + assertThat(resolver.modeFor(rpcUrl())).isEqualTo(DPoPMode.LEGACY); + assertThat(discoveredPaths()).containsExactly(WELL_KNOWN_CONFIGURATION_PROCEDURE, PROTECTED_RESOURCE_PATH); + } + + @Test + void legacyAnswerExpiresSoAnUpgradedServerIsRediscovered() { + DPoPModeResolver resolver = clockedResolver(); + assertThat(resolver.modeFor(rpcUrl())).isEqualTo(DPoPMode.LEGACY); + + wellKnown.put(WELL_KNOWN_CONFIGURATION_PROCEDURE, json("{\"configuration\":{" + ALGS + "}}")); + nanos.addAndGet(TTL.toNanos() - 1); + assertThat(resolver.modeFor(rpcUrl())).isEqualTo(DPoPMode.LEGACY); + + nanos.addAndGet(1); + assertThat(resolver.modeFor(rpcUrl())).isEqualTo(DPoPMode.RFC9449); + assertThat(discoveredPaths()).containsExactly( + WELL_KNOWN_CONFIGURATION_PROCEDURE, PROTECTED_RESOURCE_PATH, WELL_KNOWN_CONFIGURATION_PROCEDURE); + } + + @Test + void rfc9449AnswerExpiresSoAReconfiguredServerIsRediscovered() { + wellKnown.put(PROTECTED_RESOURCE_PATH, json("{" + ALGS + "}")); + DPoPModeResolver resolver = clockedResolver(); + assertThat(resolver.modeFor(rpcUrl())).isEqualTo(DPoPMode.RFC9449); + + // E.g. the origin is now fronted by a legacy KAS or a gateway that no longer publishes metadata. + wellKnown.remove(PROTECTED_RESOURCE_PATH); + nanos.addAndGet(TTL.toNanos()); + assertThat(resolver.modeFor(rpcUrl())).isEqualTo(DPoPMode.LEGACY); + assertThat(resolver.modeFor(rpcUrl())).isEqualTo(DPoPMode.LEGACY); + assertThat(discoveredPaths()).containsExactly( + WELL_KNOWN_CONFIGURATION_PROCEDURE, PROTECTED_RESOURCE_PATH, + WELL_KNOWN_CONFIGURATION_PROCEDURE, PROTECTED_RESOURCE_PATH); + } + + @Test + void seededAnswerExpires() { + DPoPModeResolver resolver = clockedResolver(); + resolver.recordRfc9449(resourceServer.url("/").url()); + assertThat(resolver.modeFor(rpcUrl())).isEqualTo(DPoPMode.RFC9449); + assertThat(discoveryRequests).isEmpty(); + + nanos.addAndGet(TTL.toNanos()); + assertThat(resolver.modeFor(rpcUrl())).isEqualTo(DPoPMode.LEGACY); + assertThat(discoveredPaths()).containsExactly(WELL_KNOWN_CONFIGURATION_PROCEDURE, PROTECTED_RESOURCE_PATH); + } + + @Test + void bootstrapAdvertisementSeedsPlatformWithoutDiscovery() { + Struct algs = Struct.newBuilder().putFields("dpop_signing_alg_values_supported", + Value.newBuilder().setListValue(ListValue.newBuilder() + .addValues(Value.newBuilder().setStringValue("ES256"))).build()).build(); + Struct declined = Struct.newBuilder() + .putFields("dpop", Value.newBuilder().setStructValue(Struct.newBuilder() + .putFields("rfc9449", Value.newBuilder().setBoolValue(false).build())).build()) + .putAllFields(algs.getFieldsMap()) + .build(); + assertThat(DPoPModeResolver.advertisesRfc9449(algs)).isTrue(); + assertThat(DPoPModeResolver.advertisesRfc9449(declined)).isFalse(); + assertThat(DPoPModeResolver.advertisesRfc9449(Struct.getDefaultInstance())).isFalse(); + + DPoPModeResolver resolver = autoResolver(); + resolver.recordRfc9449(resourceServer.url("/").url()); + assertThat(resolver.modeFor(rpcUrl())).isEqualTo(DPoPMode.RFC9449); + assertThat(discoveryRequests).isEmpty(); + + DPoPModeResolver legacy = new DPoPModeResolver(DPoPMode.LEGACY, null); + legacy.recordRfc9449(resourceServer.url("/").url()); + assertThat(legacy.modeFor(rpcUrl())).isEqualTo(DPoPMode.LEGACY); + } + + @ParameterizedTest + @EnumSource(value = DPoPMode.class, names = {"LEGACY", "RFC9449"}) + void overrideSkipsDiscovery(DPoPMode mode) throws Exception { + // Advertise the opposite of the override to show the override wins. + if (mode == DPoPMode.LEGACY) { + wellKnown.put(WELL_KNOWN_CONFIGURATION_PROCEDURE, json("{\"configuration\":{" + ALGS + "}}")); + } + TokenSource ts = tokenSource(new DPoPModeResolver(mode, new OkHttpClient())); + + TokenSource.AuthHeaders headers = ts.getAuthHeaders(rpcUrl(), "POST"); + + assertThat(headers.getAuthHeader()).isEqualTo("DPoP test-token"); + assertThat(htuOf(headers)).isEqualTo(mode == DPoPMode.LEGACY ? RPC_PATH : rpcUrl().toString()); + assertThat(discoveryRequests).isEmpty(); + } + + @ParameterizedTest + @EnumSource(value = DPoPMode.class, names = {"LEGACY", "RFC9449"}) + void nonceChallengeIsRetriedInEachMode(DPoPMode expected) throws Exception { + if (expected == DPoPMode.RFC9449) { + wellKnown.put(WELL_KNOWN_CONFIGURATION_PROCEDURE, json("{\"configuration\":{" + ALGS + "}}")); + } + AuthInterceptor interceptor = new AuthInterceptor(tokenSource(autoResolver())); + OkHttpClient client = new OkHttpClient.Builder().addInterceptor(interceptor.dpopRetryInterceptor()).build(); + challengeNextCall.set(true); + + // Connect-shaped request, so the legacy retry signs the procedure htu. + Request request = new Request.Builder() + .url(resourceServer.url("/proxy" + RPC_PATH)) + .header("Connect-Protocol-Version", "1") + .post(RequestBody.create(new byte[0])) + .build(); + try (Response response = client.newCall(request).execute()) { + assertThat(response.code()).isEqualTo(200); + } + + RecordedRequest retry = lastNonDiscoveryRequest(); + assertThat(retry.getHeader("Authorization")).isEqualTo("DPoP test-token"); + JWTClaimsSet proof = SignedJWT.parse(retry.getHeader("DPoP")).getJWTClaimsSet(); + assertThat(proof.getStringClaim("nonce")).isEqualTo("server-nonce"); + assertThat(proof.getStringClaim("htu")).isEqualTo(expected == DPoPMode.LEGACY + ? RPC_PATH + : resourceServer.url("/proxy" + RPC_PATH).toString()); + } + + @Test + void nonceRetryKeepsTheChallengedProofsForm() throws Exception { + // The origin now advertises RFC 9449, but the challenged request was signed legacy. + wellKnown.put(WELL_KNOWN_CONFIGURATION_PROCEDURE, json("{\"configuration\":{" + ALGS + "}}")); + AuthInterceptor interceptor = new AuthInterceptor(tokenSource(autoResolver())); + OkHttpClient client = new OkHttpClient.Builder().addInterceptor(interceptor.dpopRetryInterceptor()).build(); + challengeNextCall.set(true); + URL url = resourceServer.url("/proxy" + RPC_PATH).url(); + TokenSource.AuthHeaders legacy = tokenSource(DPoPModeResolver.fixed(DPoPMode.LEGACY)).getAuthHeaders(url, "POST"); + + Request request = new Request.Builder() + .url(url) + .header("Authorization", legacy.getAuthHeader()) + .header("DPoP", legacy.getDpopHeader()) + .post(RequestBody.create(new byte[0])) + .build(); + try (Response response = client.newCall(request).execute()) { + assertThat(response.code()).isEqualTo(200); + } + + RecordedRequest retry = lastNonDiscoveryRequest(); + JWTClaimsSet proof = SignedJWT.parse(retry.getHeader("DPoP")).getJWTClaimsSet(); + assertThat(proof.getStringClaim("nonce")).isEqualTo("server-nonce"); + assertThat(proof.getStringClaim("htu")).isEqualTo(RPC_PATH); + assertThat(discoveryRequests).isEmpty(); + } + + @Test + void bearerTokenSkipsDiscoveryAndProof() { + tokenServer.setDispatcher(new Dispatcher() { + @Override + public MockResponse dispatch(RecordedRequest request) { + return json(BEARER_TOKEN_RESPONSE); + } + }); + TokenSource.AuthHeaders headers = tokenSource(autoResolver()).getAuthHeaders(rpcUrl(), "POST"); + assertThat(headers.getAuthHeader()).isEqualTo("Bearer test-token"); + assertThat(headers.getDpopHeader()).isNull(); + assertThat(discoveryRequests).isEmpty(); + } + + @Test + void autoRequiresHttpClientAndBuilderRejectsNull() { + assertThatThrownBy(() -> new DPoPModeResolver(DPoPMode.AUTO, null)) + .isInstanceOf(IllegalArgumentException.class); + SDKBuilder builder = SDKBuilder.newBuilder(); + assertThatThrownBy(() -> builder.dpopMode(null)) + .isInstanceOf(IllegalArgumentException.class); + } + + private DPoPModeResolver autoResolver() { + return new DPoPModeResolver(DPoPMode.AUTO, new OkHttpClient()); + } + + private DPoPModeResolver clockedResolver() { + return new DPoPModeResolver(DPoPMode.AUTO, new OkHttpClient(), TTL, nanos::get, + DPoPModeResolver.DISCOVERY_TIMEOUT); + } + + // Discovers once, then checks the answer is reused until just before ttl and rediscovered at ttl. + private void assertCachedFor(Duration ttl) { + DPoPModeResolver resolver = clockedResolver(); + assertThat(resolver.modeFor(rpcUrl())).isEqualTo(DPoPMode.LEGACY); + int afterFirst = countConfigRequests(); + nanos.addAndGet(ttl.toNanos() - 1); + resolver.modeFor(rpcUrl()); + assertThat(countConfigRequests()).isEqualTo(afterFirst); + nanos.addAndGet(1); + resolver.modeFor(rpcUrl()); + assertThat(countConfigRequests()).isEqualTo(afterFirst + 1); + } + + private int countConfigRequests() { + return (int) discoveredPaths().stream().filter(WELL_KNOWN_CONFIGURATION_PROCEDURE::equals).count(); + } + + private TokenSource tokenSource(DPoPModeResolver resolver) { + return new TokenSource( + new ClientSecretBasic(new ClientID("test-client"), new Secret("test-secret")), + rsaKey, + JWSAlgorithm.RS256, + tokenServer.url("/token").uri(), + new ClientCredentialsGrant(), + null, + resolver); + } + + private static String htuOf(TokenSource.AuthHeaders headers) throws Exception { + return SignedJWT.parse(headers.getDpopHeader()).getJWTClaimsSet().getStringClaim("htu"); + } + + private URL rpcUrl() { + return resourceServer.url(RPC_PATH).url(); + } + + private List discoveredPaths() { + return discoveryRequests.stream().map(RecordedRequest::getPath).collect(java.util.stream.Collectors.toList()); + } + + private RecordedRequest lastNonDiscoveryRequest() throws InterruptedException { + RecordedRequest last = null; + for (int i = resourceServer.getRequestCount(); i > 0; i--) { + RecordedRequest r = resourceServer.takeRequest(); + if (!isDiscovery(r.getPath())) { + last = r; + } + } + return last; + } + + private static boolean isDiscovery(String path) { + return path.startsWith("/.well-known/") || path.equals(WELL_KNOWN_CONFIGURATION_PROCEDURE); + } + + private static MockResponse json(String body) { + return new MockResponse().setBody(body).setHeader("Content-Type", "application/json"); + } +} diff --git a/sdk/src/test/java/io/opentdf/platform/sdk/SDKBuilderTest.java b/sdk/src/test/java/io/opentdf/platform/sdk/SDKBuilderTest.java index 3437cecd..80e3d91a 100644 --- a/sdk/src/test/java/io/opentdf/platform/sdk/SDKBuilderTest.java +++ b/sdk/src/test/java/io/opentdf/platform/sdk/SDKBuilderTest.java @@ -3,6 +3,7 @@ import com.connectrpc.ResponseMessageKt; import com.google.protobuf.Struct; import com.google.protobuf.Value; +import com.nimbusds.jwt.SignedJWT; import io.grpc.Metadata; import io.grpc.Server; import io.grpc.ServerBuilder; @@ -353,7 +354,13 @@ void sdkServicesSetup(boolean useSSLPlatform, boolean useSSLIDP) throws Exceptio public void getWellKnownConfiguration(GetWellKnownConfigurationRequest request, StreamObserver responseObserver) { var val = Value.newBuilder().setStringValue(issuer).build(); - var config = Struct.newBuilder().putFields("platform_issuer", val).build(); + // advertising RFC 9449 here seeds the platform's DPoP style (DSPX-5640) + var algs = Value.newBuilder().setListValue(com.google.protobuf.ListValue.newBuilder() + .addValues(Value.newBuilder().setStringValue("RS256"))).build(); + var config = Struct.newBuilder() + .putFields("platform_issuer", val) + .putFields("dpop_signing_alg_values_supported", algs) + .build(); var response = GetWellKnownConfigurationResponse .newBuilder() .setConfiguration(config) @@ -440,10 +447,11 @@ public ServerCall.Listener interceptCall(ServerCall ServerCall.Listener interceptCall(ServerCall ServerCall.Listener interceptCall(ServerCall