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.oidc; 018 019import com.google.errorprone.annotations.CheckReturnValue; 020 021import com.revetsec.OutboundUriPolicy; 022import com.revetsec.internal.Limits; 023import com.revetsec.internal.ObserverDispatch; 024import com.revetsec.internal.http.Deadline; 025import com.revetsec.internal.http.UriChecks; 026import com.revetsec.internal.http.HttpExchange; 027import java.util.concurrent.atomic.AtomicReference; 028import java.util.concurrent.locks.ReentrantLock; 029import com.revetsec.internal.oauth.OidcTransactionAccess; 030import com.revetsec.jose.*; 031import com.revetsec.oauth.*; 032import org.jspecify.annotations.NonNull; 033import org.jspecify.annotations.Nullable; 034import javax.annotation.concurrent.ThreadSafe; 035import javax.annotation.concurrent.NotThreadSafe; 036import java.net.URI; 037import java.net.http.HttpClient; 038import java.time.Clock; 039import java.time.Duration; 040import java.time.Instant; 041import java.util.*; 042import static java.util.Objects.requireNonNull; 043 044/** 045 * OpenID Connect authorization-code relying party. Provider discovery is lazy; explicit configuration and issuer settings are validated 046 * without I/O or new threads in build. Authentication uses fresh nonce and PKCE S256 and validates the ID token before releasing 047 * tokens or identity. The application supplies a fixed callback URI from trusted routing and clears pending cookies. 048 * A sealed cookie inherits OAuth's concurrent replay boundary; use a durable atomic store for client-side single use. 049 * 050 * @author <a href="https://www.revetkn.com">Mark Allen</a> 051 * @since 1.0.0 052 */ 053@ThreadSafe 054public final class OidcClient { 055 private final @Nullable OidcProviderCache<ProviderState> cache; 056 private final OAuthClient oauth; 057 private final String issuer; 058 private final OidcIssuerPolicy issuerPolicy; 059 private final Object proofOwner = new Object(); 060 private final @Nullable JwsAlgorithm userInfoAlgorithm; 061 private final UserInfoEndpoint userInfo; 062 private final Set<String> scopes; 063 private final List<URI> resources; 064 private final Set<String> acrValues; 065 private final @Nullable List<String> acrPreferences; 066 private final Duration totalDeadline; 067 private final @Nullable URI postLogoutRedirectUri; 068 private final Duration logoutPendingLifetime; 069 private final OidcObserver observer; 070 private final @Nullable JwksSource configuredKeySource; 071 private final String clientId; 072 private final Set<JwsAlgorithm> algorithms; 073 private final Set<JwsAlgorithm> hmacAlgorithms; 074 private final Set<String> trustedAudiences; 075 private final Set<String> trustedAuthorizedParties; 076 private final Duration clockSkew; 077 private final Duration maximumIdTokenAge; 078 private final Clock clock; 079 private final @Nullable HttpClient httpClient; 080 private final OutboundUriPolicy policy; 081 private final boolean allowInsecureLoopback; 082 private final boolean acknowledgeUnpatchedRuntime; 083 private final Duration requestTimeout; 084 private final ReentrantLock stateLock = new ReentrantLock(); 085 private @Nullable ProviderState state; 086 087 private OidcClient(@NonNull Builder builder, @NonNull OAuthClient oauth) { 088 this.issuerPolicy = builder.issuerPolicy; this.oauth = oauth; this.issuer = builder.issuer; this.userInfoAlgorithm = builder.userInfoAlgorithm; this.scopes = builder.scopes; this.resources = builder.resources; 089 this.acrValues = builder.acrValues; this.acrPreferences = builder.acrPreferences; this.totalDeadline = builder.totalDeadline; 090 this.postLogoutRedirectUri = builder.postLogoutRedirectUri; this.logoutPendingLifetime = builder.pendingLifetime; this.observer = builder.observer; 091 this.configuredKeySource = builder.keySource; this.clientId = requireNonNull(builder.clientId); 092 this.algorithms = builder.algorithms; this.hmacAlgorithms = hmacAlgorithms(this.algorithms); this.trustedAudiences = builder.trustedAudiences; 093 this.trustedAuthorizedParties = builder.trustedAuthorizedParties; this.clockSkew = builder.clockSkew; 094 this.maximumIdTokenAge = builder.maximumIdTokenAge; this.clock = builder.clock; this.httpClient = builder.httpClient; 095 this.policy = builder.policy; this.allowInsecureLoopback = builder.allowInsecureLoopback; 096 this.acknowledgeUnpatchedRuntime = builder.acknowledgeUnpatchedRuntime; this.requestTimeout = builder.requestTimeout; 097 this.userInfo = new UserInfoEndpoint(HttpExchange.fromHttpClient(this.httpClient, this.policy, this.allowInsecureLoopback), 098 this.requestTimeout, this.clock, this.observer, new UserInfoAttemptGate(Limits.DISCOVERY_COOLDOWN.getDefaultDuration(), System::nanoTime)); 099 if (builder.metadata == null) { 100 this.cache = new OidcProviderCache<>(URI.create(builder.issuer), HttpExchange.fromHttpClient(this.httpClient, this.policy, 101 this.allowInsecureLoopback), this.policy, this.allowInsecureLoopback, this.requestTimeout, this.clock, 102 this.observer, builder.minimumTimeToLive, builder.defaultTimeToLive, builder.maximumTimeToLive, 103 builder.discoveryCooldown, metadata -> { 104 try { this.issuerPolicy.checkMetadata(metadata); checkMetadata(metadata, this.algorithms, this.policy, this.allowInsecureLoopback, this.userInfoAlgorithm); return stateFor(metadata); } 105 catch (IllegalArgumentException invalid) { 106 throw OidcTransactionAccess.get().endpointFailure(OAuthException.Reason.METADATA_INVALID); 107 } 108 }, System::nanoTime, this.issuerPolicy); 109 } else { this.cache = null; stateFor(builder.metadata); } 110 } 111 private @NonNull ProviderState provider(@NonNull Deadline deadline) { 112 if (this.cache != null) return this.cache.get(deadline); 113 this.stateLock.lock(); 114 try { return requireNonNull(this.state); } finally { this.stateLock.unlock(); } 115 } 116 private @NonNull ProviderState stateFor(@NonNull OidcProviderMetadata metadata) { 117 this.stateLock.lock(); 118 try { 119 ProviderState current = this.state; 120 if (current != null && current.metadata == metadata) return current; 121 // Keep one current source, sharing its cache only while the exact JWKS URI is unchanged. 122 JwksSource source = this.configuredKeySource; 123 if (source == null && current != null && current.metadata.getJwksUri().toString().equals(metadata.getJwksUri().toString())) source = current.source; 124 if (source == null) source = RemoteJwksSource.withUri(metadata.getJwksUri()) 125 .httpClient(this.httpClient).outboundUriPolicy(this.policy).clock(this.clock).observer(this.observer) 126 .allowInsecureLoopback(this.allowInsecureLoopback).acknowledgeUnpatchedRuntime(this.acknowledgeUnpatchedRuntime) 127 .requestTimeout(this.requestTimeout).build(); 128 ProviderState found = new ProviderState(metadata, source, new IdTokenValidator(metadata.getIssuer(), this.clientId, source, 129 effectiveAlgorithms(metadata, this.algorithms), this.trustedAudiences, this.trustedAuthorizedParties, 130 this.clockSkew, this.maximumIdTokenAge, this.clock, this.observer, !this.hmacAlgorithms.isEmpty(), this.issuerPolicy)); 131 this.state = found; return found; 132 } finally { this.stateLock.unlock(); } 133 } 134 private static @NonNull Set<@NonNull JwsAlgorithm> hmacAlgorithms(@NonNull Set<@NonNull JwsAlgorithm> algorithms) { 135 Set<JwsAlgorithm> found = new HashSet<>(); 136 for (JwsAlgorithm algorithm : algorithms) 137 if (Set.of(JwsAlgorithm.HS256, JwsAlgorithm.HS384, JwsAlgorithm.HS512).contains(algorithm)) found.add(algorithm); 138 return Set.copyOf(found); 139 } 140 private static @NonNull Set<@NonNull JwsAlgorithm> effectiveAlgorithms(@NonNull OidcProviderMetadata metadata, @NonNull Set<@NonNull JwsAlgorithm> configured) { 141 Set<JwsAlgorithm> effective = new HashSet<>(); 142 for (JwsAlgorithm algorithm : configured) 143 if (metadata.getIdTokenSigningAlgValuesSupported().contains(algorithm.getWireValue())) effective.add(algorithm); 144 if (effective.isEmpty() || !metadata.getResponseTypesSupported().contains("code")) 145 throw new IllegalArgumentException("The OIDC provider does not support this client's code-flow policy."); 146 return Set.copyOf(effective); 147 } 148 private static void checkMetadata(@NonNull OidcProviderMetadata metadata, @NonNull Set<@NonNull JwsAlgorithm> configured, 149 @NonNull OutboundUriPolicy policy, boolean loopback, @Nullable JwsAlgorithm userInfoAlgorithm) { 150 effectiveAlgorithms(metadata, configured); 151 if (userInfoAlgorithm != null) metadata.getUserInfoSigningAlgValuesSupported().ifPresent(supported -> { 152 if (!supported.contains(userInfoAlgorithm.getWireValue())) throw new IllegalArgumentException("The configured UserInfo signing algorithm is not advertised."); 153 }); 154 for (URI endpoint : List.of(metadata.getAuthorizationEndpoint(), metadata.getTokenEndpoint(), metadata.getJwksUri())) 155 UriChecks.requirePermitted(endpoint, policy, loopback); 156 metadata.getUserInfoEndpoint().ifPresent(uri -> UriChecks.requirePermitted(uri, policy, loopback)); 157 metadata.oauthMetadata().getRevocationEndpoint().ifPresent(uri -> UriChecks.requirePermitted(uri, policy, loopback)); 158 } 159 @ThreadSafe 160 private record ProviderState(@NonNull OidcProviderMetadata metadata, @NonNull JwksSource source, @NonNull IdTokenValidator validator) { } 161 /** 162 * Starts an OIDC client with lazy issuer-path discovery. Build performs no discovery or key lookup. 163 * @param issuer exact issuer identifier, without query or fragment 164 * @return the builder 165 * @since 1.0.0 166 */ 167 public static @NonNull Builder withIssuer(@NonNull String issuer) { return new Builder(issuer, null); } 168 /** 169 * Starts an OIDC client with explicit provider metadata. 170 * @param metadata trusted application configuration 171 * @return the builder 172 * @since 1.0.0 173 */ 174 public static @NonNull Builder withProviderMetadata(@NonNull OidcProviderMetadata metadata) { return new Builder(requireNonNull(metadata).getIssuer(), metadata); } 175 /** 176 * Fetches lazy provider metadata and remote signing keys now. Explicit metadata and static keys perform no I/O. 177 * Metadata and key lookup share the total deadline. 178 * 179 * @since 1.0.0 180 */ 181 public void warmUp() { 182 Deadline deadline = Deadline.fromNow(this.totalDeadline); 183 ProviderState provider = provider(deadline); 184 if ((provider.validator.needsPublicKeys() || this.userInfoAlgorithm != null) && provider.source instanceof RemoteJwksSource remote) com.revetsec.internal.jose.JwtValidationAccess.get().warmUp(remote, deadline::remainingNanos); 185 } 186 /** 187 * Starts authentication with the client defaults. This prepares the authorization URL. 188 * 189 * @return redirect and pending record 190 * @since 1.0.0 191 */ 192 public @NonNull AuthorizationRedirect beginAuthentication() { return beginAuthentication(OidcAuthenticationOptions.builder().build()); } 193 /** 194 * Starts authentication with replacement options. Openid is emitted exactly once and nonce is generated internally. 195 * @param options per-login options 196 * @return redirect and pending record 197 * @since 1.0.0 198 */ 199 public @NonNull AuthorizationRedirect beginAuthentication(@NonNull OidcAuthenticationOptions options) { 200 requireNonNull(options); 201 Set<String> required = options.getRequiredAcrValues().orElse(this.acrValues); 202 List<String> preferred = options.getAcrPreferences().orElse(this.acrPreferences == null ? required.stream().sorted().toList() : this.acrPreferences); 203 return OidcTransactionAccess.get().begin(this.oauth, options.transactionOptions(this.scopes, this.resources), 204 provider(Deadline.fromNow(this.totalDeadline)).metadata.oauthMetadata(), options.getMaxAge().orElse(null), required, preferred); 205 } 206 /** 207 * Completes authentication after the shared browser binding, state, flow kind, client, issuer, callback route and 208 * endpoint checks. A successful token POST does not release tokens until all ID-token checks pass. Never derive 209 * actualCallbackUri from request headers. Clear the pending browser cookie on every callback, including failure. 210 * @param response raw-parsed callback 211 * @param source browser-bound pending source 212 * @param actualCallbackUri exact receiving route URI from trusted application routing 213 * @return validated authentication and released tokens 214 * @since 1.0.0 215 */ 216 private @NonNull OidcAuthentication completeAuthenticationChecked(@NonNull AuthorizationResponse response, 217 @NonNull PendingAuthorizationSource source, @NonNull URI actualCallbackUri) { 218 Deadline deadline = Deadline.fromNow(this.totalDeadline); 219 AtomicReference<ProviderState> selected = new AtomicReference<>(); 220 OidcTransactionAccess.Completion completion = OidcTransactionAccess.get().complete(this.oauth, 221 response, source, actualCallbackUri, budget -> { 222 ProviderState provider = provider(budget); selected.set(provider); return provider.metadata.oauthMetadata(); 223 }, deadline, this.hmacAlgorithms); 224 ProviderState provider = requireNonNull(selected.get()); 225 IdToken token; 226 try { 227 String compact = completion.idToken(); 228 if (compact == null) throw OidcValidationException.fromReason(OidcValidationException.Reason.ID_TOKEN_MISSING); 229 if (!completion.tokenType().equalsIgnoreCase("Bearer")) 230 throw OidcValidationException.fromReason(OidcValidationException.Reason.TOKEN_TYPE_UNSUPPORTED); 231 token = provider.validator.validate(compact, completion.nonce(), completion.accessToken(), completion.code(), 232 completion.maxAge(), completion.acrValues(), deadline, completion.clientSecret()); 233 } catch (OidcValidationException failure) { 234 ObserverDispatch.dispatch(this.observer, observer -> observer.didRejectIdToken(failure)); 235 throw failure; 236 } 237 OidcAuthentication authentication = new OidcAuthentication(token, completion.releaseTokens(), this.clientId, this.proofOwner, completion.acrValues()); 238 ObserverDispatch.dispatch(this.observer, OidcObserver::didCompleteAuthentication); 239 return authentication; 240 } 241 242 /** 243 * Completes authentication once, returning authenticated identity, checked authorization errors, rejected callback 244 * binding, rejected endpoint credentials, or a rejected ID token. Rejected outcomes release no identity, claims or endpoint credentials. 245 * Pending-store failures return a fixed failure result. Metadata, transport, malformed responses, transient 246 * endpoint failures and invalid HMAC-secret failures remain exceptions. Clear the pending 247 * cookie on every outcome; the original completion's atomic-consumption and observer behavior is preserved. 248 * @param response parsed callback 249 * @param source browser-bound pending source 250 * @param actualCallbackUri receiving route URI from trusted routing configuration 251 * @return the authentication outcome 252 * @since 1.0.0 253 */ 254 @CheckReturnValue 255 public @NonNull OidcAuthenticationResult completeAuthenticationResult(@NonNull AuthorizationResponse response, 256 @NonNull PendingAuthorizationSource source, @NonNull URI actualCallbackUri) { 257 try { 258 return OidcAuthenticationResult.fromAuthentication(completeAuthenticationChecked(response, source, actualCallbackUri)); 259 } catch (AuthorizationErrorException failure) { 260 OAuthEndpointError error = OAuthEndpointError.fromWireValue(failure.getErrorCode().orElse("")); 261 return error == OAuthEndpointError.ACCESS_DENIED ? OidcAuthenticationResult.fromDenial() 262 : OidcAuthenticationResult.fromAuthorizationError(error); 263 } catch (OAuthErrorResponseException failure) { 264 if (!isEndpointRejection(failure)) throw failure; 265 return OidcAuthenticationResult.fromEndpoint(failure); 266 } catch (OAuthValidationException rejection) { 267 if (!isLocalCallbackRejection(rejection.getReason())) throw rejection; 268 return OidcAuthenticationResult.fromAuthorizationReason(rejection.getReason()); 269 } catch (com.revetsec.oauth.PendingAuthorizationStoreException failure) { 270 return OidcAuthenticationResult.fromStoreFailure(failure.getReason()); 271 } catch (OidcValidationException rejection) { 272 if (rejection.getReason() == OidcValidationException.Reason.HMAC_SECRET_INVALID) throw rejection; 273 return OidcAuthenticationResult.fromIdTokenReason(rejection.getReason(), rejection.getJoseReason().orElse(null)); 274 } 275 } 276 277 private static boolean isLocalCallbackRejection(OAuthException.@NonNull Reason reason) { 278 return switch (reason) { 279 case STATE_MISMATCH, BROWSER_BINDING_MISMATCH, PENDING_AUTHORIZATION_INVALID, 280 PENDING_AUTHORIZATION_EXPIRED, PENDING_AUTHORIZATION_NOT_FOUND, CLIENT_MISMATCH, 281 ISSUER_MISMATCH, ISSUER_MISSING, CALLBACK_URI_MISMATCH, RESPONSE_MODE_MISMATCH -> true; 282 default -> false; 283 }; 284 } 285 286 /** 287 * Fetches UserInfo and returns checked data or a fixed local or endpoint rejection. Issuer/client binding, 288 * subject, format and token lifetime checks precede release of any UserInfo. Transport, metadata, transient 289 * endpoint failures and invalid HMAC configuration remain exceptions. No request is automatically retried. 290 * @param authentication previously validated authentication for this issuer and client 291 * @return the UserInfo outcome 292 * @since 1.0.0 293 */ 294 @CheckReturnValue 295 public @NonNull OidcUserInfoResult fetchUserInfoResult(@NonNull OidcAuthentication authentication) { 296 try { 297 return OidcUserInfoResult.fromUserInfo(fetchUserInfoChecked(authentication)); 298 } catch (OidcValidationException failure) { 299 if (failure.getReason() == OidcValidationException.Reason.HMAC_SECRET_INVALID) throw failure; 300 return OidcUserInfoResult.fromRejection(failure); 301 } catch (OAuthErrorResponseException failure) { 302 if (!isEndpointRejection(failure)) throw failure; 303 return OidcUserInfoResult.fromEndpoint(failure); 304 } 305 } 306 307 /** 308 * Fetches UserInfo using a checked refresh result and the original authenticated identity. The original 309 * session must match before I/O. Rejection releases no UserInfo; infrastructure failures remain exceptions. 310 * @param authentication original validated authentication 311 * @param refreshed checked refresh result for that original session 312 * @return the UserInfo outcome 313 * @since 1.0.0 314 */ 315 @CheckReturnValue 316 public @NonNull OidcUserInfoResult fetchUserInfoResult(@NonNull OidcAuthentication authentication, 317 @NonNull OidcRefresh refreshed) { 318 try { 319 return OidcUserInfoResult.fromUserInfo(fetchUserInfoChecked(authentication, refreshed)); 320 } catch (OidcValidationException failure) { 321 if (failure.getReason() == OidcValidationException.Reason.HMAC_SECRET_INVALID) throw failure; 322 return OidcUserInfoResult.fromRejection(failure); 323 } catch (OAuthErrorResponseException failure) { 324 if (!isEndpointRejection(failure)) throw failure; 325 return OidcUserInfoResult.fromEndpoint(failure); 326 } 327 } 328 329 /** 330 * Sends one refresh POST with default options and returns checked tokens or a fixed rejection. Persist the 331 * original session reference in trusted storage and serialize refreshes to avoid token-rotation races. 332 * Infrastructure failures and invalid HMAC configuration remain exceptions; no request is retried. 333 * @param refreshToken current refresh credential 334 * @param original original session comparison reference, not proof of identity 335 * @return the refresh outcome 336 * @since 1.0.0 337 */ 338 @CheckReturnValue 339 public @NonNull OidcRefreshResult refreshResult(@NonNull RefreshToken refreshToken, 340 @NonNull OidcSessionReference original) { 341 return refreshResult(refreshToken, original, TokenRequestOptions.builder().build()); 342 } 343 344 /** 345 * Sends one refresh POST with scope/resource options and returns checked tokens or a fixed rejection. 346 * The caller restricts scopes to the original grant. Any returned ID token must pass original-session 347 * continuity checks before tokens are released. Infrastructure failures and invalid HMAC configuration 348 * remain exceptions; no request is automatically retried. 349 * @param refreshToken current refresh credential 350 * @param original original session comparison reference 351 * @param options per-request scope and resources 352 * @return the refresh outcome 353 * @since 1.0.0 354 */ 355 @CheckReturnValue 356 public @NonNull OidcRefreshResult refreshResult(@NonNull RefreshToken refreshToken, 357 @NonNull OidcSessionReference original, @NonNull TokenRequestOptions options) { 358 try { 359 return OidcRefreshResult.fromRefresh(refreshChecked(refreshToken, original, options)); 360 } catch (OidcValidationException failure) { 361 if (failure.getReason() == OidcValidationException.Reason.HMAC_SECRET_INVALID) throw failure; 362 return OidcRefreshResult.fromRejection(failure); 363 } catch (OAuthErrorResponseException failure) { 364 if (!isEndpointRejection(failure)) throw failure; 365 return OidcRefreshResult.fromEndpoint(failure); 366 } 367 } 368 369 private static boolean isEndpointRejection(@NonNull OAuthErrorResponseException failure) { 370 return OidcTransactionAccess.get().isEndpointRejection(failure); 371 } 372 373 /** 374 * Fetches UserInfo for this client's validated authentication. The access token is sent only in a Bearer header 375 * to a permitted endpoint; issuer/client binding and safe token form are checked before discovery or UserInfo I/O. 376 * The returned subject must exactly match the ID token. JSON is the default; a configured signed response cannot 377 * be replaced by JSON. The call shares one deadline across discovery, UserInfo and signing-key lookup. Transient 378 * endpoint failures have bounded backoff; no request is automatically retried and no UserInfo result is cached. 379 * @param authentication previously validated authentication for this issuer and client 380 * @return checked UserInfo 381 * @since 1.0.0 382 */ 383 private @NonNull OidcUserInfo fetchUserInfoChecked(@NonNull OidcAuthentication authentication) { 384 requireNonNull(authentication); Deadline deadline = Deadline.fromNow(this.totalDeadline); 385 OidcUserInfo result; 386 try { 387 if (!this.clientId.equals(authentication.clientId()) || (this.issuerPolicy.isMicrosoftEntra() 388 ? !authentication.belongsTo(this.proofOwner) || OidcIssuerPolicy.tenantFromIssuer(authentication.getIssuer()) == null 389 : !this.issuer.equals(authentication.getIssuer()))) 390 throw OidcValidationException.fromReason(OidcValidationException.Reason.USERINFO_AUTHENTICATION_MISMATCH); 391 if (this.issuerPolicy.isMicrosoftEntra()) { 392 ObserverDispatch.dispatch(this.observer, OidcObserver::didUseMicrosoftEntraMultiTenant); 393 Instant before = OidcIssuerPolicy.readClock(this.clock); 394 this.issuerPolicy.checkTenant(requireNonNull(OidcIssuerPolicy.tenantFromIssuer(authentication.getIssuer())), deadline); 395 if (OidcIssuerPolicy.readClock(this.clock).isBefore(before)) throw OidcTransactionAccess.get().endpointFailure(OAuthException.Reason.ISSUER_POLICY_UNAVAILABLE); 396 } 397 UserInfoEndpoint.authorization(authentication.getTokens().getAccessToken(), this.clock); 398 ProviderState provider = provider(deadline); 399 result = this.userInfo.fetch(provider.metadata, provider.source, authentication, this.clientId, this.userInfoAlgorithm, 400 this.clockSkew, this.trustedAudiences, deadline, this.issuerPolicy); 401 } catch (OidcValidationException failure) { 402 ObserverDispatch.dispatch(this.observer, observer -> observer.didRejectUserInfo(failure)); throw failure; 403 } 404 ObserverDispatch.dispatch(this.observer, observer -> observer.didFetchUserInfo(result.isSigned())); 405 return result; 406 } 407 /** 408 * Fetches UserInfo using a checked refresh result's access token and the original authenticated identity. 409 * The result must retain the same original session reference. A parsed session reference alone cannot supply 410 * identity. All ordinary UserInfo issuer/client, subject, format, lifetime and network checks still apply. 411 * @param authentication original validated authentication 412 * @param refreshed checked refresh result for that original session 413 * @return checked UserInfo 414 * @since 1.0.0 415 */ 416 private @NonNull OidcUserInfo fetchUserInfoChecked(@NonNull OidcAuthentication authentication, @NonNull OidcRefresh refreshed) { 417 requireNonNull(authentication); requireNonNull(refreshed); 418 if (!authentication.getSessionReference().matchesOriginalReference(refreshed.getSessionReference())) { 419 OidcValidationException failure = OidcValidationException.fromReason(OidcValidationException.Reason.USERINFO_AUTHENTICATION_MISMATCH); 420 ObserverDispatch.dispatch(this.observer, observer -> observer.didRejectUserInfo(failure)); throw failure; 421 } 422 return fetchUserInfoChecked(authentication.withTokens(refreshed.getTokens())); 423 } 424 /** 425 * Sends one refresh POST with scope/resource options. No scope option means no scope field is sent; the caller 426 * restricts scope requests to the original grant. A returned ID token must preserve original issuer, subject, 427 * audience and authorized party. Present auth_time and nonce must match the original. Issued-at cannot precede 428 * the original token; refresh does not apply the login token-age or authentication-age window. A present code 429 * hash cannot be verified during refresh and is rejected. The original flow's saved ACR acceptance set applies to every returned ID token, separately from this client's login defaults. Tokens remain private until validation completes. 430 * @param refreshToken current refresh credential 431 * @param original original session comparison reference 432 * @param options per-request options 433 * @return tokens, retained/replacement refresh credential and optional verified ID token 434 * @since 1.0.0 435 */ 436 private @NonNull OidcRefresh refreshChecked(@NonNull RefreshToken refreshToken, @NonNull OidcSessionReference original, 437 @NonNull TokenRequestOptions options) { 438 requireNonNull(refreshToken); requireNonNull(original); requireNonNull(options); 439 Deadline deadline = Deadline.fromNow(this.totalDeadline); 440 @Nullable IdToken verified; 441 OidcTransactionAccess.RefreshCompletion completion; 442 try { 443 if (this.issuerPolicy.isMicrosoftEntra()) original.checkMicrosoftEntraClient(this.clientId); 444 else original.checkClient(this.issuer, this.clientId); 445 ProviderState provider = provider(deadline); 446 completion = OidcTransactionAccess.get().refresh(this.oauth, refreshToken, options, provider.metadata.oauthMetadata(), deadline, this.hmacAlgorithms); 447 if (!completion.tokenType().equalsIgnoreCase("Bearer")) throw OidcValidationException.fromReason(OidcValidationException.Reason.TOKEN_TYPE_UNSUPPORTED); 448 String compact = completion.idToken(); 449 if (completion.idTokenPresent() && compact == null) throw OidcValidationException.fromReason(OidcValidationException.Reason.ID_TOKEN_MALFORMED); 450 verified = compact == null ? null : provider.validator.validateRefresh(compact, original, completion.accessToken(), original.getRequiredAcrValues(), deadline, completion.clientSecret()); 451 } catch (OidcValidationException failure) { 452 ObserverDispatch.dispatch(this.observer, observer -> observer.didRejectRefresh(failure)); throw failure; 453 } 454 TokenResponse tokens = completion.releaseTokens(); 455 OidcRefresh result = new OidcRefresh(tokens, verified, refreshToken, original, this.proofOwner); 456 ObserverDispatch.dispatch(this.observer, observer -> observer.didRefreshTokens(result.getIdToken().isPresent(), tokens.getRefreshToken().isPresent())); 457 return result; 458 } 459 460 461 /** 462 * Explicitly retains this exact client's validated ID token as a logout hint. This does not extend identity 463 * lifetime or change the comparison-only original reference. A token may later be used after authentication expiry. 464 * @param authentication genuine completed authentication produced by this exact client instance 465 * @return credential-bearing logout companion for trusted storage 466 * @throws NullPointerException if authentication is null 467 * @throws OidcLogoutException if ownership, profile, current issuer policy, interruption or the budget fails 468 * @since 1.0.0 469 */ 470 public @NonNull OidcLogoutHint logoutHintFrom(@NonNull OidcAuthentication authentication) { 471 requireNonNull(authentication); Deadline deadline = Deadline.fromNow(this.totalDeadline); OidcLogoutSupport.active(deadline); 472 if (!authentication.belongsTo(this.proofOwner)) throw OidcLogoutSupport.failure(OidcLogoutException.Reason.HINT_MISMATCH); 473 checkLogoutReference(authentication.getSessionReference(), deadline); 474 OidcLogoutHint hint = checkedLogoutHint(authentication.getSessionReference(), authentication.getIdToken().toCompactSerialization(), deadline); 475 OidcLogoutSupport.active(deadline); return hint; 476 } 477 478 /** 479 * Explicitly retains a newly validated ID token from this exact client's refresh. Omitted ID tokens yield empty; 480 * the original session reference is always retained and no new authenticated identity is created. 481 * @param refreshed genuine refresh result produced by this exact client instance 482 * @return optional replacement credential, never a replacement original reference 483 * @throws NullPointerException if refreshed is null 484 * @throws OidcLogoutException if ownership, profile, current issuer policy, interruption or the budget fails 485 * @since 1.0.0 486 */ 487 public @NonNull Optional<@NonNull OidcLogoutHint> logoutHintFrom(@NonNull OidcRefresh refreshed) { 488 requireNonNull(refreshed); Deadline deadline = Deadline.fromNow(this.totalDeadline); OidcLogoutSupport.active(deadline); 489 if (!refreshed.belongsTo(this.proofOwner)) throw OidcLogoutSupport.failure(OidcLogoutException.Reason.HINT_MISMATCH); 490 checkLogoutReference(refreshed.getSessionReference(), deadline); 491 Optional<OidcLogoutHint> hint = refreshed.getIdToken().map(token -> checkedLogoutHint(refreshed.getSessionReference(), token.toCompactSerialization(), deadline)); 492 OidcLogoutSupport.active(deadline); return hint; 493 } 494 495 496 /** 497 * Prepares a browser GET/form POST request after the application has authorized its local POST/CSRF request and 498 * terminated its own session. Failures never undo local termination. No end-session server request or automatic 499 * retry is sent. The original reference and retained hint must match before discovery, entropy or output. 500 * @param original original continuity reference for this session, not identity proof 501 * @param hint explicitly retained logout credential bound to that reference 502 * @return credential-bearing browser request and independent pending correlation state 503 * @throws NullPointerException if a required argument is null 504 * @throws OidcLogoutException if configuration, binding, discovery, URI policy, time, entropy or the budget fails 505 * @since 1.0.0 506 */ 507 public @NonNull OidcLogoutRequest beginLogout(@NonNull OidcSessionReference original, @NonNull OidcLogoutHint hint) { 508 requireNonNull(original); requireNonNull(hint); Deadline deadline = Deadline.fromNow(this.totalDeadline); OidcLogoutSupport.active(deadline); 509 URI callback = requireLogoutConfiguration(); 510 if (!original.matchesOriginalReference(hint.reference())) throw OidcLogoutSupport.failure(OidcLogoutException.Reason.HINT_MISMATCH); 511 java.time.Instant before = logoutClock(deadline); checkLogoutReference(original, deadline); 512 ProviderState provider; 513 try { provider = logoutProvider(deadline); OidcLogoutSupport.active(deadline); } 514 catch (OidcLogoutException failure) { throw failure; } 515 catch (com.revetsec.oauth.OAuthException failure) { 516 OidcLogoutSupport.active(deadline); throw OidcLogoutSupport.failure(failure.isTemporaryCondition() ? OidcLogoutException.Reason.DISCOVERY_UNAVAILABLE : OidcLogoutException.Reason.PROVIDER_UNAVAILABLE); 517 } catch (VirtualMachineError fatal) { throw fatal; } 518 catch (Throwable failure) { if (failure instanceof InterruptedException) Thread.currentThread().interrupt(); OidcLogoutSupport.active(deadline); throw OidcLogoutSupport.failure(OidcLogoutException.Reason.PROVIDER_UNAVAILABLE); } 519 URI endpoint = provider.metadata.getEndSessionEndpoint().orElseThrow(() -> OidcLogoutSupport.failure(OidcLogoutException.Reason.END_SESSION_UNSUPPORTED)); 520 try { 521 OidcLogoutSupport.active(deadline); OidcLogoutSupport.endpoint(endpoint); UriChecks.requirePermitted(endpoint, this.policy, this.allowInsecureLoopback); OidcLogoutSupport.active(deadline); 522 } catch (OidcLogoutException failure) { throw failure; } 523 catch (VirtualMachineError fatal) { throw fatal; } 524 catch (Throwable invalid) { if (invalid instanceof InterruptedException) Thread.currentThread().interrupt(); OidcLogoutSupport.active(deadline); throw OidcLogoutSupport.failure(OidcLogoutException.Reason.ENDPOINT_NOT_PERMITTED); } 525 java.time.Instant created = logoutClock(deadline); 526 if (created.isBefore(before)) throw OidcLogoutSupport.failure(OidcLogoutException.Reason.PROVIDER_UNAVAILABLE); 527 byte @Nullable [] random = null; 528 try { 529 java.time.Instant expires = created.plus(this.logoutPendingLifetime); 530 OidcLogoutSupport.active(deadline); com.revetsec.internal.crypto.EntropySource entropy = com.revetsec.internal.crypto.EntropySource.fromDefaults(); OidcLogoutSupport.active(deadline); 531 random = entropy.nextBytes(32); OidcLogoutSupport.active(deadline); String state = com.revetsec.internal.encoding.Base64Url.encode(random); 532 PendingOidcLogout pending = new PendingOidcLogout(this.issuer, this.clientId, callback, state, created, expires); OidcLogoutPendingCodec.encode(pending, null); 533 OidcLogoutRequest request = new OidcLogoutRequest(endpoint, this.clientId, callback, hint.compact(), state, pending); 534 java.time.Instant completed = logoutClock(deadline); 535 if (completed.isBefore(created) || !completed.isBefore(expires)) throw OidcLogoutSupport.failure(OidcLogoutException.Reason.PROVIDER_UNAVAILABLE); 536 OidcLogoutSupport.active(deadline); return request; 537 } catch (OidcLogoutException failure) { OidcLogoutSupport.active(deadline); throw failure; } 538 catch (VirtualMachineError fatal) { throw fatal; } 539 catch (Throwable unavailable) { if (unavailable instanceof InterruptedException) Thread.currentThread().interrupt(); OidcLogoutSupport.active(deadline); throw OidcLogoutSupport.failure(OidcLogoutException.Reason.PROVIDER_UNAVAILABLE); } 540 finally { OidcLogoutSupport.clear(random); } 541 } 542 543 /** 544 * Correlates a state-only browser return without discovery, JWKS, token POST, ID-token signature verification, 545 * retry or session creation. The actual callback comes from trusted routing configuration, never headers. Clear 546 * a pending cookie on every callback, including rejection/exception paths. Returned proves correlation only. 547 * @param rawQuery raw query without the leading question mark, at most4096characters 548 * @param source this browser's typed pending source 549 * @param actualCallbackUri trusted actual callback route 550 * @return correlation-only Returned or a fixed value-free rejection 551 * @throws NullPointerException if a required argument is null 552 * @throws OidcLogoutException if configuration, budget, interruption, provider or store uncertainty prevents completion 553 * @since 1.0.0 554 */ 555 @CheckReturnValue 556 public @NonNull OidcLogoutResult completeLogoutResult(@NonNull String rawQuery, @NonNull PendingOidcLogoutSource source, @NonNull URI actualCallbackUri) { 557 requireNonNull(rawQuery); requireNonNull(source); requireNonNull(actualCallbackUri); Deadline deadline = Deadline.fromNow(this.totalDeadline); OidcLogoutSupport.active(deadline); 558 URI callback = requireLogoutConfiguration(); 559 if (!callback.toString().equals(actualCallbackUri.toString())) return OidcLogoutResult.rejected(OidcLogoutResult.Reason.CALLBACK_MISMATCH); 560 String state; 561 try { state = OidcLogoutSupport.returnedState(rawQuery); } 562 catch (IllegalArgumentException malformed) { return OidcLogoutResult.rejected(OidcLogoutResult.Reason.MALFORMED_RETURN); } 563 return source.complete(state, this.issuer, this.clientId, callback, this.clock, deadline); 564 } 565 566 private @NonNull URI requireLogoutConfiguration() { 567 if (this.postLogoutRedirectUri == null) throw OidcLogoutSupport.failure(OidcLogoutException.Reason.LOGOUT_NOT_CONFIGURED); 568 return this.postLogoutRedirectUri; 569 } 570 private @NonNull ProviderState logoutProvider(@NonNull Deadline deadline) { 571 OidcLogoutSupport.active(deadline); 572 if (this.cache != null) return this.cache.get(deadline); 573 boolean locked = false; 574 try { 575 locked = this.stateLock.tryLock(OidcLogoutSupport.remaining(deadline).toNanos(), java.util.concurrent.TimeUnit.NANOSECONDS); 576 if (!locked) throw OidcLogoutSupport.failure(OidcLogoutException.Reason.BUDGET_EXHAUSTED); 577 OidcLogoutSupport.active(deadline); return requireNonNull(this.state); 578 } catch (InterruptedException interrupted) { Thread.currentThread().interrupt(); throw OidcLogoutSupport.failure(OidcLogoutException.Reason.INTERRUPTED); } 579 finally { if (locked) this.stateLock.unlock(); } 580 } 581 private @NonNull Instant logoutClock(@NonNull Deadline deadline) { 582 OidcLogoutSupport.active(deadline); 583 try { java.time.Instant now = requireNonNull(this.clock.instant()); OidcLogoutSupport.active(deadline); return now; } 584 catch (OidcLogoutException failure) { throw failure; } 585 catch (VirtualMachineError fatal) { throw fatal; } 586 catch (RuntimeException | Error unavailable) { OidcLogoutSupport.active(deadline); throw OidcLogoutSupport.failure(OidcLogoutException.Reason.PROVIDER_UNAVAILABLE); } 587 } 588 589 private @NonNull OidcLogoutHint checkedLogoutHint(@NonNull OidcSessionReference reference, @NonNull String compact, @NonNull Deadline deadline) { 590 try { OidcLogoutHint hint = new OidcLogoutHint(reference, compact); OidcLogoutSupport.active(deadline); return hint; } 591 catch (OidcLogoutException failure) { OidcLogoutSupport.active(deadline); throw failure; } 592 catch (VirtualMachineError fatal) { throw fatal; } 593 catch (RuntimeException | Error unavailable) { OidcLogoutSupport.active(deadline); throw OidcLogoutSupport.failure(OidcLogoutException.Reason.PROVIDER_UNAVAILABLE); } 594 } 595 596 private void checkLogoutReference(@NonNull OidcSessionReference original, @NonNull Deadline deadline) { 597 OidcLogoutSupport.active(deadline); 598 try { 599 OidcLogoutSupport.client(this.clientId); OidcLogoutSupport.text(this.issuer, OidcLogoutSupport.FIELD_LIMIT); 600 if (this.issuerPolicy.isMicrosoftEntra()) { 601 original.checkMicrosoftEntraClient(this.clientId); 602 String actualIssuer = ((com.revetsec.json.JsonString) requireNonNull(original.continuityClaims().getMembers().get("iss"))).getValue(); 603 OidcLogoutSupport.text(actualIssuer, OidcLogoutSupport.FIELD_LIMIT); 604 this.issuerPolicy.checkTenant(requireNonNull(OidcIssuerPolicy.tenantFromIssuer(actualIssuer)), deadline); 605 } else original.checkClient(this.issuer, this.clientId); 606 } catch (OidcValidationException | IllegalArgumentException invalid) { 607 OidcLogoutSupport.active(deadline); throw OidcLogoutSupport.failure(OidcLogoutException.Reason.HINT_MISMATCH); 608 } catch (RuntimeException unavailable) { 609 OidcLogoutSupport.active(deadline); throw OidcLogoutSupport.failure(OidcLogoutException.Reason.PROVIDER_UNAVAILABLE); 610 } 611 OidcLogoutSupport.active(deadline); 612 } 613 614 /** 615 * Redacts client configuration. 616 * 617 * @return a redacted description 618 * @since 1.0.0 619 */ 620 @Override public @NonNull String toString() { return "OidcClient{configuration=<redacted>}"; } 621 /** 622 * Mutable OIDC client configuration. Null restores an optional property's default. 623 * @author <a href="https://www.revetkn.com">Mark Allen</a> 624 * @since 1.0.0 625 */ 626 @NotThreadSafe 627 @CheckReturnValue 628 public static final class Builder { 629 private final String issuer; 630 private final @Nullable OidcProviderMetadata metadata; 631 private @Nullable String clientId; 632 private ClientAuthentication authentication = ClientAuthentication.noneInstance(); 633 private @Nullable URI redirectUri; 634 private @Nullable URI postLogoutRedirectUri; 635 private Set<String> scopes = Set.of(); 636 private List<URI> resources = List.of(); 637 private Set<String> acrValues = Set.of(); 638 private @Nullable List<String> acrPreferences; 639 private Set<String> trustedAudiences = Set.of(); 640 private Set<String> trustedAuthorizedParties = Set.of(); 641 private Set<JwsAlgorithm> algorithms = Set.of(JwsAlgorithm.RS256); 642 private Set<OidcCompatibilityMode> compatibility = Set.of(); 643 private @Nullable JwksSource keySource; 644 private @Nullable JwsAlgorithm userInfoAlgorithm; 645 private Duration clockSkew = Duration.ofSeconds(60); 646 private Duration maximumIdTokenAge = Duration.ofMinutes(5); 647 private Duration pendingLifetime = Limits.PENDING_STATE_LIFETIME.getDefaultDuration(); 648 private Duration requestTimeout = Duration.ofSeconds(10); 649 private Duration totalDeadline = Duration.ofSeconds(15); 650 private Clock clock = Clock.systemUTC(); 651 private @Nullable HttpClient httpClient; 652 private OutboundUriPolicy policy = OutboundUriPolicy.defaultInstance(); 653 private OidcObserver observer = OidcObserver.disabledInstance(); 654 private OidcIssuerPolicy issuerPolicy = OidcIssuerPolicy.exactInstance(); 655 private IssuerParameterPolicy issuerParameterPolicy = IssuerParameterPolicy.METADATA_DRIVEN; 656 private boolean requirePkceAdvertised; 657 private boolean allowInsecureLoopback; 658 private boolean acknowledgeUnpatchedRuntime; 659 private Duration minimumTimeToLive = Limits.DISCOVERY_MINIMUM_TIME_TO_LIVE.getDefaultDuration(); 660 private Duration defaultTimeToLive = Limits.DISCOVERY_DEFAULT_TIME_TO_LIVE.getDefaultDuration(); 661 private Duration maximumTimeToLive = Limits.DISCOVERY_MAXIMUM_TIME_TO_LIVE.getDefaultDuration(); 662 private Duration discoveryCooldown = Limits.DISCOVERY_COOLDOWN.getDefaultDuration(); 663 private Builder(@NonNull String issuer, @Nullable OidcProviderMetadata metadata) { this.issuer = requireNonNull(issuer); this.metadata = metadata; } 664 /** 665 * Sets the registered nonempty client identifier. 666 * 667 * @param value value, or null to restore the default 668 * @return this builder 669 * @since 1.0.0 670 */ 671 public @NonNull Builder clientId(@Nullable String value) { this.clientId = value; return this; } 672 /** 673 * Sets the token endpoint authentication; default public client. 674 * 675 * @param value value, or null to restore the default 676 * @return this builder 677 * @since 1.0.0 678 */ 679 public @NonNull Builder clientAuthentication(@Nullable ClientAuthentication value) { this.authentication = value == null ? ClientAuthentication.noneInstance() : value; return this; } 680 /** 681 * Sets the exact registered callback URI. 682 * 683 * @param value value, or null to restore the default 684 * @return this builder 685 * @since 1.0.0 686 */ 687 public @NonNull Builder redirectUri(@Nullable URI value) { this.redirectUri = value; return this; } 688 /** 689 * Sets one fixed registered logout callback, independent of the login callback. It must be HTTPS (or explicit 690 * test loopback), at most 2048 UTF8 bytes, without query, fragment or userinfo. Null disables logout. 691 * @param value fixed callback, or null for absent 692 * @return this builder 693 * @since 1.0.0 694 */ 695 public @NonNull Builder postLogoutRedirectUri(@Nullable URI value) { this.postLogoutRedirectUri = value; return this; } 696 697 /** 698 * Sets the complete default scopes, in addition to openid. 699 * 700 * @param value value, or null to restore the default 701 * @return this builder 702 * @since 1.0.0 703 */ 704 public @NonNull Builder scopes(@Nullable Set<@NonNull String> value) { this.scopes = value == null ? Set.of() : AuthorizationRequestOptions.builder().scopes(value).build().getScopes(); return this; } 705 /** 706 * Sets the complete default resource indicators. 707 * 708 * @param value value, or null to restore the default 709 * @return this builder 710 * @since 1.0.0 711 */ 712 public @NonNull Builder resources(@Nullable List<@NonNull URI> value) { this.resources = value == null ? List.of() : AuthorizationRequestOptions.builder().resources(value).build().getResources(); return this; } 713 /** 714 * Sets the complete acceptable ACR defaults. 715 * 716 * @param value value, or null to restore the default 717 * @return this builder 718 * @since 1.0.0 719 */ 720 public @NonNull Builder requiredAcrValues(@Nullable Set<@NonNull String> value) { this.acrValues = value == null ? Set.of() : OidcAuthenticationOptions.requireAcrValues(value); return this; } 721 /** 722 * Sets ordered acr_values request preferences, independent of local acceptance. Null derives a deterministic 723 * lexical request list from the effective acceptance set; an empty list omits the request parameter. 724 * @param value distinct nonempty visible-ASCII preferences, or null 725 * @return this builder 726 * @throws IllegalArgumentException if a value is malformed or duplicated 727 * @since 1.0.0 728 */ 729 public @NonNull Builder acrPreferences(@Nullable List<@NonNull String> value) { this.acrPreferences = value == null ? null : OidcAuthenticationOptions.requireAcrPreferences(value); return this; } 730 731 /** 732 * Sets the complete additional trusted audience set. 733 * 734 * @param value value, or null to restore the default 735 * @return this builder 736 * @since 1.0.0 737 */ 738 public @NonNull Builder trustedAudiences(@Nullable Set<@NonNull String> value) { this.trustedAudiences = value == null ? Set.of() : Set.copyOf(value); return this; } 739 /** 740 * Sets the complete additional trusted authorized-party set. 741 * 742 * @param value value, or null to restore the default 743 * @return this builder 744 * @since 1.0.0 745 */ 746 public @NonNull Builder trustedAuthorizedParties(@Nullable Set<@NonNull String> value) { this.trustedAuthorizedParties = value == null ? Set.of() : Set.copyOf(value); return this; } 747 /** 748 * Sets the complete ID-token algorithm allowlist; default RS256. 749 * 750 * @param value value, or null to restore the default 751 * @return this builder 752 * @since 1.0.0 753 */ 754 public @NonNull Builder idTokenSigningAlgorithms(@Nullable Set<@NonNull JwsAlgorithm> value) { this.algorithms = value == null ? Set.of(JwsAlgorithm.RS256) : Set.copyOf(value); return this; } 755 /** 756 * Sets the complete per-client compatibility-mode set. Null restores no modes. Enabling HMAC does not change 757 * the default RS256 allowlist; explicitly name HS algorithms and configure confidential client authentication. 758 * Secret suppliers are checked once at build and once per credentialed token POST, before I/O. The exact 759 * secret used for that POST verifies its ID token; a later rotation cannot change the call's key. 760 * @param value modes, or null to restore the default 761 * @return this builder 762 * @since 1.0.0 763 */ 764 public @NonNull Builder compatibility(@Nullable Set<@NonNull OidcCompatibilityMode> value) { 765 this.compatibility = value == null ? Set.of() : Set.copyOf(value); return this; 766 } 767 /** 768 * Sets the exact registered signed-UserInfo algorithm. Null restores JSON responses. This allowlist is separate 769 * from the ID-token allowlist; an advertised UserInfo capability set must include it. HMAC compatibility is not 770 * enabled. JSON cannot replace a configured signed response. 771 * @param value registered signing algorithm, or null for JSON 772 * @return this builder 773 * @since 1.0.0 774 */ 775 public @NonNull Builder userInfoSignedResponseAlgorithm(@Nullable JwsAlgorithm value) { this.userInfoAlgorithm = value; return this; } 776 /** 777 * Sets the advanced signing-key source; share only within the same exact issuer trust boundary, 778 * or with the same Entra issuer-policy instance. Distinct tenant callbacks are not equivalent. 779 * 780 * @param value value, or null to restore the default 781 * @return this builder 782 * @since 1.0.0 783 */ 784 public @NonNull Builder jwksSource(@Nullable JwksSource value) { this.keySource = value; return this; } 785 /** 786 * Sets the time skew, zero to five minutes. 787 * 788 * @param value value, or null to restore the default 789 * @return this builder 790 * @since 1.0.0 791 */ 792 public @NonNull Builder clockSkew(@Nullable Duration value) { this.clockSkew = value == null ? Duration.ofSeconds(60) : Limits.JOSE_CLOCK_SKEW.require(value); return this; } 793 /** 794 * Sets the maximum ID-token age plus skew. 795 * 796 * @param value value, or null to restore the default 797 * @return this builder 798 * @since 1.0.0 799 */ 800 public @NonNull Builder maximumIdTokenAge(@Nullable Duration value) { this.maximumIdTokenAge = value == null ? Duration.ofMinutes(5) : Limits.ID_TOKEN_MAXIMUM_AGE.require(value); return this; } 801 /** 802 * Sets the pending lifetime, one to sixty minutes. 803 * 804 * @param value value, or null to restore the default 805 * @return this builder 806 * @since 1.0.0 807 */ 808 public @NonNull Builder pendingAuthorizationLifetime(@Nullable Duration value) { this.pendingLifetime = value == null ? Limits.PENDING_STATE_LIFETIME.getDefaultDuration() : Limits.PENDING_STATE_LIFETIME.require(value); return this; } 809 /** 810 * Sets the per-exchange timeout. 811 * 812 * @param value value, or null to restore the default 813 * @return this builder 814 * @since 1.0.0 815 */ 816 public @NonNull Builder requestTimeout(@Nullable Duration value) { this.requestTimeout = value == null ? Duration.ofSeconds(10) : Limits.REQUEST_TIMEOUT.require(value); return this; } 817 /** 818 * Sets the deadline shared by discovery, code exchange and key lookup. 819 * 820 * @param value value, or null to restore the default 821 * @return this builder 822 * @since 1.0.0 823 */ 824 public @NonNull Builder totalDeadline(@Nullable Duration value) { this.totalDeadline = value == null ? Duration.ofSeconds(15) : Limits.TOTAL_DEADLINE.require(value); return this; } 825 /** 826 * Sets the clock for pending state, keys and claims. 827 * 828 * @param value value, or null to restore the default 829 * @return this builder 830 * @since 1.0.0 831 */ 832 public @NonNull Builder clock(@Nullable Clock value) { this.clock = value == null ? Clock.systemUTC() : value; return this; } 833 /** 834 * Sets the application-managed HTTP client. It must use {@code HttpClient.Redirect.NEVER} and have no 835 * {@code Authenticator} or {@code CookieHandler}; build rejects noncompliance without a network request. 836 * Null restores the lazy default. The application owns TLS, proxy and egress controls beyond URI text policy. 837 * 838 * @param value value, or null to restore the default 839 * @return this builder 840 * @since 1.0.0 841 */ 842 public @NonNull Builder httpClient(@Nullable HttpClient value) { this.httpClient = value; return this; } 843 /** 844 * Sets the outbound URI policy. 845 * 846 * @param value value, or null to restore the default 847 * @return this builder 848 * @since 1.0.0 849 */ 850 public @NonNull Builder outboundUriPolicy(@Nullable OutboundUriPolicy value) { this.policy = value == null ? OutboundUriPolicy.defaultInstance() : value; return this; } 851 /** 852 * Sets the caller-thread observer. 853 * 854 * @param value value, or null to restore the default 855 * @return this builder 856 * @since 1.0.0 857 */ 858 public @NonNull Builder observer(@Nullable OidcObserver value) { this.observer = value == null ? OidcObserver.disabledInstance() : value; return this; } 859 /** 860 * Selects exact validation or the fixed Entra common/organizations policy. Null restores exact validation. 861 * Build performs no tenant callback, key lookup or network request. HMAC ID tokens are incompatible. 862 * @param value selected issuer policy, or null to restore exact 863 * @return this builder 864 * @since 1.0.0 865 */ 866 public @NonNull Builder issuerPolicy(@Nullable OidcIssuerPolicy value) { this.issuerPolicy = value == null ? OidcIssuerPolicy.exactInstance() : value; return this; } 867 /** 868 * Sets the callback issuer policy. 869 * 870 * @param value value, or null to restore the default 871 * @return this builder 872 * @since 1.0.0 873 */ 874 public @NonNull Builder issuerParameterPolicy(@Nullable IssuerParameterPolicy value) { this.issuerParameterPolicy = value == null ? IssuerParameterPolicy.METADATA_DRIVEN : value; return this; } 875 /** 876 * Sets whether S256 advertisement is required. 877 * 878 * @param value the flag, or null to restore false 879 * @return this builder 880 * @since 1.0.0 881 */ 882 public @NonNull Builder requirePkceAdvertised(@Nullable Boolean value) { this.requirePkceAdvertised = Boolean.TRUE.equals(value); return this; } 883 /** 884 * Sets whether plain HTTP is allowed for literal loopback tests. 885 * 886 * @param value the flag, or null to restore false 887 * @return this builder 888 * @since 1.0.0 889 */ 890 public @NonNull Builder allowInsecureLoopback(@Nullable Boolean value) { this.allowInsecureLoopback = Boolean.TRUE.equals(value); return this; } 891 /** 892 * Sets explicit acknowledgment of runtime risk. 893 * 894 * @param value the flag, or null to restore false 895 * @return this builder 896 * @since 1.0.0 897 */ 898 public @NonNull Builder acknowledgeUnpatchedRuntime(@Nullable Boolean value) { this.acknowledgeUnpatchedRuntime = Boolean.TRUE.equals(value); return this; } 899 /** 900 * Sets the lowest discovery cache lifetime. 901 * @param value duration, or null to restore the default 902 * @return this builder 903 * @since 1.0.0 904 */ 905 public @NonNull Builder minimumTimeToLive(@Nullable Duration value) { this.minimumTimeToLive = value == null ? Limits.DISCOVERY_MINIMUM_TIME_TO_LIVE.getDefaultDuration() : Limits.DISCOVERY_MINIMUM_TIME_TO_LIVE.require(value); return this; } 906 /** 907 * Sets the fallback discovery cache lifetime. 908 * @param value duration, or null to restore the default 909 * @return this builder 910 * @since 1.0.0 911 */ 912 public @NonNull Builder defaultTimeToLive(@Nullable Duration value) { this.defaultTimeToLive = value == null ? Limits.DISCOVERY_DEFAULT_TIME_TO_LIVE.getDefaultDuration() : Limits.DISCOVERY_DEFAULT_TIME_TO_LIVE.require(value); return this; } 913 /** 914 * Sets the highest discovery cache lifetime. 915 * @param value duration, or null to restore the default 916 * @return this builder 917 * @since 1.0.0 918 */ 919 public @NonNull Builder maximumTimeToLive(@Nullable Duration value) { this.maximumTimeToLive = value == null ? Limits.DISCOVERY_MAXIMUM_TIME_TO_LIVE.getDefaultDuration() : Limits.DISCOVERY_MAXIMUM_TIME_TO_LIVE.require(value); return this; } 920 /** 921 * Sets the discovery attempt window and initial failure backoff. 922 * @param value duration, or null to restore the default 923 * @return this builder 924 * @since 1.0.0 925 */ 926 public @NonNull Builder discoveryCooldown(@Nullable Duration value) { this.discoveryCooldown = value == null ? Limits.DISCOVERY_COOLDOWN.getDefaultDuration() : Limits.DISCOVERY_COOLDOWN.require(value); return this; } 927 /** 928 * Validates issuer, explicit metadata and configuration without I/O or new threads. 929 * @return the client 930 * @since 1.0.0 931 */ 932 public @NonNull OidcClient build() { 933 if (this.clientId == null || this.redirectUri == null) 934 throw new IllegalStateException("An OIDC client requires a client ID and callback URI."); 935 if (this.clientId.isEmpty() || this.algorithms.isEmpty() 936 || this.trustedAudiences.contains("") || this.trustedAuthorizedParties.contains("")) 937 throw new IllegalArgumentException("An OIDC client requires a client ID, callback URI and algorithm allowlist."); 938 if (this.postLogoutRedirectUri != null) { 939 OidcLogoutSupport.callback(this.postLogoutRedirectUri, this.allowInsecureLoopback); 940 OidcLogoutSupport.client(this.clientId); OidcLogoutSupport.text(this.issuer, OidcLogoutSupport.FIELD_LIMIT); 941 } 942 this.issuerPolicy.checkConfiguredIssuer(this.issuer); 943 if (this.metadata != null) this.issuerPolicy.checkMetadata(this.metadata); 944 Set<JwsAlgorithm> hmac = hmacAlgorithms(this.algorithms); 945 if (this.issuerPolicy.isMicrosoftEntra() && !hmac.isEmpty()) throw new IllegalArgumentException("Entra issuer policy requires asymmetric ID tokens."); 946 if (!hmac.isEmpty() && !this.compatibility.contains(OidcCompatibilityMode.HMAC_ID_TOKENS)) 947 throw new IllegalArgumentException("HMAC ID-token compatibility is not enabled."); 948 OidcTransactionAccess.get().checkHmacAuthentication(this.authentication, hmac); 949 if (this.userInfoAlgorithm != null && Set.of(JwsAlgorithm.HS256, JwsAlgorithm.HS384, JwsAlgorithm.HS512).contains(this.userInfoAlgorithm)) 950 throw new IllegalArgumentException("HMAC UserInfo compatibility is not enabled."); 951 Limits.requireDiscoveryTimeToLiveOrder(this.minimumTimeToLive, this.defaultTimeToLive, this.maximumTimeToLive, this.discoveryCooldown); 952 if (this.metadata != null) checkMetadata(this.metadata, this.algorithms, this.policy, this.allowInsecureLoopback, this.userInfoAlgorithm); 953 OAuthClient.Builder engine = this.metadata == null ? OAuthClient.withIssuer(this.issuer) 954 : OAuthClient.withAuthorizationServerMetadata(this.metadata.oauthMetadata()); 955 OAuthClient oauth = engine.clientId(this.clientId).clientAuthentication(this.authentication).redirectUri(this.redirectUri) 956 .scopes(this.scopes).resources(this.resources).issuerParameterPolicy(this.issuerParameterPolicy) 957 .requirePkceAdvertised(this.requirePkceAdvertised).pendingAuthorizationLifetime(this.pendingLifetime) 958 .httpClient(this.httpClient).outboundUriPolicy(this.policy).requestTimeout(this.requestTimeout) 959 .totalDeadline(this.totalDeadline).clock(this.clock).observer(this.observer) 960 .allowInsecureLoopback(this.allowInsecureLoopback).acknowledgeUnpatchedRuntime(this.acknowledgeUnpatchedRuntime).build(); 961 OidcClient client = new OidcClient(this, oauth); 962 if (this.issuerPolicy.isMicrosoftEntra()) ObserverDispatch.dispatch(this.observer, OidcObserver::didEnableMicrosoftEntraMultiTenant); 963 for (OidcCompatibilityMode mode : this.compatibility) 964 ObserverDispatch.dispatch(this.observer, observer -> observer.didEnableCompatibilityMode(mode)); 965 return client; 966 } 967 } 968}