001/*
002 * Copyright 2026 Revetware LLC.
003 *
004 * Licensed under the Apache License, Version 2.0 (the "License");
005 * you may not use this file except in compliance with the License.
006 * You may obtain a copy of the License at
007 *
008 * http://www.apache.org/licenses/LICENSE-2.0
009 *
010 * Unless required by applicable law or agreed to in writing, software
011 * distributed under the License is distributed on an "AS IS" BASIS,
012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
013 * See the License for the specific language governing permissions and
014 * limitations under the License.
015 */
016
017package com.revetsec.oauth;
018
019import com.google.errorprone.annotations.CheckReturnValue;
020import com.revetsec.OutboundUriPolicy;
021import com.revetsec.internal.HostClassifier;
022import com.revetsec.internal.Limits;
023import com.revetsec.internal.ObserverDispatch;
024import com.revetsec.internal.oauth.OidcTransactionAccess;
025import com.revetsec.internal.http.Deadline;
026import com.revetsec.internal.http.HttpExchange;
027import com.revetsec.internal.http.HttpExchangeException;
028import com.revetsec.internal.http.HttpExchangeRequest;
029import com.revetsec.internal.http.RawResponse;
030import com.revetsec.internal.http.ResponseProfile;
031import com.revetsec.internal.http.RuntimeFloor;
032import com.revetsec.internal.http.UriChecks;
033import org.jspecify.annotations.NonNull;
034import org.jspecify.annotations.Nullable;
035
036import javax.annotation.concurrent.NotThreadSafe;
037import javax.annotation.concurrent.ThreadSafe;
038import java.net.URI;
039import java.net.http.HttpClient;
040import java.security.MessageDigest;
041import java.security.NoSuchAlgorithmException;
042import java.security.SecureRandom;
043import java.time.Clock;
044import java.time.Duration;
045import java.time.Instant;
046import java.util.Arrays;
047import java.util.Base64;
048import java.util.HashMap;
049import java.util.List;
050import java.util.Map;
051import java.util.Optional;
052import java.util.Set;
053import java.util.TreeSet;
054import java.util.function.Function;
055
056import static java.util.Objects.requireNonNull;
057
058/**
059 * OAuth 2.0 authorization-code, client-credentials, refresh and revocation client. Code authorization always uses
060 * fresh PKCE S256. Discovery is lazy; constructing a client does no network I/O and starts no thread. Browser
061 * callbacks must be supplied with a pending source and the exact callback URI selected by trusted application
062 * routing, never reconstructed from request headers. Tokens are raw credentials, not verified identity results.
063 *
064 * @author <a href="https://www.revetkn.com">Mark Allen</a>
065 * @since 1.0.0
066 */
067@ThreadSafe
068public final class OAuthClient {
069        static { OidcTransactionAccess.set(new OidcOperations()); }
070
071        @ThreadSafe
072        private static final class OidcOperations implements OidcTransactionAccess.Operations {
073  @Override public @NonNull VerifiedAccessToken validateAccessToken(@NonNull JwtAccessTokenValidator validator,@NonNull BearerToken token,@NonNull Deadline deadline) {
074   return validator.validate(token,deadline);
075  }
076  @Override public @NonNull String bearerValue(@NonNull BearerToken token) {return requireNonNull(token).value();}
077                @Override public void checkHmacAuthentication(@NonNull ClientAuthentication authentication, @NonNull Set<com.revetsec.jose.@NonNull JwsAlgorithm> algorithms) { authentication.checkHmac(algorithms); }
078                @Override public @NonNull OAuthException endpointFailure(OAuthException.@NonNull Reason reason) {
079                        return switch (reason) {
080                                case METADATA_INVALID -> OAuthValidationException.fromReason(reason);
081                                case ISSUER_MISMATCH -> OAuthConfigurationException.fromReason(reason);
082                                case DOCUMENT_MALFORMED -> OAuthResponseException.fromReason(reason);
083                                case ISSUER_POLICY_UNAVAILABLE -> OAuthConfigurationException.fromReason(reason);
084                                case NETWORK_FAILURE, INTERRUPTED, ATTEMPT_LIMIT -> OAuthTransportException.fromReason(reason, null);
085                                default -> throw new IllegalArgumentException("Unsupported endpoint failure reason.");
086                        };
087                }
088                @Override public @NonNull OAuthException endpointExchangeFailure(com.revetsec.internal.http.@NonNull HttpExchangeException failure) {
089                        return OAuthHttpErrors.fromExchange(failure);
090                }
091                @Override public @NonNull OAuthException copyEndpointFailure(@NonNull OAuthException failure) {
092                        return OAuthHttpErrors.copyForCaller(failure);
093                }
094                @Override public @NonNull OAuthException endpointStatusFailure(int status, @Nullable Duration retryAfter) {
095                        return OAuthErrorResponseException.fromResponse(status, "", Optional.ofNullable(retryAfter));
096                }
097                @Override public @NonNull OAuthException metadataStatusFailure(int status, @Nullable Duration retryAfter) {
098                        return OAuthErrorResponseException.fromMetadataResponse(status, Optional.ofNullable(retryAfter));
099                }
100                @Override public boolean isEndpointRejection(@NonNull OAuthErrorResponseException failure) {
101                        return failure.isEndpointRejection();
102                }
103                @Override public OidcTransactionAccess.@NonNull RefreshCompletion refresh(@NonNull OAuthClient client, @NonNull RefreshToken token,
104                                @NonNull TokenRequestOptions options, @NonNull AuthorizationServerMetadata metadata, @NonNull Deadline deadline, @NonNull Set<com.revetsec.jose.@NonNull JwsAlgorithm> hmacAlgorithms) {
105                        TokenEndpointPayload payload = client.refreshPayload(token, options, metadata, deadline, hmacAlgorithms);
106                        return new OidcTransactionAccess.RefreshCompletion(payload.idToken(), payload.idTokenPresent(), payload.accessToken(), payload.tokenType(), payload::toTokenResponse, payload.clientSecret());
107                }
108
109                @Override public @NonNull AuthorizationRedirect begin(@NonNull OAuthClient client, @NonNull AuthorizationRequestOptions options,
110                                @NonNull AuthorizationServerMetadata metadata, @Nullable Duration maxAge, @NonNull Set<@NonNull String> acrValues, @NonNull List<@NonNull String> acrPreferences) {
111                        return client.begin(options, "oidc", metadata, maxAge, acrValues, acrPreferences);
112                }
113                @Override public OidcTransactionAccess.@NonNull Completion complete(@NonNull OAuthClient client, @NonNull AuthorizationResponse response,
114                                @NonNull PendingAuthorizationSource source, @NonNull URI callback, @NonNull Function<@NonNull Deadline, @NonNull AuthorizationServerMetadata> metadata, @NonNull Deadline deadline, @NonNull Set<com.revetsec.jose.@NonNull JwsAlgorithm> hmacAlgorithms) {
115                        CodeCompletion completion = client.complete(response, source, callback, "oidc", metadata, deadline, hmacAlgorithms);
116                        PendingAuthorization pending = completion.pending();
117                        TokenEndpointPayload payload = completion.payload();
118                        return new OidcTransactionAccess.Completion(payload.idToken(), payload.accessToken(), payload.tokenType(),
119                                        completion.code(), requireNonNull(pending.nonce()), pending.maxAge(), pending.acrValues(),
120                                        () -> payload.toTokenResponse().withApplicationData(pending.getApplicationData()), payload.clientSecret());
121                }
122        }
123
124        private record CodeCompletion(@NonNull PendingAuthorization pending, @NonNull TokenEndpointPayload payload, @NonNull String code) {
125                @Override public @NonNull String toString() { return "CodeCompletion{credentials=<redacted>}"; }
126        }
127
128        private final @NonNull String issuer;
129        private final @Nullable AuthorizationServerMetadata staticMetadata;
130        private final @Nullable AuthorizationServerCache cache;
131        private final @NonNull String clientId;
132        private final @NonNull ClientAuthentication clientAuthentication;
133        private final @Nullable URI redirectUri;
134        private final @NonNull Set<@NonNull String> scopes;
135        private final @NonNull List<@NonNull URI> resources;
136        private final @NonNull IssuerParameterPolicy issuerParameterPolicy;
137        private final boolean requirePkceAdvertised;
138        private final @NonNull Duration pendingAuthorizationLifetime;
139        private final @NonNull HttpExchange exchange;
140        private final @NonNull Duration requestTimeout;
141        private final @NonNull Duration totalDeadline;
142        private final @NonNull Clock clock;
143        private final @NonNull OAuthObserver observer;
144        private final @NonNull SecureRandom random;
145        private final ResourceSettings resourceSettings;
146
147        private OAuthClient(@NonNull Builder builder, @NonNull HttpExchange exchange) {
148                this.issuer = builder.issuer;
149                this.staticMetadata = builder.staticMetadata;
150                this.clientId = requireNonNull(builder.clientId);
151                this.clientAuthentication = requireNonNull(builder.clientAuthentication);
152                this.redirectUri = builder.redirectUri;
153                this.scopes = builder.scopes;
154                this.resources = builder.resources;
155                this.issuerParameterPolicy = builder.issuerParameterPolicy;
156                this.requirePkceAdvertised = builder.requirePkceAdvertised;
157                this.pendingAuthorizationLifetime = builder.pendingAuthorizationLifetime;
158                this.exchange = exchange;
159                this.requestTimeout = builder.requestTimeout;
160                this.totalDeadline = builder.totalDeadline;
161                this.clock = builder.clock;
162                this.observer = builder.observer;
163                this.random = new SecureRandom();
164        this.resourceSettings = new ResourceSettings(this.issuer, this.staticMetadata, exchange, builder.outboundUriPolicy,
165                builder.allowInsecureLoopback, builder.requestTimeout, builder.totalDeadline, builder.clock,
166                builder.minimumTimeToLive, builder.defaultTimeToLive, builder.maximumTimeToLive, builder.discoveryCooldown);
167                this.cache = builder.staticMetadata == null ? new AuthorizationServerCache(URI.create(builder.issuer),
168                                exchange, builder.outboundUriPolicy, builder.allowInsecureLoopback, builder.requestTimeout,
169                                builder.clock, builder.observer, builder.minimumTimeToLive, builder.defaultTimeToLive,
170                                builder.maximumTimeToLive, builder.discoveryCooldown) : null;
171        }
172
173        /**
174         * Starts a client with lazy RFC 8414 then OIDC discovery.
175         *
176         * @param issuer exact configured issuer URI
177         * @return the builder
178         * @since 1.0.0
179         */
180        public static @NonNull Builder withIssuer(@NonNull String issuer) {
181                return new Builder(requireNonNull(issuer), null);
182        }
183
184        /**
185         * Starts a client with manually supplied metadata; build validates every known endpoint.
186         *
187         * @param metadata metadata
188         * @return the builder
189         * @since 1.0.0
190         */
191        public static @NonNull Builder withAuthorizationServerMetadata(@NonNull AuthorizationServerMetadata metadata) {
192                requireNonNull(metadata);
193                return new Builder(metadata.getIssuer(), metadata);
194        }
195
196        /**
197         * Loads metadata now, under the same cache and deadline policy as normal use. A static client does no I/O.
198         *
199         * @since 1.0.0
200         */
201        public void warmUp() { metadata(Deadline.fromNow(this.totalDeadline)); }
202
203        /**
204         * Starts a browser code flow with client-default scopes and resources.
205         *
206         * @return the redirect and pending authorization
207         * @since 1.0.0
208         */
209        public @NonNull AuthorizationRedirect beginAuthorization() {
210                return beginAuthorization(AuthorizationRequestOptions.builder().build());
211        }
212
213        /**
214         * Starts a browser code flow with per-request options. It may perform lazy discovery.
215         *
216         * @param options the options
217         * @return the redirect and pending authorization
218         * @since 1.0.0
219         */
220        public @NonNull AuthorizationRedirect beginAuthorization(@NonNull AuthorizationRequestOptions options) {
221                requireNonNull(options);
222                if (this.redirectUri == null) throw new IllegalStateException("A redirect URI is required for authorization code flow.");
223                return begin(options, "oauth", metadata(Deadline.fromNow(this.totalDeadline)), null, Set.of());
224        }
225
226        private @NonNull AuthorizationRedirect begin(@NonNull AuthorizationRequestOptions options, @NonNull String kind,
227                        @NonNull AuthorizationServerMetadata metadata, @Nullable Duration maxAge, @NonNull Set<@NonNull String> acrValues) {
228                return begin(options, kind, metadata, maxAge, acrValues, acrValues.stream().sorted().toList());
229        }
230        private @NonNull AuthorizationRedirect begin(@NonNull AuthorizationRequestOptions options, @NonNull String kind,
231                        @NonNull AuthorizationServerMetadata metadata, @Nullable Duration maxAge, @NonNull Set<@NonNull String> acrValues,
232                        @NonNull List<@NonNull String> acrPreferences) {
233                if (this.redirectUri == null)
234                        throw new IllegalStateException("A redirect URI is required for authorization code flow.");
235                if (metadata.getCodeChallengeMethodsSupported().isPresent()) {
236                        if (!metadata.getCodeChallengeMethodsSupported().orElseThrow().contains("S256"))
237                                throw OAuthValidationException.fromReason(OAuthException.Reason.PKCE_UNSUPPORTED);
238                } else if (this.requirePkceAdvertised) {
239                        throw OAuthValidationException.fromReason(OAuthException.Reason.PKCE_UNSUPPORTED);
240                }
241                String state = randomBase64Url();
242                String verifier = randomBase64Url();
243                String nonce = randomBase64Url();
244                String challenge = challenge(verifier);
245                Set<String> requestedScopes = options.scopesOverridden() ? options.getScopes() : this.scopes;
246                List<URI> requestedResources = options.resourcesOverridden() ? options.getResources() : this.resources;
247                OAuthRequestWriter query = new OAuthRequestWriter().add("response_type", "code")
248                                .add("client_id", this.clientId).add("redirect_uri", this.redirectUri.toString())
249                                .add("state", state).add("code_challenge", challenge).add("code_challenge_method", "S256");
250                if (!requestedScopes.isEmpty()) query.add("scope", String.join(" ", new TreeSet<>(requestedScopes)));
251                query.resources(requestedResources);
252                if (kind.equals("oidc")) {
253                        query.add("nonce", nonce);
254                        if (maxAge != null) query.add("max_age", Long.toString(maxAge.toSeconds()));
255                        if (!acrPreferences.isEmpty()) query.add("acr_values", String.join(" ", acrPreferences));
256                }
257                if (options.getResponseMode() == AuthorizationRequestOptions.ResponseMode.FORM_POST)
258                        query.add("response_mode", "form_post");
259                options.getPrompt().ifPresent(prompt -> query.add("prompt", prompt));
260                options.getLoginHint().ifPresent(hint -> query.add("login_hint", hint));
261                query.addAll(options.getAdditionalParameters());
262                URI uri = query.appendTo(metadata.getAuthorizationEndpoint());
263                Instant createdAt = this.clock.instant();
264                PendingAuthorization pending = new PendingAuthorization(kind, this.issuer, this.clientId, this.redirectUri,
265                                state, verifier, nonce, requestedScopes, requestedResources, options.getResponseMode(), createdAt,
266                                createdAt.plus(this.pendingAuthorizationLifetime), options.getApplicationData(),
267                                this.issuerParameterPolicy == IssuerParameterPolicy.REQUIRED
268                                                || metadata.isAuthorizationResponseIssuerSupported(), metadata.getAuthorizationEndpoint(),
269                                metadata.getTokenEndpoint(), maxAge, acrValues, options.getPrompt().orElse(null));
270                URI safe = AuthorizationServerCache.reduced(metadata.getAuthorizationEndpoint());
271                ObserverDispatch.dispatch(this.observer, observer -> observer.didBeginAuthorization(safe));
272                return new AuthorizationRedirect(uri, pending);
273        }
274
275        /**
276         * Completes a browser code flow. The caller supplies the URI of the fixed route that received the callback from
277         * trusted routing configuration. The application clears its pending cookie on every callback. Sealed-cookie
278         * completion may send two code POSTs for concurrent replays; an atomic store is required for client-side single
279         * use. All local checks precede discovery and token I/O.
280         *
281         * @param response parsed callback
282         * @param source sealed cookie or browser-bound store
283         * @param actualCallbackUri fixed registered URI of the receiving route
284         * @return raw token response
285         * @since 1.0.0
286         */
287        private @NonNull TokenResponse completeAuthorizationTokens(@NonNull AuthorizationResponse response,
288                        @NonNull PendingAuthorizationSource source, @NonNull URI actualCallbackUri) {
289                CodeCompletion completion = complete(response, source, actualCallbackUri, "oauth",
290                                this::metadata, Deadline.fromNow(this.totalDeadline));
291                return completion.payload().toTokenResponse().withApplicationData(completion.pending().getApplicationData());
292        }
293
294
295        /**
296         * Completes the flow once, returning endpoint tokens, a checked authorization error, a local callback
297         * security rejection, an endpoint client rejection, or a fixed pending-store failure. Metadata, transport,
298         * malformed responses and transient endpoint failures remain exceptions. Clear the pending cookie on every outcome. Atomic consumption and replay behavior are
299         * preserved: local checks precede I/O and an atomic store supplies client-side single use.
300         * @param response parsed callback
301         * @param source browser-bound pending source
302         * @param actualCallbackUri receiving route URI from trusted routing configuration
303         * @return the completion outcome
304         * @since 1.0.0
305         */
306        @CheckReturnValue
307        public @NonNull AuthorizationCompletionResult completeAuthorizationResult(@NonNull AuthorizationResponse response,
308                        @NonNull PendingAuthorizationSource source, @NonNull URI actualCallbackUri) {
309                try {
310                        return AuthorizationCompletionResult.fromTokens(completeAuthorizationTokens(response, source, actualCallbackUri));
311                } catch (AuthorizationErrorException failure) {
312                        OAuthEndpointError error = OAuthEndpointError.fromWireValue(failure.getErrorCode().orElse(""));
313                        return error == OAuthEndpointError.ACCESS_DENIED ? AuthorizationCompletionResult.fromDenial()
314                                        : AuthorizationCompletionResult.fromAuthorizationError(error);
315                } catch (OAuthErrorResponseException failure) {
316                        if (!isEndpointRejection(failure)) throw failure;
317                        return AuthorizationCompletionResult.fromEndpoint(failure);
318                } catch (OAuthValidationException rejection) {
319                        if (!isLocalCallbackRejection(rejection.getReason())) throw rejection;
320                        return AuthorizationCompletionResult.fromReason(rejection.getReason());
321                } catch (PendingAuthorizationStoreException failure) {
322                        return AuthorizationCompletionResult.fromStoreFailure(failure.getReason());
323                }
324        }
325
326        private static boolean isLocalCallbackRejection(OAuthException.@NonNull Reason reason) {
327                return switch (reason) {
328                        case STATE_MISMATCH, BROWSER_BINDING_MISMATCH, PENDING_AUTHORIZATION_INVALID,
329                                PENDING_AUTHORIZATION_EXPIRED, PENDING_AUTHORIZATION_NOT_FOUND, CLIENT_MISMATCH,
330                                ISSUER_MISMATCH, ISSUER_MISSING, CALLBACK_URI_MISMATCH, RESPONSE_MODE_MISMATCH -> true;
331                        default -> false;
332                };
333        }
334
335        private @NonNull CodeCompletion complete(@NonNull AuthorizationResponse response, @NonNull PendingAuthorizationSource source,
336                        @NonNull URI actualCallbackUri, @NonNull String kind, @NonNull Function<@NonNull Deadline, @NonNull AuthorizationServerMetadata> metadataSupplier, @NonNull Deadline deadline) {
337                return complete(response, source, actualCallbackUri, kind, metadataSupplier, deadline, Set.of());
338        }
339        private @NonNull CodeCompletion complete(@NonNull AuthorizationResponse response, @NonNull PendingAuthorizationSource source,
340                        @NonNull URI actualCallbackUri, @NonNull String kind, @NonNull Function<@NonNull Deadline, @NonNull AuthorizationServerMetadata> metadataSupplier,
341                        @NonNull Deadline deadline, @NonNull Set<com.revetsec.jose.@NonNull JwsAlgorithm> hmacAlgorithms) {
342                requireNonNull(response);
343                requireNonNull(source);
344                requireNonNull(actualCallbackUri);
345                PendingAuthorization pending;
346                try {
347                        pending = PendingAuthorizationResolver.resolve(source, response.getState().orElse(""), this.clock, deadline);
348                        if (!pending.kind().equals(kind))
349                                throw OAuthValidationException.fromReason(OAuthException.Reason.PENDING_AUTHORIZATION_INVALID);
350                        if (!pending.getClientId().equals(this.clientId))
351                                throw OAuthValidationException.fromReason(OAuthException.Reason.CLIENT_MISMATCH);
352                        if (!pending.getIssuer().equals(this.issuer))
353                                throw OAuthValidationException.fromReason(OAuthException.Reason.ISSUER_MISMATCH);
354                        if (pending.responseMode() != response.getResponseMode())
355                                throw OAuthValidationException.fromReason(OAuthException.Reason.RESPONSE_MODE_MISMATCH);
356                        if (!pending.getRedirectUri().toString().equals(actualCallbackUri.toString()))
357                                throw OAuthValidationException.fromReason(OAuthException.Reason.CALLBACK_URI_MISMATCH);
358                        Optional<String> responseIssuer = response.getIssuer();
359                        if (responseIssuer.isEmpty() && pending.issuerRequired())
360                                throw OAuthValidationException.fromReason(OAuthException.Reason.ISSUER_MISSING);
361                        if (responseIssuer.isPresent() && !responseIssuer.orElseThrow().equals(pending.getIssuer()))
362                                throw OAuthValidationException.fromReason(OAuthException.Reason.ISSUER_MISMATCH);
363                } catch (OAuthValidationException rejection) {
364                        ObserverDispatch.dispatch(this.observer, observer -> observer.didRejectCallback(rejection));
365                        throw rejection;
366                }
367                if (response.getError().isPresent())
368                        throw AuthorizationErrorException.fromErrorCode(response.getError().orElseThrow());
369                String code = response.getCode().orElseThrow(() ->
370                                OAuthResponseException.fromReason(OAuthException.Reason.CALLBACK_MALFORMED));
371                AuthorizationServerMetadata metadata;
372                try { metadata = metadataSupplier.apply(deadline); }
373                catch (OAuthException failure) { assertionMetadataFailure(OAuthEndpoint.TOKEN, failure, this.observer); throw failure; }
374                if (!metadata.getAuthorizationEndpoint().toString().equals(pending.authorizationEndpoint().toString())
375                                || !metadata.getTokenEndpoint().toString().equals(pending.tokenEndpoint().toString()))
376                        throw OAuthValidationException.fromReason(OAuthException.Reason.METADATA_ENDPOINT_DRIFT);
377                OAuthRequestWriter form = new OAuthRequestWriter().add("grant_type", "authorization_code")
378                                .add("code", code).add("redirect_uri", pending.getRedirectUri().toString())
379                                .add("code_verifier", pending.verifier()).resources(pending.resources());
380                return new CodeCompletion(pending,
381                                tokenPayloadRequest(metadata, form, pending.getRequestedScopes(), deadline, hmacAlgorithms), code);
382        }
383
384        /**
385         * Requests one client-credentials token and returns issued tokens or a fixed endpoint client rejection.
386         * A public client cannot use this grant. Transport, metadata, malformed responses and transient endpoint
387         * failures remain exceptions. No request is automatically retried.
388         * @param options scope, resource and safe additional form options
389         * @return the token-request outcome
390         * @since 1.0.0
391         */
392        @CheckReturnValue
393        public @NonNull OAuthTokenRequestResult requestClientCredentialsResult(@NonNull TokenRequestOptions options) {
394                try {
395                        return OAuthTokenRequestResult.fromTokens(requestClientCredentialsTokens(options));
396                } catch (OAuthErrorResponseException failure) {
397                        if (!isEndpointRejection(failure)) throw failure;
398                        return OAuthTokenRequestResult.fromEndpoint(failure);
399                }
400        }
401
402        /**
403         * Sends one refresh POST and returns issued tokens or a fixed endpoint client rejection. The caller restricts
404         * scopes to the original grant and retains the old refresh token when no replacement is returned. Transport,
405         * metadata, malformed responses and transient endpoint failures remain exceptions. No request is retried.
406         * @param refreshToken current refresh credential
407         * @param options per-request scope and resources
408         * @return the token-request outcome
409         * @since 1.0.0
410         */
411        @CheckReturnValue
412        public @NonNull OAuthTokenRequestResult refreshResult(@NonNull RefreshToken refreshToken,
413                        @NonNull TokenRequestOptions options) {
414                try {
415                        return OAuthTokenRequestResult.fromTokens(refreshTokens(refreshToken, options));
416                } catch (OAuthErrorResponseException failure) {
417                        if (!isEndpointRejection(failure)) throw failure;
418                        return OAuthTokenRequestResult.fromEndpoint(failure);
419                }
420        }
421
422        /**
423         * Sends one RFC 7009 revocation POST and returns acceptance or a fixed endpoint client rejection.
424         * A 200 response also accepts unknown tokens, and its body is ignored. Transport, metadata, malformed responses
425         * and transient endpoint failures remain exceptions. No request is automatically retried.
426         * @param token token to revoke
427         * @param hint token type hint
428         * @return the revocation outcome
429         * @since 1.0.0
430         */
431        @CheckReturnValue
432        public @NonNull OAuthRevocationResult revokeResult(@NonNull String token, @NonNull TokenTypeHint hint) {
433                try {
434                        revokeToken(token, hint);
435                        return OAuthRevocationResult.fromSuccess();
436                } catch (OAuthErrorResponseException failure) {
437                        if (!isEndpointRejection(failure)) throw failure;
438                        return OAuthRevocationResult.fromEndpoint(failure);
439                }
440        }
441
442        private static boolean isEndpointRejection(@NonNull OAuthErrorResponseException failure) {
443                return failure.isEndpointRejection();
444        }
445
446        /**
447         * Requests one client-credentials token. A public client cannot use this grant.
448         *
449         * @param options scope, resource and safe additional form options
450         * @return raw token response
451         * @since 1.0.0
452         */
453        private @NonNull TokenResponse requestClientCredentialsTokens(@NonNull TokenRequestOptions options) {
454                requireNonNull(options);
455                if (!supportsClientCredentials())
456                        throw new IllegalStateException("A public client cannot request client credentials.");
457                Deadline deadline = Deadline.fromNow(this.totalDeadline);
458                AuthorizationServerMetadata metadata = assertionMetadata(deadline, OAuthEndpoint.TOKEN);
459                Set<String> requestedScopes = options.getScopes().orElse(this.scopes);
460                OAuthRequestWriter form = new OAuthRequestWriter().add("grant_type", "client_credentials");
461                if (!requestedScopes.isEmpty()) form.add("scope", String.join(" ", new TreeSet<>(requestedScopes)));
462                form.resources(options.resourcesOverridden() ? options.getResources() : this.resources)
463                                .addAll(options.getAdditionalParameters());
464                return tokenRequest(metadata, form, requestedScopes, deadline);
465        }
466
467        /**
468         * Sends one refresh POST, with no automatic retry. The caller sends only scopes within the original grant; an
469         * absent scope option remains absent. If the response omits a replacement refresh token, retain the old one.
470         *
471         * @param refreshToken the current refresh token
472         * @param options per-request scope and resources
473         * @return raw token response
474         * @since 1.0.0
475         */
476        private @NonNull TokenResponse refreshTokens(@NonNull RefreshToken refreshToken, @NonNull TokenRequestOptions options) {
477                requireNonNull(refreshToken);
478                requireNonNull(options);
479                Deadline deadline = Deadline.fromNow(this.totalDeadline);
480                AuthorizationServerMetadata metadata = assertionMetadata(deadline, OAuthEndpoint.TOKEN);
481                return refreshPayload(refreshToken, options, metadata, deadline).toTokenResponse();
482        }
483
484        private @NonNull TokenEndpointPayload refreshPayload(@NonNull RefreshToken refreshToken, @NonNull TokenRequestOptions options,
485                        @NonNull AuthorizationServerMetadata metadata, @NonNull Deadline deadline) {
486                return refreshPayload(refreshToken, options, metadata, deadline, Set.of());
487        }
488        private @NonNull TokenEndpointPayload refreshPayload(@NonNull RefreshToken refreshToken, @NonNull TokenRequestOptions options,
489                        @NonNull AuthorizationServerMetadata metadata, @NonNull Deadline deadline, @NonNull Set<com.revetsec.jose.@NonNull JwsAlgorithm> hmacAlgorithms) {
490                OAuthRequestWriter form = new OAuthRequestWriter().add("grant_type", "refresh_token")
491                                .add("refresh_token", refreshToken.getValue());
492                options.getScopes().ifPresent(scopes -> {
493                        if (!scopes.isEmpty()) form.add("scope", String.join(" ", new TreeSet<>(scopes)));
494                });
495                form.resources(options.getResources()).addAll(options.getAdditionalParameters());
496                return tokenPayloadRequest(metadata, form, options.getScopes().orElse(null), deadline, hmacAlgorithms);
497        }
498
499        /**
500         * Sends one RFC 7009 revocation POST, with no automatic retry. A 200 body is ignored.
501         *
502         * @param token the token to revoke
503         * @param hint its type hint
504         * @since 1.0.0
505         */
506        private void revokeToken(@NonNull String token, @NonNull TokenTypeHint hint) {
507                if (requireNonNull(token).isEmpty()) throw new IllegalArgumentException("A token must not be empty.");
508                requireNonNull(hint);
509                Deadline deadline = Deadline.fromNow(this.totalDeadline);
510                AuthorizationServerMetadata metadata = assertionMetadata(deadline, OAuthEndpoint.REVOCATION);
511                URI endpoint = metadata.getRevocationEndpoint().orElseThrow(() ->
512                                new IllegalStateException("The authorization server has no revocation endpoint."));
513                Map<String, String> headers = new HashMap<>();
514                Map<String, String> authentication = new HashMap<>();
515                ClientAssertionPreparation.Prepared assertion = prepareAuthentication(new ResourceServerMetadata(this.issuer, endpoint,
516                                metadata.getRevocationEndpointAuthMethodsSupported().orElse(null), metadata.getRevocationEndpointAuthSigningAlgValuesSupported().orElse(null),
517                                metadata.getTokenEndpoint()), OAuthEndpoint.REVOCATION, deadline, this.observer);
518                if (assertion == null) this.clientAuthentication.apply(this.clientId, headers, authentication);
519                else addAssertion(authentication, assertion);
520                if (this.clientAuthentication.isUnencodedBasic())
521                        ObserverDispatch.dispatch(this.observer, OAuthObserver::didUseUnencodedBasic);
522                OAuthRequestWriter form = new OAuthRequestWriter().add("token", token)
523                                .add("token_type_hint", hint.wireValue()).addAll(authentication);
524                Instant requestStart = this.clock.instant();
525                RawResponse response = send(endpoint, OAuthEndpoint.REVOCATION, ResponseProfile.REVOCATION,
526                                form.body(), headers, deadline, assertion);
527                if (response.status() != 200)
528                        throw TokenResponseParser.error(response, requestStart);
529        }
530
531        private @NonNull TokenResponse tokenRequest(@NonNull AuthorizationServerMetadata metadata, @NonNull OAuthRequestWriter form,
532                        @Nullable Set<@NonNull String> requestedScopes, @NonNull Deadline deadline) {
533                return tokenPayloadRequest(metadata, form, requestedScopes, deadline).toTokenResponse();
534        }
535
536        private @NonNull TokenEndpointPayload tokenPayloadRequest(@NonNull AuthorizationServerMetadata metadata, @NonNull OAuthRequestWriter form,
537                        @Nullable Set<@NonNull String> requestedScopes, @NonNull Deadline deadline) {
538                return tokenPayloadRequest(metadata, form, requestedScopes, deadline, Set.of());
539        }
540        private @NonNull TokenEndpointPayload tokenPayloadRequest(@NonNull AuthorizationServerMetadata metadata, @NonNull OAuthRequestWriter form,
541                        @Nullable Set<@NonNull String> requestedScopes, @NonNull Deadline deadline, @NonNull Set<com.revetsec.jose.@NonNull JwsAlgorithm> hmacAlgorithms) {
542                URI endpoint = metadata.getTokenEndpoint();
543                Map<String, String> headers = new HashMap<>();
544                Map<String, String> authentication = new HashMap<>();
545                ClientAssertionPreparation.Prepared assertion = prepareAuthentication(new ResourceServerMetadata(this.issuer, endpoint,
546                                metadata.getTokenEndpointAuthMethodsSupported().orElse(null), metadata.getTokenEndpointAuthSigningAlgValuesSupported().orElse(null),
547                                metadata.getTokenEndpoint()), OAuthEndpoint.TOKEN, deadline, this.observer);
548                String secret;
549                if (assertion == null) secret = this.clientAuthentication.applyForOidc(this.clientId, headers, authentication, hmacAlgorithms);
550                else { addAssertion(authentication, assertion); secret = null; }
551                if (this.clientAuthentication.isUnencodedBasic())
552                        ObserverDispatch.dispatch(this.observer, OAuthObserver::didUseUnencodedBasic);
553                form.addAll(authentication);
554                Instant requestStart = this.clock.instant();
555                RawResponse response = send(endpoint, OAuthEndpoint.TOKEN, ResponseProfile.TOKEN,
556                                form.body(), headers, deadline, assertion);
557                try {
558                        return TokenResponseParser.parsePayload(response, requestStart, requestedScopes).withClientSecret(hmacAlgorithms.isEmpty() ? null : secret);
559                } catch (OAuthException failure) {
560                        URI safe = AuthorizationServerCache.reduced(endpoint);
561                        ObserverDispatch.dispatch(this.observer, observer -> observer.didFailEndpoint(
562                                        OAuthEndpoint.TOKEN, safe, failure, response.elapsed()));
563                        throw failure;
564                }
565        }
566
567        private @NonNull RawResponse send(@NonNull URI endpoint, @NonNull OAuthEndpoint kind, @NonNull ResponseProfile profile,
568                        @NonNull String formBody, @NonNull Map<@NonNull String, @NonNull String> headers, @NonNull Deadline deadline,
569                        ClientAssertionPreparation.@Nullable Prepared assertion) {
570                URI safe = AuthorizationServerCache.reduced(endpoint);
571                ObserverDispatch.dispatch(this.observer, observer -> observer.willRequestEndpoint(kind, safe));
572                long started = System.nanoTime();
573                try {
574                        ClientAssertionPreparation.checkReady(assertion, this.clock, deadline);
575                        RawResponse response = this.exchange.execute(new HttpExchangeRequest(endpoint, profile, formBody, headers,
576                                        Limits.HTTP_RESPONSE_BODY_SIZE.getDefaultIntValue(),
577                                        Limits.HTTP_ERROR_BODY_SIZE.getDefaultIntValue(), this.requestTimeout), deadline);
578                        ObserverDispatch.dispatch(this.observer, observer -> observer.didRequestEndpoint(
579                                        kind, safe, response.status(), response.elapsed()));
580                        return response;
581                } catch (OAuthException failure) {
582                        Duration elapsed = Duration.ofNanos(System.nanoTime() - started);
583                        ObserverDispatch.dispatch(this.observer, observer -> observer.didFailEndpoint(kind, safe, failure, elapsed));
584                        throw failure;
585                } catch (HttpExchangeException failure) {
586                        OAuthException mapped = OAuthHttpErrors.fromExchange(failure);
587                        Duration elapsed = Duration.ofNanos(System.nanoTime() - started);
588                        ObserverDispatch.dispatch(this.observer, observer -> observer.didFailEndpoint(kind, safe, mapped, elapsed));
589                        throw mapped;
590                }
591        }
592
593        private @NonNull AuthorizationServerMetadata assertionMetadata(@NonNull Deadline deadline, @NonNull OAuthEndpoint role) {
594                try { return metadata(deadline); }
595                catch (OAuthException failure) { assertionMetadataFailure(role, failure, this.observer); throw failure; }
596        }
597        void assertionMetadataFailure(@NonNull OAuthEndpoint role, @NonNull OAuthException failure, @NonNull OAuthObserver targetObserver) {
598                if (!this.clientAuthentication.isPrivateKeyJwt()) return;
599                useAssertionAudience(targetObserver);
600                ObserverDispatch.dispatch(targetObserver, observer -> observer.didFailClientAssertionPreparation(role, failure));
601        }
602        private void useAssertionAudience(@NonNull OAuthObserver targetObserver) {
603                if (this.clientAuthentication.assertionAudience() == ClientAssertionAudience.TOKEN_ENDPOINT)
604                        ObserverDispatch.dispatch(targetObserver, observer -> observer.didUseClientAssertionAudience(ClientAssertionAudience.TOKEN_ENDPOINT));
605        }
606        private ClientAssertionPreparation.@Nullable Prepared prepareAuthentication(@NonNull ResourceServerMetadata target,
607                        @NonNull OAuthEndpoint role, @NonNull Deadline deadline, @NonNull OAuthObserver targetObserver) {
608                if (!this.clientAuthentication.isPrivateKeyJwt()) return null;
609                useAssertionAudience(targetObserver);
610                try { return ClientAssertionPreparation.prepare(this.clientAuthentication, this.clientId, target, role, this.resourceSettings, this.random, deadline); }
611                catch (OAuthException failure) {
612                        ObserverDispatch.dispatch(targetObserver, observer -> observer.didFailClientAssertionPreparation(role, failure));
613                        throw failure;
614                }
615        }
616        private void addAssertion(@NonNull Map<@NonNull String, @NonNull String> form, ClientAssertionPreparation.@NonNull Prepared assertion) {
617                form.put("client_id", this.clientId);
618                form.put("client_assertion_type", "urn:ietf:params:oauth:client-assertion-type:jwt-bearer");
619                form.put("client_assertion", assertion.value());
620        }
621
622        private @NonNull AuthorizationServerMetadata metadata(@NonNull Deadline deadline) {
623                return this.staticMetadata != null ? this.staticMetadata : requireNonNull(this.cache).get(deadline);
624        }
625
626    record ResourceSettings(@NonNull String issuer, @Nullable AuthorizationServerMetadata metadata, @NonNull HttpExchange exchange,
627            @NonNull OutboundUriPolicy policy, boolean allowLoopback, @NonNull Duration requestTimeout, @NonNull Duration totalDeadline, @NonNull Clock clock,
628            @NonNull Duration minimumTtl, @NonNull Duration defaultTtl, @NonNull Duration maximumTtl, @NonNull Duration cooldown) {
629        @Override public @NonNull String toString() { return "ResourceSettings{data=<redacted>}"; }
630    }
631    @NonNull ResourceSettings resourceSettings() { return this.resourceSettings; }
632    void requireIntrospectionAuthentication(@Nullable Set<@NonNull String> methods) {
633        if (this.clientAuthentication.isPublicClient()) throw new IllegalArgumentException("Introspection requires confidential client authentication.");
634        if (!this.clientAuthentication.isPrivateKeyJwt() && methods != null && !methods.contains(this.clientAuthentication.methodName())) throw OAuthValidationException.fromReason(OAuthException.Reason.METADATA_INVALID);
635    }
636    @SuppressWarnings("ReferenceEquality") // Observer delivery deduplicates the same instance, never equal values.
637    @NonNull OAuthObserver resourceObserver(@NonNull AccessTokenObserver resource) {
638        if (resource == this.observer) return resource;
639        return new OAuthObserver() {
640            @Override public void willRequestEndpoint(@NonNull OAuthEndpoint kind, @NonNull URI uri) { endpointObservers(resource, o -> o.willRequestEndpoint(kind, uri)); }
641            @Override public void didRequestEndpoint(@NonNull OAuthEndpoint kind, @NonNull URI uri, @NonNull Integer status, @NonNull Duration elapsed) { endpointObservers(resource, o -> o.didRequestEndpoint(kind, uri, status, elapsed)); }
642            @Override public void didFailEndpoint(@NonNull OAuthEndpoint kind, @NonNull URI uri, @NonNull OAuthException failure, @NonNull Duration elapsed) { endpointObservers(resource, o -> o.didFailEndpoint(kind, uri, failure, elapsed)); }
643            @Override public void didUseClientAssertionAudience(@NonNull ClientAssertionAudience audience) { endpointObservers(resource, o -> o.didUseClientAssertionAudience(audience)); }
644            @Override public void didFailClientAssertionPreparation(@NonNull OAuthEndpoint kind, @NonNull OAuthException failure) { endpointObservers(resource, o -> o.didFailClientAssertionPreparation(kind, failure)); }
645        };
646    }
647    @SuppressWarnings("ReferenceEquality") // Distinct observer instances each receive the event.
648    private void endpointObservers(@NonNull OAuthObserver resource, java.util.function.@NonNull Consumer<@NonNull OAuthObserver> hook) {
649        ObserverDispatch.dispatch(this.observer, hook);
650        if (resource != this.observer) ObserverDispatch.dispatch(resource, hook);
651    }
652    @NonNull RawResponse introspectionRequest(@NonNull BearerToken token, @NonNull ResourceServerMetadata target, @NonNull Deadline deadline, @NonNull AccessTokenObserver resource) {
653        Map<String, String> headers = new HashMap<>(); Map<String, String> authentication = new HashMap<>();
654        URI endpoint = target.endpoint();
655        ClientAssertionPreparation.Prepared assertion = prepareAuthentication(target, OAuthEndpoint.INTROSPECTION, deadline, resourceObserver(resource));
656        if (assertion == null) this.clientAuthentication.apply(this.clientId, headers, authentication);
657        else addAssertion(authentication, assertion);
658        if (this.clientAuthentication.isUnencodedBasic()) endpointObservers(resource, OAuthObserver::didUseUnencodedBasic);
659        OAuthRequestWriter form = new OAuthRequestWriter().add("token", token.value()).add("token_type_hint", "access_token").addAll(authentication);
660        URI safe = AuthorizationServerCache.reduced(endpoint);
661        endpointObservers(resource, o -> o.willRequestEndpoint(OAuthEndpoint.INTROSPECTION, safe));
662        long started = System.nanoTime();
663        try {
664            ClientAssertionPreparation.checkReady(assertion, this.clock, deadline);
665            RawResponse response = this.exchange.execute(new HttpExchangeRequest(endpoint, ResponseProfile.INTROSPECTION, form.body(), headers,
666                    Limits.HTTP_RESPONSE_BODY_SIZE.getDefaultIntValue(), Limits.HTTP_ERROR_BODY_SIZE.getDefaultIntValue(), this.requestTimeout), deadline);
667            endpointObservers(resource, o -> o.didRequestEndpoint(OAuthEndpoint.INTROSPECTION, safe, response.status(), response.elapsed()));
668            return response;
669        } catch (OAuthException failure) {
670            endpointObservers(resource, o -> o.didFailEndpoint(OAuthEndpoint.INTROSPECTION, safe, failure, Duration.ofNanos(System.nanoTime() - started)));
671            throw failure;
672                } catch (HttpExchangeException failure) {
673            OAuthException mapped = OAuthHttpErrors.fromExchange(failure);
674            endpointObservers(resource, o -> o.didFailEndpoint(OAuthEndpoint.INTROSPECTION, safe, mapped, Duration.ofNanos(System.nanoTime() - started)));
675            throw mapped;
676        }
677    }
678    void introspectionResponseFailure(@NonNull URI endpoint, @NonNull OAuthException failure, @NonNull Duration elapsed, @NonNull AccessTokenObserver resource) {
679        URI safe = AuthorizationServerCache.reduced(endpoint);
680        endpointObservers(resource, o -> o.didFailEndpoint(OAuthEndpoint.INTROSPECTION, safe, failure, elapsed));
681    }
682
683        boolean supportsClientCredentials() { return !this.clientAuthentication.isPublicClient(); }
684        @NonNull Clock clock() { return this.clock; }
685        @NonNull Duration totalDeadline() { return this.totalDeadline; }
686
687        private @NonNull String randomBase64Url() {
688                byte[] bytes = new byte[32];
689                this.random.nextBytes(bytes);
690                try {
691                        return Base64.getUrlEncoder().withoutPadding().encodeToString(bytes);
692                } finally {
693                        Arrays.fill(bytes, (byte) 0);
694                }
695        }
696
697        static @NonNull String challenge(@NonNull String verifier) {
698                try {
699                        byte[] digest = MessageDigest.getInstance("SHA-256").digest(
700                                        verifier.getBytes(java.nio.charset.StandardCharsets.US_ASCII));
701                        try {
702                                return Base64.getUrlEncoder().withoutPadding().encodeToString(digest);
703                        } finally {
704                                Arrays.fill(digest, (byte) 0);
705                        }
706                } catch (NoSuchAlgorithmException impossible) {
707                        throw new IllegalStateException("SHA-256 is unavailable.");
708                }
709        }
710
711        /**
712         * Redacts client configuration and credentials.
713         *
714         * @return a redacted description
715         * @since 1.0.0
716         */
717        @Override
718        public @NonNull String toString() { return "OAuthClient{configuration=<redacted>}"; }
719
720        /**
721         * Configures an OAuth client. Building performs validation only: no discovery, HTTP request or new thread.
722         *
723         * @author <a href="https://www.revetkn.com">Mark Allen</a>
724         * @since 1.0.0
725         */
726        @NotThreadSafe
727        @CheckReturnValue
728        public static final class Builder {
729                private final @NonNull String issuer;
730                private final @Nullable AuthorizationServerMetadata staticMetadata;
731                private @Nullable String clientId;
732                private @Nullable ClientAuthentication clientAuthentication;
733                private @Nullable URI redirectUri;
734                private @NonNull Set<@NonNull String> scopes = Set.of();
735                private @NonNull List<@NonNull URI> resources = List.of();
736                private @NonNull IssuerParameterPolicy issuerParameterPolicy = IssuerParameterPolicy.METADATA_DRIVEN;
737                private boolean requirePkceAdvertised;
738                private @NonNull Duration pendingAuthorizationLifetime = Limits.PENDING_STATE_LIFETIME.getDefaultDuration();
739                private @Nullable HttpClient httpClient;
740                private @NonNull OutboundUriPolicy outboundUriPolicy = OutboundUriPolicy.defaultInstance();
741                private @NonNull Duration requestTimeout = Limits.REQUEST_TIMEOUT.getDefaultDuration();
742                private @NonNull Duration totalDeadline = Limits.TOTAL_DEADLINE.getDefaultDuration();
743                private @NonNull Clock clock = Clock.systemUTC();
744                private @NonNull OAuthObserver observer = OAuthObserver.disabledInstance();
745                private boolean allowInsecureLoopback;
746                private boolean acknowledgeUnpatchedRuntime;
747                private @NonNull Duration minimumTimeToLive = Limits.DISCOVERY_MINIMUM_TIME_TO_LIVE.getDefaultDuration();
748                private @NonNull Duration defaultTimeToLive = Limits.DISCOVERY_DEFAULT_TIME_TO_LIVE.getDefaultDuration();
749                private @NonNull Duration maximumTimeToLive = Limits.DISCOVERY_MAXIMUM_TIME_TO_LIVE.getDefaultDuration();
750                private @NonNull Duration discoveryCooldown = Limits.DISCOVERY_COOLDOWN.getDefaultDuration();
751
752                private Builder(@NonNull String issuer, @Nullable AuthorizationServerMetadata staticMetadata) {
753                        this.issuer = issuer;
754                        this.staticMetadata = staticMetadata;
755                }
756
757                /**
758                 * Sets the client identifier registered with the authorization server.
759                 *
760                 * @param value nonempty client ID, or null which clears the required setting
761                 * @return this builder
762                 * @since 1.0.0
763                 */
764                public @NonNull Builder clientId(@Nullable String value) {
765                        if (value != null && value.isEmpty()) throw new IllegalArgumentException("A client ID must not be empty.");
766                        this.clientId = value; return this;
767                }
768
769                /**
770                 * Sets the client's token-endpoint authentication method.
771                 *
772                 * @param value one client authentication strategy, or null which clears the required setting
773                 * @return this builder
774                 * @since 1.0.0
775                 */
776                public @NonNull Builder clientAuthentication(@Nullable ClientAuthentication value) {
777                        this.clientAuthentication = value; return this;
778                }
779
780                /**
781                 * Sets the registered redirect URI for authorization-code flows.
782                 *
783                 * @param value exact registered code-flow callback URI, or null for token-only clients
784                 * @return this builder
785                 * @since 1.0.0
786                 */
787                public @NonNull Builder redirectUri(@Nullable URI value) { this.redirectUri = value; return this; }
788
789                /**
790                 * Sets the scopes used when a request has no scope override.
791                 *
792                 * @param value complete client-default scopes, or null which restores the default
793                 * @return this builder
794                 * @since 1.0.0
795                 */
796                public @NonNull Builder scopes(@Nullable Set<@NonNull String> value) {
797                        this.scopes = AuthorizationRequestOptions.builder().scopes(value).build().getScopes(); return this;
798                }
799
800                /**
801                 * Sets the default resource indicators for token requests.
802                 *
803                 * @param value complete client-default resources, or null which restores the default
804                 * @return this builder
805                 * @since 1.0.0
806                 */
807                public @NonNull Builder resources(@Nullable List<@NonNull URI> value) {
808                        this.resources = AuthorizationRequestOptions.builder().resources(value).build().getResources(); return this;
809                }
810
811                /**
812                 * Sets how the callback issuer parameter is required.
813                 *
814                 * @param value callback issuer policy, or null which restores the default
815                 * @return this builder
816                 * @since 1.0.0
817                 */
818                public @NonNull Builder issuerParameterPolicy(@Nullable IssuerParameterPolicy value) {
819                        this.issuerParameterPolicy = value == null ? IssuerParameterPolicy.METADATA_DRIVEN : value; return this;
820                }
821
822                /**
823                 * Requires metadata to advertise S256 before an authorization flow begins.
824                 *
825                 * @param value whether metadata must advertise S256, or null which restores the default
826                 * @return this builder
827                 * @since 1.0.0
828                 */
829                public @NonNull Builder requirePkceAdvertised(@Nullable Boolean value) { this.requirePkceAdvertised = Boolean.TRUE.equals(value); return this; }
830
831                /**
832                 * Sets the lifetime of browser-bound pending authorization.
833                 *
834                 * @param value pending lifetime from 1 to 60 minutes, or null which restores the default
835                 * @return this builder
836                 * @since 1.0.0
837                 */
838                public @NonNull Builder pendingAuthorizationLifetime(@Nullable Duration value) {
839                        this.pendingAuthorizationLifetime = value == null ? Limits.PENDING_STATE_LIFETIME.getDefaultDuration() : Limits.PENDING_STATE_LIFETIME.require(value); return this;
840                }
841
842                /**
843                 * Injects an application-managed HTTP client. It must use Redirect.NEVER and have no Authenticator or
844                 * CookieHandler; build rejects noncompliance without sending a request. The application owns injected
845                 * TLS/proxy configuration and network egress beyond the URI policy.
846                 *
847                 * @param value injected client meeting these restrictions, or null for the lazy default
848                 * @return this builder
849                 * @since 1.0.0
850                 */
851                public @NonNull Builder httpClient(@Nullable HttpClient value) { this.httpClient = value; return this; }
852
853                /**
854                 * Sets the policy used to approve outbound endpoint URIs.
855                 *
856                 * @param value outbound URI policy, or null which restores the default
857                 * @return this builder
858                 * @since 1.0.0
859                 */
860                public @NonNull Builder outboundUriPolicy(@Nullable OutboundUriPolicy value) {
861                        this.outboundUriPolicy = value == null ? OutboundUriPolicy.defaultInstance() : value; return this;
862                }
863
864                /**
865                 * Sets the timeout for one HTTP exchange.
866                 *
867                 * @param value per-request timeout, or null which restores the default
868                 * @return this builder
869                 * @since 1.0.0
870                 */
871                public @NonNull Builder requestTimeout(@Nullable Duration value) {
872                        this.requestTimeout = value == null ? Limits.REQUEST_TIMEOUT.getDefaultDuration() : Limits.REQUEST_TIMEOUT.require(value); return this;
873                }
874
875                /**
876                 * Sets the deadline shared by all exchanges in one public call.
877                 *
878                 * @param value total deadline per public call, or null which restores the default
879                 * @return this builder
880                 * @since 1.0.0
881                 */
882                public @NonNull Builder totalDeadline(@Nullable Duration value) {
883                        this.totalDeadline = value == null ? Limits.TOTAL_DEADLINE.getDefaultDuration() : Limits.TOTAL_DEADLINE.require(value); return this;
884                }
885
886                /**
887                 * Sets the clock used for pending state, token expiry and cache freshness.
888                 *
889                 * @param value clock for token expiry and cache freshness, or null which restores the default
890                 * @return this builder
891                 * @since 1.0.0
892                 */
893                public @NonNull Builder clock(@Nullable Clock value) { this.clock = value == null ? Clock.systemUTC() : value; return this; }
894
895                /**
896                 * Sets the observer for bounded OAuth events.
897                 *
898                 * @param value observer, or null which restores the default
899                 * @return this builder
900                 * @since 1.0.0
901                 */
902                public @NonNull Builder observer(@Nullable OAuthObserver value) {
903                        this.observer = value == null ? OAuthObserver.disabledInstance() : value; return this;
904                }
905
906                /**
907                 * Allows plain HTTP to exact loopback hosts for local tests.
908                 *
909                 * @param value allow plain HTTP to exact loopback hosts for tests, or null which restores the default
910                 * @return this builder
911                 * @since 1.0.0
912                 */
913                public @NonNull Builder allowInsecureLoopback(@Nullable Boolean value) {
914                        this.allowInsecureLoopback = Boolean.TRUE.equals(value); return this;
915                }
916
917                /**
918                 * Acknowledges the risk of building on an unpatched runtime.
919                 *
920                 * @param value explicit acknowledgment of an unpatched runtime, or null which restores the default
921                 * @return this builder
922                 * @since 1.0.0
923                 */
924                public @NonNull Builder acknowledgeUnpatchedRuntime(@Nullable Boolean value) {
925                        this.acknowledgeUnpatchedRuntime = Boolean.TRUE.equals(value); return this;
926                }
927
928                /**
929                 * Sets the lowest permitted discovery cache lifetime.
930                 *
931                 * @param value minimum discovery cache lifetime, or null which restores the default
932                 * @return this builder
933                 * @since 1.0.0
934                 */
935                public @NonNull Builder minimumTimeToLive(@Nullable Duration value) {
936                        this.minimumTimeToLive = value == null ? Limits.DISCOVERY_MINIMUM_TIME_TO_LIVE.getDefaultDuration() : Limits.DISCOVERY_MINIMUM_TIME_TO_LIVE.require(value); return this;
937                }
938
939                /**
940                 * Sets the fallback lifetime when discovery supplies no usable cache lifetime.
941                 *
942                 * @param value fallback discovery cache lifetime, or null which restores the default
943                 * @return this builder
944                 * @since 1.0.0
945                 */
946                public @NonNull Builder defaultTimeToLive(@Nullable Duration value) {
947                        this.defaultTimeToLive = value == null ? Limits.DISCOVERY_DEFAULT_TIME_TO_LIVE.getDefaultDuration() : Limits.DISCOVERY_DEFAULT_TIME_TO_LIVE.require(value); return this;
948                }
949
950                /**
951                 * Sets the highest permitted discovery cache lifetime.
952                 *
953                 * @param value maximum discovery cache lifetime, or null which restores the default
954                 * @return this builder
955                 * @since 1.0.0
956                 */
957                public @NonNull Builder maximumTimeToLive(@Nullable Duration value) {
958                        this.maximumTimeToLive = value == null ? Limits.DISCOVERY_MAXIMUM_TIME_TO_LIVE.getDefaultDuration() : Limits.DISCOVERY_MAXIMUM_TIME_TO_LIVE.require(value); return this;
959                }
960
961                /**
962                 * Sets the cooldown after a failed discovery attempt.
963                 *
964                 * @param value discovery attempt ceiling window, or null which restores the default
965                 * @return this builder
966                 * @since 1.0.0
967                 */
968                public @NonNull Builder discoveryCooldown(@Nullable Duration value) {
969                        this.discoveryCooldown = value == null ? Limits.DISCOVERY_COOLDOWN.getDefaultDuration() : Limits.DISCOVERY_COOLDOWN.require(value); return this;
970                }
971
972                /**
973                 * Validates configuration and builds without I/O or thread creation.
974                 *
975                 * @return the client
976                 * @since 1.0.0
977                 */
978                public @NonNull OAuthClient build() {
979                        return build(Runtime.version());
980                }
981
982                @NonNull OAuthClient build(Runtime.@NonNull Version runtimeVersion) {
983                        RuntimeFloor.require(requireNonNull(runtimeVersion), this.acknowledgeUnpatchedRuntime);
984                        if (this.clientId == null || this.clientAuthentication == null)
985                                throw new IllegalStateException("A client ID and client authentication strategy are required.");
986                        Limits.requireRequestTimeoutWithinTotalDeadline(this.requestTimeout, this.totalDeadline);
987                        Limits.requireDiscoveryTimeToLiveOrder(this.minimumTimeToLive, this.defaultTimeToLive,
988                                        this.maximumTimeToLive, this.discoveryCooldown);
989                        URI issuerUri;
990                        try { issuerUri = URI.create(this.issuer); }
991                        catch (IllegalArgumentException malformed) { throw new IllegalArgumentException("The issuer URI is invalid."); }
992                        if (issuerUri.getRawQuery() != null || issuerUri.getRawFragment() != null)
993                                throw new IllegalArgumentException("An issuer URI must not have a query or fragment.");
994                        UriChecks.requirePermitted(issuerUri, this.outboundUriPolicy, this.allowInsecureLoopback);
995                        if (this.redirectUri != null) requireCallbackUri(this.redirectUri, this.allowInsecureLoopback);
996                        if (this.staticMetadata != null)
997                                for (URI endpoint : AuthorizationServerCache.allEndpoints(this.staticMetadata))
998                                        UriChecks.requirePermitted(endpoint, this.outboundUriPolicy, this.allowInsecureLoopback);
999                        HttpExchange exchange = HttpExchange.fromHttpClient(this.httpClient, this.outboundUriPolicy,
1000                                        this.allowInsecureLoopback);
1001                        OAuthClient client = new OAuthClient(this, exchange);
1002                        if (this.clientAuthentication.isPrivateKeyJwt() && this.clientAuthentication.assertionAudience() == ClientAssertionAudience.TOKEN_ENDPOINT)
1003                                ObserverDispatch.dispatch(this.observer, observer -> observer.didEnableClientAssertionAudience(ClientAssertionAudience.TOKEN_ENDPOINT));
1004                        if (this.clientAuthentication.isUnencodedBasic())
1005                                ObserverDispatch.dispatch(this.observer, OAuthObserver::didUseUnencodedBasic);
1006                        if (RuntimeFloor.isBelowFloor(runtimeVersion) && this.acknowledgeUnpatchedRuntime)
1007                                ObserverDispatch.dispatch(this.observer,
1008                                                observer -> observer.didUseUnpatchedRuntime(runtimeVersion.toString()));
1009                        return client;
1010                }
1011
1012                private static void requireCallbackUri(@NonNull URI uri, boolean allowLoopback) {
1013                        String scheme = uri.getScheme();
1014                        String host = uri.getHost();
1015                        int port = uri.getPort();
1016                        if (scheme == null || uri.isOpaque() || host == null || uri.getRawUserInfo() != null
1017                                        || uri.getRawFragment() != null || port == 0 || port > 65_535
1018                                        || !(scheme.equalsIgnoreCase("https") || (scheme.equalsIgnoreCase("http") && allowLoopback
1019                                        && HostClassifier.isPlainHttpLoopbackHost(host))))
1020                                throw new IllegalArgumentException("A redirect URI must be an absolute HTTPS URI with a host, no userinfo "
1021                                                + "or fragment, or an allowed test loopback HTTP URI.");
1022                }
1023        }
1024}