001/*
002 * Licensed to the Apache Software Foundation (ASF) under one or more
003 * contributor license agreements.  See the NOTICE file distributed with
004 * this work for additional information regarding copyright ownership.
005 * The ASF licenses this file to You under the Apache License, Version 2.0
006 * (the "License"); you may not use this file except in compliance with
007 * the License.  You may obtain a copy of the License at
008 *
009 *      http://www.apache.org/licenses/LICENSE-2.0
010 *
011 * Unless required by applicable law or agreed to in writing, software
012 * distributed under the License is distributed on an "AS IS" BASIS,
013 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
014 * See the License for the specific language governing permissions and
015 * limitations under the License.
016 */
017package org.apache.juneau.rest.server.auth.oidc.rp;
018
019import static org.apache.juneau.commons.utils.Shorts.*;
020import static org.apache.juneau.commons.utils.StringUtils.*;
021
022import java.io.*;
023import java.net.*;
024import java.nio.charset.*;
025import java.security.*;
026import java.time.*;
027import java.util.*;
028import java.util.function.*;
029
030import org.apache.juneau.commons.utils.*;
031import org.apache.juneau.rest.server.auth.*;
032import org.apache.juneau.rest.auth.oauth.flow.*;
033import org.apache.juneau.rest.auth.oauth.oidc.*;
034
035import com.nimbusds.jose.*;
036import com.nimbusds.jose.jwk.*;
037import com.nimbusds.jose.jwk.source.*;
038import com.nimbusds.jose.proc.*;
039import com.nimbusds.jwt.*;
040import com.nimbusds.jwt.proc.*;
041import com.nimbusds.oauth2.sdk.http.*;
042import com.nimbusds.oauth2.sdk.id.*;
043import com.nimbusds.oauth2.sdk.pkce.*;
044import com.nimbusds.oauth2.sdk.token.*;
045import com.nimbusds.openid.connect.sdk.*;
046import com.nimbusds.openid.connect.sdk.claims.*;
047import com.nimbusds.openid.connect.sdk.validators.*;
048
049import jakarta.servlet.http.*;
050
051/**
052 * Facade orchestrating an OpenID Connect Authorization-Code-with-PKCE <i>Relying Party</i> login flow on
053 * top of the {@code juneau-rest-server-auth-oauth} building blocks.
054 *
055 * <p>
056 * A single instance wires the login / callback / logout endpoints plus the session SPI for one IdP.  The
057 * application mounts the three endpoints as explicit {@code @RestGet} methods that delegate to this
058 * facade &mdash; there are no auto-mounted servlet routes (URL ownership stays with the app):
059 *
060 * <p class='bjava'>
061 *    <ja>@Rest</ja>(path=<js>"/auth"</js>)
062 *    <jk>public class</jk> LoginResource <jk>extends</jk> BasicRestServlet {
063 *
064 *       <jk>private final</jk> OidcRelyingParty <jf>rp</jf> = OidcRelyingParty.<jsm>create</jsm>()
065 *          .issuer(URI.<jsm>create</jsm>(<js>"https://accounts.google.com"</js>))
066 *          .clientId(<js>"web-app"</js>)
067 *          .clientSecret(<jv>env</jv>(<js>"OIDC_CLIENT_SECRET"</js>))
068 *          .redirectUri(URI.<jsm>create</jsm>(<js>"https://app.example.com/auth/callback"</js>))
069 *          .scope(<js>"openid"</js>, <js>"profile"</js>, <js>"email"</js>)
070 *          .sessionStore(SignedCookieSessionStore.<jsm>create</jsm>().signingKey(<jv>env</jv>(<js>"SESSION_KEY"</js>)).build())
071 *          .build();
072 *
073 *       <ja>@RestGet</ja>(path=<js>"/login"</js>)
074 *       <jk>public void</jk> login(RestRequest <jv>req</jv>, RestResponse <jv>res</jv>) <jk>throws</jk> Exception {
075 *          <jf>rp</jf>.startLogin(<jv>req</jv>, <jv>res</jv>);
076 *       }
077 *
078 *       <ja>@RestGet</ja>(path=<js>"/callback"</js>)
079 *       <jk>public void</jk> callback(RestRequest <jv>req</jv>, RestResponse <jv>res</jv>) <jk>throws</jk> Exception {
080 *          <jf>rp</jf>.completeLogin(<jv>req</jv>, <jv>res</jv>);
081 *       }
082 *
083 *       <ja>@RestGet</ja>(path=<js>"/logout"</js>)
084 *       <jk>public void</jk> logout(RestRequest <jv>req</jv>, RestResponse <jv>res</jv>) <jk>throws</jk> Exception {
085 *          <jf>rp</jf>.logout(<jv>req</jv>, <jv>res</jv>);
086 *       }
087 *    }
088 * </p>
089 *
090 * <p>
091 * Register {@link #authFilter()} in the servlet filter chain (or {@code AuthFilterChain}) so each request
092 * resolves the session cookie into a {@link ClaimsPrincipal} for {@code RoleBasedRestGuard} /
093 * {@code @Auth Principal}.
094 *
095 * <h2 class='section'>Security</h2>
096 * <ul>
097 *    <li>{@code state} and {@code nonce} are single-use and TTL-bounded (default 5&nbsp;min); a
098 *       missing / replayed value fails the callback.
099 *    <li>PKCE S256 is enforced end-to-end.
100 *    <li>The ID token is validated for signature, {@code iss}, {@code aud}/{@code azp}, {@code exp}, and
101 *       {@code nonce} (see {@link IdTokenValidatorAdapter}).
102 *    <li>The session id is freshly generated on login (no pre-auth fixation).
103 *    <li>Auth responses set {@code Cache-Control: no-store}; tokens are never logged.
104 *    <li>The session cookie is {@code HttpOnly} + {@code Secure} + {@code SameSite} by default.
105 * </ul>
106 *
107 * <h2 class='section'>See Also:</h2><ul>
108 *    <li class='jc'>{@link SessionStore}
109 *    <li class='jc'>{@link OidcSessionAuthFilter}
110 *    <li class='link'><a class="doclink" href="https://juneau.apache.org/docs/topics/OidcRelyingParty">OIDC Relying Party Login (juneau-rest-server-auth-oidc-rp)</a>
111 *    <li class='link'><a class="doclink" href="https://openid.net/specs/openid-connect-core-1_0.html">OpenID Connect Core 1.0</a>
112 * </ul>
113 *
114 * @since 10.0.0
115 */
116@SuppressWarnings({
117   "java:S1192", // Duplicate string literals are OIDC protocol parameter names and claim names; intentional
118   "java:S3077", // The lazily built metadata/code-flow/validator/JWK/logout-processor caches are volatile references to effectively immutable objects, published once without compound updates
119   "java:S9358" // Ternary chooses a different constructor/null vs value; moving it inside one call is not equivalent.
120})
121public class OidcRelyingParty {
122
123   private static final String DEFAULT_COOKIE_NAME = "JUNEAU_OIDC_SESSION";
124   private static final String DEFAULT_ROLES_CLAIM = "scope";
125   private static final Duration DEFAULT_SESSION_TTL = Duration.ofHours(8);
126   private static final int USERINFO_TIMEOUT_MS = 5_000;
127
128   /**
129    * Static creator.
130    *
131    * @return A new builder.
132    */
133   public static Builder create() {
134      return new Builder();
135   }
136
137   /**
138    * Builder.
139    */
140   public static class Builder {
141      URI issuer;
142      OidcMetadata metadata;
143      String clientId;
144      Supplier<String> clientSecretSupplier;
145      URI redirectUri;
146      URI postLogoutRedirectUri;
147      String postLoginRedirect = "/";
148      Set<String> scopes = st();
149      SessionStore sessionStore;
150      LoginStateStore loginStateStore;
151      String rolesClaim = DEFAULT_ROLES_CLAIM;
152      Duration stateNonceTtl = InMemoryLoginStateStore.DEFAULT_TTL;
153      int ephemeralMaxEntries = InMemoryLoginStateStore.DEFAULT_MAX_ENTRIES;
154      Duration sessionTtl = DEFAULT_SESSION_TTL;
155      String cookieName = DEFAULT_COOKIE_NAME;
156      boolean cookieSecure = true;
157      boolean cookieHttpOnly = true;
158      String cookieSameSite = "Lax";
159      Consumer<HTTPRequest> httpRequestConfigurator;
160      Consumer<AuthenticationRequest.Builder> authenticationRequestCustomizer;
161      JWSAlgorithm[] idTokenAlgorithms;
162      int clockSkewSeconds = 60;
163      JWKSet jwkSet;
164      JWKSource<SecurityContext> jwkSource;
165      Set<String> userInfoClaims = st();
166      Clock clock = Clock.systemUTC();
167
168      /** Constructor. */
169      protected Builder() {}
170
171      /**
172       * Sets the IdP issuer URL.  OIDC discovery resolves the endpoints + JWKS URI lazily.  Either
173       * this or {@link #metadata(OidcMetadata)} is required.
174       *
175       * <p>
176       * The issuer (and every endpoint discovered from it) must use <js>"https"</js> or target a loopback
177       * host; discovery, JWKS, and token exchanges carry trust-anchor key material and client credentials, so
178       * a plaintext transport to a non-loopback host is rejected.
179       *
180       * @param value The issuer URL.  Must not be <jk>null</jk> and must use HTTPS or target a loopback host.
181       * @return This object.
182       */
183      public Builder issuer(URI value) {
184         issuer = UriUtils.assertSecureOrLoopback(reqnn("value", value));
185         return this;
186      }
187
188      /**
189       * Sets the IdP metadata explicitly, bypassing discovery.  Either this or {@link #issuer(URI)}
190       * is required.
191       *
192       * @param value The metadata.  Must not be <jk>null</jk>.
193       * @return This object.
194       */
195      public Builder metadata(OidcMetadata value) {
196         metadata = reqnn("value", value);
197         return this;
198      }
199
200      /**
201       * Sets the OAuth client id.  Required.
202       *
203       * @param value The client id.  Must not be <jk>null</jk> or blank.
204       * @return This object.
205       */
206      public Builder clientId(String value) {
207         clientId = reqnb("value", value);
208         return this;
209      }
210
211      /**
212       * Sets the client secret.  May be omitted for public clients (PKCE-only).
213       *
214       * @param value The client secret.  Must not be <jk>null</jk> or blank.
215       * @return This object.
216       */
217      public Builder clientSecret(String value) {
218         reqnb("value", value);
219         clientSecretSupplier = () -> value;
220         return this;
221      }
222
223      /**
224       * Sets the client secret via a supplier.
225       *
226       * @param value The supplier.  Must not be <jk>null</jk>.
227       * @return This object.
228       */
229      public Builder clientSecretSupplier(Supplier<String> value) {
230         clientSecretSupplier = reqnn("value", value);
231         return this;
232      }
233
234      /**
235       * Sets the redirect URI registered with the IdP.  Required.
236       *
237       * @param value The redirect URI.  Must not be <jk>null</jk>.
238       * @return This object.
239       */
240      public Builder redirectUri(URI value) {
241         redirectUri = reqnn("value", value);
242         return this;
243      }
244
245      /**
246       * Sets the post-logout redirect URI passed to the IdP end-session endpoint.
247       *
248       * @param value The post-logout redirect URI.  Must not be <jk>null</jk>.
249       * @return This object.
250       */
251      public Builder postLogoutRedirectUri(URI value) {
252         postLogoutRedirectUri = reqnn("value", value);
253         return this;
254      }
255
256      /**
257       * Sets the default post-login redirect target (when the login request supplied no safe
258       * {@code redirect} parameter).  Defaults to {@code "/"}.
259       *
260       * @param value The default redirect path.  Must not be <jk>null</jk> or blank.
261       * @return This object.
262       */
263      public Builder postLoginRedirect(String value) {
264         postLoginRedirect = reqnb("value", value);
265         return this;
266      }
267
268      /**
269       * Adds requested scopes.  {@code openid} is always included.
270       *
271       * @param values The scopes.
272       * @return This object.
273       */
274      public Builder scope(String...values) {
275         reqnn("values", values);
276         for (var v : values) {
277            reqnb("scope", v);
278            scopes.add(v);
279         }
280         return this;
281      }
282
283      /**
284       * Sets the session store.  Required.
285       *
286       * @param value The session store.  Must not be <jk>null</jk>.
287       * @return This object.
288       */
289      public Builder sessionStore(SessionStore value) {
290         sessionStore = reqnn("value", value);
291         return this;
292      }
293
294      /**
295       * Sets the claim roles are extracted from.  Defaults to {@code "scope"} (whitespace-split);
296       * array claims are also accepted.  Mirrors the {@code OAuthFilter} convention.
297       *
298       * @param value The claim name.  Must not be <jk>null</jk> or blank.
299       * @return This object.
300       */
301      public Builder rolesClaim(String value) {
302         rolesClaim = reqnb("value", value);
303         return this;
304      }
305
306      /**
307       * Sets the single-use TTL the framework enforces for the login-state ({@code state} / {@code nonce} /
308       * PKCE {@code code_verifier}) association.  Defaults to 5 minutes.
309       *
310       * <p>
311       * This is the RP-enforced policy applied to <b>every</b> consumed record &mdash; both the default
312       * {@link InMemoryLoginStateStore} and any custom {@link #loginStateStore(LoginStateStore) injected store}.
313       * The framework mints {@code expiresAt = createdAt + stateNonceTtl} on the record and re-checks it on
314       * consume, so the ceiling holds even for a shared store that fails to expire an entry.  The
315       * {@code (0, }{@link LoginStateStore#MAX_TTL}{@code ]} cap is enforced here (not only in the default
316       * impl's constructor, which is skipped when a custom store is injected).
317       *
318       * @param value The TTL.  Must be positive and not exceed {@link LoginStateStore#MAX_TTL} (30 minutes).
319       * @return This object.
320       */
321      public Builder stateNonceTtl(Duration value) {
322         reqnn("value", value);
323         req(!value.isZero() && !value.isNegative(), "stateNonceTtl must be positive");
324         req(value.compareTo(LoginStateStore.MAX_TTL) <= 0, "stateNonceTtl must not exceed 30 minutes (was %s)", value);
325         stateNonceTtl = value;
326         return this;
327      }
328
329      /**
330       * Sets an optional custom {@link LoginStateStore} for the pending-login ({@code state} &rarr;
331       * {@code nonce} / PKCE {@code code_verifier} / redirect) association.
332       *
333       * <p>
334       * Optional (unlike {@link #sessionStore(SessionStore)}): when omitted the RP uses the shipped per-JVM
335       * {@link InMemoryLoginStateStore}, and behavior is identical to a single-node deployment.  Supply a
336       * shared (Redis / JDBC) implementation to support a clustered deployment where {@code /login} and
337       * {@code /callback} may land on different nodes without sticky sessions &mdash; the same motivation as a
338       * distributed {@link SessionStore}.
339       *
340       * <p>
341       * <b>The store is secret-bearing</b> ({@code code_verifier} + {@code nonce}); read the
342       * {@link LoginStateStore} security contract before implementing one (TLS + locked-down ACL floor,
343       * encryption-at-rest recommended, never log the payload, atomic {@code GETDEL}/Lua single-use consume).
344       * The framework retains authority over the security-critical decisions regardless of the store: it
345       * re-validates {@code redirectTarget} via {@code safeRelativePath} and re-checks {@code expiresAt}
346       * against its own {@link #clock(Clock) clock} on consume, and enforces the
347       * {@link #stateNonceTtl(Duration)} ceiling &mdash; the store persists the record and enforces single-use,
348       * but is treated as a blob store, not a trusted oracle.
349       *
350       * @param value The login-state store.  Must not be <jk>null</jk>.
351       * @return This object.
352       */
353      public Builder loginStateStore(LoginStateStore value) {
354         loginStateStore = reqnn("value", value);
355         return this;
356      }
357
358      /**
359       * Sets the session lifetime (bounded independently of token lifetime).  Defaults to 8 hours.
360       *
361       * @param value The session TTL.  Must be positive.
362       * @return This object.
363       */
364      public Builder sessionTtl(Duration value) {
365         reqnn("value", value);
366         req(!value.isZero() && !value.isNegative(), "sessionTtl must be positive"); // HTT: JaCoCo bytecode artifact; zero and negative are tested by m01/m02 but one short-circuit branch edge remains instrumented
367         sessionTtl = value;
368         return this;
369      }
370
371      /**
372       * Sets the session cookie name.  Defaults to {@code JUNEAU_OIDC_SESSION}.
373       *
374       * @param value The cookie name.  Must not be <jk>null</jk> or blank.
375       * @return This object.
376       */
377      public Builder cookieName(String value) {
378         cookieName = reqnb("value", value);
379         return this;
380      }
381
382      /**
383       * Sets the cookie {@code Secure} flag.  Defaults to <jk>true</jk> (fail-closed).
384       *
385       * @param value The flag.
386       * @return This object.
387       */
388      public Builder cookieSecure(boolean value) {
389         cookieSecure = value;
390         return this;
391      }
392
393      /**
394       * Sets the cookie {@code HttpOnly} flag.  Defaults to <jk>true</jk> (fail-closed).
395       *
396       * @param value The flag.
397       * @return This object.
398       */
399      public Builder cookieHttpOnly(boolean value) {
400         cookieHttpOnly = value;
401         return this;
402      }
403
404      /**
405       * Sets the cookie {@code SameSite} attribute.  Defaults to {@code "Lax"}.
406       *
407       * @param value The SameSite value (e.g. {@code "Lax"} or {@code "Strict"}).  Must not be
408       *    <jk>null</jk> or blank.
409       * @return This object.
410       */
411      public Builder cookieSameSite(String value) {
412         cookieSameSite = reqnb("value", value);
413         return this;
414      }
415
416      /**
417       * Sets a Nimbus {@link HTTPRequest} configurator escape hatch (proxy / TLS / timeouts) applied
418       * to discovery + token + userinfo calls.
419       *
420       * @param value The callback.  Must not be <jk>null</jk>.
421       * @return This object.
422       */
423      public Builder httpRequestConfigurator(Consumer<HTTPRequest> value) {
424         httpRequestConfigurator = reqnn("value", value);
425         return this;
426      }
427
428      /**
429       * Sets a Nimbus {@link com.nimbusds.openid.connect.sdk.AuthenticationRequest.Builder} customizer escape hatch (e.g. {@code prompt},
430       * {@code max_age}, {@code acr_values}) applied to the authorization redirect.
431       *
432       * @param value The callback.  Must not be <jk>null</jk>.
433       * @return This object.
434       */
435      public Builder authenticationRequestCustomizer(Consumer<AuthenticationRequest.Builder> value) {
436         authenticationRequestCustomizer = reqnn("value", value);
437         return this;
438      }
439
440      /**
441       * Sets the ID-token signing-algorithm allowlist.  Defaults to {@code [RS256, ES256]}.
442       *
443       * @param values The allowed algorithms.
444       * @return This object.
445       */
446      public Builder idTokenAlgorithms(JWSAlgorithm...values) {
447         idTokenAlgorithms = reqnn("values", values);
448         return this;
449      }
450
451      /**
452       * Sets the clock-skew tolerance (seconds) for ID-token validation.  Defaults to 60.
453       *
454       * @param value The tolerance in seconds.  Must be non-negative.
455       * @return This object.
456       */
457      public Builder clockSkewSeconds(int value) {
458         req(value >= 0, "clockSkewSeconds must be non-negative (was %s)", value);
459         clockSkewSeconds = value;
460         return this;
461      }
462
463      /**
464       * Injects a fixed JWK set for ID-token / logout-token signature verification, bypassing the
465       * JWKS endpoint.  Useful for tests and static-key deployments.
466       *
467       * @param value The JWK set.  Must not be <jk>null</jk>.
468       * @return This object.
469       */
470      public Builder jwkSet(JWKSet value) {
471         jwkSet = reqnn("value", value);
472         return this;
473      }
474
475      /**
476       * Injects a custom JWK source for ID-token / logout-token signature verification.
477       *
478       * @param value The JWK source.  Must not be <jk>null</jk>.
479       * @return This object.
480       */
481      public Builder jwkSource(JWKSource<SecurityContext> value) {
482         jwkSource = reqnn("value", value);
483         return this;
484      }
485
486      /**
487       * Adds claim names to backfill from the UserInfo endpoint when absent from the ID token.
488       *
489       * <p>
490       * When empty (the default) the UserInfo endpoint is never called &mdash; the {@link Principal}
491       * is built from ID-token claims only.
492       *
493       * @param values The claim names to backfill.
494       * @return This object.
495       */
496      public Builder userInfoClaims(String...values) {
497         reqnn("values", values);
498         for (var v : values) {
499            reqnb("claim", v);
500            userInfoClaims.add(v);
501         }
502         return this;
503      }
504
505      /**
506       * Overrides the clock used for session expiry and the login-state store.  Useful in tests.
507       *
508       * <p>
509       * The login-state {@code expiresAt} is both minted (on {@code startLogin}) and re-checked (on
510       * {@code completeLogin}) against this clock.  In a clustered deployment with a shared
511       * {@link #loginStateStore(LoginStateStore) LoginStateStore}, the ceiling is therefore only as
512       * trustworthy as clock synchronization across nodes; a backend {@code EXPIRE}/TTL is a GC hint, not the
513       * authoritative expiry decision.
514       *
515       * @param value The clock.  Must not be <jk>null</jk>.
516       * @return This object.
517       */
518      public Builder clock(Clock value) {
519         clock = reqnn("value", value);
520         return this;
521      }
522
523      /**
524       * Builds the relying party.
525       *
526       * @return A new {@link OidcRelyingParty}.
527       */
528      public OidcRelyingParty build() {
529         if (issuer == null && metadata == null)
530            throw new IllegalStateException("OidcRelyingParty requires issuer(...) or metadata(...)");
531         if (clientId == null)
532            throw new IllegalStateException("OidcRelyingParty requires clientId(...)");
533         if (redirectUri == null)
534            throw new IllegalStateException("OidcRelyingParty requires redirectUri(...)");
535         if (sessionStore == null)
536            throw new IllegalStateException("OidcRelyingParty requires sessionStore(...)");
537         return new OidcRelyingParty(this);
538      }
539   }
540
541   private final URI issuer;
542   private final String clientId;
543   private final Supplier<String> clientSecretSupplier;
544   private final URI redirectUri;
545   private final URI postLogoutRedirectUri;
546   private final String postLoginRedirect;
547   private final Set<String> scopes;
548   private final SessionStore sessionStore;
549   private final String rolesClaim;
550   private final Duration sessionTtl;
551   private final String cookieName;
552   private final boolean cookieSecure;
553   private final boolean cookieHttpOnly;
554   private final String cookieSameSite;
555   private final Consumer<HTTPRequest> httpRequestConfigurator;
556   private final Consumer<AuthenticationRequest.Builder> authenticationRequestCustomizer;
557   private final JWSAlgorithm[] idTokenAlgorithms;
558   private final int clockSkewSeconds;
559   private final JWKSet jwkSet;
560   private final JWKSource<SecurityContext> injectedJwkSource;
561   private final Set<String> userInfoClaims;
562   private final Clock clock;
563   private final Duration stateNonceTtl;
564   private final LoginStateStore loginStateStore;
565
566   private volatile OidcMetadata metadataCache;
567   private final OidcMetadata explicitMetadata;
568   private volatile OAuthAuthorizationCodeFlow codeFlowCache;
569   private volatile IdTokenValidatorAdapter idTokenValidatorCache;
570   private volatile JWKSource<SecurityContext> jwkSourceCache;
571   private volatile ConfigurableJWTProcessor<SecurityContext> logoutTokenProcessorCache;
572
573   /**
574    * Constructor.
575    *
576    * @param b The builder.
577    */
578   protected OidcRelyingParty(Builder b) {
579      this.issuer = b.issuer;
580      this.explicitMetadata = b.metadata;
581      this.clientId = b.clientId;
582      this.clientSecretSupplier = b.clientSecretSupplier;
583      this.redirectUri = b.redirectUri;
584      this.postLogoutRedirectUri = b.postLogoutRedirectUri;
585      this.postLoginRedirect = b.postLoginRedirect;
586      var s = new LinkedHashSet<String>();
587      s.add("openid");
588      s.addAll(b.scopes);
589      this.scopes = u(s);
590      this.sessionStore = b.sessionStore;
591      this.rolesClaim = b.rolesClaim;
592      this.sessionTtl = b.sessionTtl;
593      this.cookieName = b.cookieName;
594      this.cookieSecure = b.cookieSecure;
595      this.cookieHttpOnly = b.cookieHttpOnly;
596      this.cookieSameSite = b.cookieSameSite;
597      this.httpRequestConfigurator = b.httpRequestConfigurator;
598      this.authenticationRequestCustomizer = b.authenticationRequestCustomizer;
599      this.idTokenAlgorithms = b.idTokenAlgorithms;
600      this.clockSkewSeconds = b.clockSkewSeconds;
601      this.jwkSet = b.jwkSet;
602      this.injectedJwkSource = b.jwkSource;
603      this.userInfoClaims = u(cp(b.userInfoClaims));
604      this.clock = b.clock;
605      this.stateNonceTtl = b.stateNonceTtl;
606      this.loginStateStore = b.loginStateStore != null
607         ? b.loginStateStore
608         : new InMemoryLoginStateStore(b.stateNonceTtl, b.ephemeralMaxEntries, b.clock);
609   }
610
611   //-----------------------------------------------------------------------------------------------------------------
612   // Public flow methods
613   //-----------------------------------------------------------------------------------------------------------------
614
615   /**
616    * Begins the login flow: generates {@code state} + {@code nonce} + PKCE verifier, stores them
617    * single-use, and redirects the user-agent to the IdP authorization endpoint.
618    *
619    * @param req The HTTP request.  An optional {@code redirect} query parameter (a safe relative path)
620    *    is remembered as the post-login target.
621    * @param res The HTTP response.
622    * @throws IOException If the redirect cannot be written.
623    */
624   public void startLogin(HttpServletRequest req, HttpServletResponse res) throws IOException {
625      reqnn("req", req);
626      reqnn("res", res);
627      var state = new State().getValue();
628      var nonce = new Nonce().getValue();
629      var verifier = new CodeVerifier();
630      var challenge = CodeChallenge.compute(CodeChallengeMethod.S256, verifier);
631      var redirectTarget = safeRelativePath(req.getParameter("redirect"));
632      var createdAt = clock.instant();
633      var binding = new State().getValue();
634      var pending = new LoginStateStore.PendingLogin(nonce, verifier.getValue(), redirectTarget, createdAt, createdAt.plus(stateNonceTtl), hashBinding(binding));
635      try {
636         loginStateStore.store(state, pending);
637      } catch (RuntimeException e) {
638         // Fail closed before any authorization URL is issued.  Do NOT chain the raw backend exception as the
639         // cause: a shared-store backend may echo the state/code_verifier into its own message, and
640         // AuthenticationException publishes the cause via getCause(), so a raw chain would re-expose the secret.
641         throw new AuthenticationException("OIDC login-state store unavailable");
642      }
643      var authUrl = codeFlow().buildAuthenticationUrl(state, challenge, nonce, authenticationRequestCustomizer);
644      noStore(res);
645      res.addHeader("Set-Cookie", buildLoginBindingCookie(binding, stateNonceTtl.toSeconds()));
646      res.sendRedirect(authUrl.toString());
647   }
648
649   /**
650    * Completes the login flow: parses the callback, verifies + consumes {@code state}, exchanges the
651    * code (PKCE), validates the ID token (signature / {@code iss} / {@code aud} / {@code exp} /
652    * {@code nonce}), creates a session, sets the session cookie, and redirects to the application.
653    *
654    * @param req The callback HTTP request (carrying {@code code} + {@code state}).
655    * @param res The HTTP response.
656    * @throws IOException If the redirect cannot be written.
657    * @throws AuthenticationException If the callback is an error, the state is missing / replayed, or
658    *    ID-token validation fails.
659    */
660   public void completeLogin(HttpServletRequest req, HttpServletResponse res) throws IOException, AuthenticationException {
661      reqnn("req", req);
662      reqnn("res", res);
663
664      var callbackUri = fullRequestUri(req);
665      AuthenticationResponse parsed;
666      try {
667         parsed = AuthenticationResponseParser.parse(callbackUri);
668      } catch (com.nimbusds.oauth2.sdk.ParseException e) {
669         throw new AuthenticationException(e, "OIDC callback could not be parsed");
670      }
671      if (! parsed.indicatesSuccess()) {
672         var err = parsed.toErrorResponse().getErrorObject();
673         throw new AuthenticationException("OIDC callback returned an error: %s", err == null ? "unknown" : err.getCode()); // HTT: err==null branch requires an error response with no error object, which Nimbus never produces
674      }
675      var success = parsed.toSuccessResponse();
676      if (success.getAuthorizationCode() == null)
677         throw new AuthenticationException("OIDC callback contained no authorization code");
678      var code = success.getAuthorizationCode().getValue();
679      var state = success.getState() == null ? null : success.getState().getValue(); // HTT: null state branch: AuthCode response always carries state per PKCE flow; null branch is defensive dead code
680
681      Optional<LoginStateStore.PendingLogin> consumed;
682      try {
683         consumed = loginStateStore.consume(state);
684      } catch (RuntimeException e) {
685         // Infra failure (backend unreachable) is distinct from a CSRF/replay miss; reject as unavailable
686         // without leaking the payload (do not chain the raw backend exception as cause).
687         throw new AuthenticationException("OIDC login-state store unavailable");
688      }
689      var pending = consumed.orElseThrow(
690         () -> new AuthenticationException("OIDC callback state is missing, expired, or already used"));
691
692      // The login must complete in the same browser that started it: the callback must present the binding cookie
693      // whose hash was stored with the state.
694      if (! bindingMatches(readCookie(req, loginBindingCookieName()), pending.bindingHash()))
695         throw new AuthenticationException("OIDC callback is not bound to the browser that started the login");
696
697      // Fail-closed expiry re-check BEFORE the token exchange: the framework owns the TTL ceiling independently
698      // of the store, so an honest store that failed to expire an over-age record cannot extend usability.  Null
699      // createdAt/expiresAt (a foreign/deserialized blob) is treated as expired, not an NPE->500.
700      if (pending.createdAt() == null || pending.expiresAt() == null || ! clock.instant().isBefore(pending.expiresAt()))
701         throw new AuthenticationException("OIDC callback state is missing, expired, or already used");
702
703      OAuthToken token;
704      try {
705         token = codeFlow().exchange(code, new CodeVerifier(pending.codeVerifier()));
706      } catch (OAuthFlowException e) {
707         throw new AuthenticationException(e, "OIDC token exchange failed");
708      }
709      var idToken = token.idToken().orElseThrow(
710         () -> new AuthenticationException("IdP token response contained no id_token"));
711
712      var principal = idTokenValidator().validate(idToken, pending.nonce());
713      principal = maybeBackfillUserInfo(principal, token);
714
715      var subject = principal.getName();
716      var sid = principal.getClaim("sid", String.class);
717      var roles = extractRoles(principal);
718      var now = clock.instant();
719      var session = new OidcSession(
720         new State().getValue(),
721         subject,
722         sid,
723         principal,
724         roles,
725         o(token),
726         now,
727         now.plus(sessionTtl));
728
729      var cookieValue = sessionStore.createSessionCookieValue(session);
730      noStore(res);
731      res.addHeader("Set-Cookie", buildSetCookie(cookieValue, sessionTtl.toSeconds()));
732      // Re-validate the redirect target on consume: a writable/compromised shared store cannot inject an open
733      // redirect.  A failing re-validation falls back to the operator-configured default (not itself re-sanitized).
734      res.sendRedirect(or(safeRelativePath(pending.redirectTarget()), postLoginRedirect));
735   }
736
737   /**
738    * Logs the user out: invalidates the session, clears the session cookie, and (when the IdP
739    * advertises an end-session endpoint) redirects through it; otherwise redirects to the
740    * post-logout target.
741    *
742    * @param req The HTTP request.
743    * @param res The HTTP response.
744    * @throws IOException If the redirect cannot be written.
745    */
746   public void logout(HttpServletRequest req, HttpServletResponse res) throws IOException {
747      reqnn("req", req);
748      reqnn("res", res);
749      if (! "POST".equals(req.getMethod())) {
750         res.setStatus(HttpServletResponse.SC_METHOD_NOT_ALLOWED);
751         res.setHeader("Allow", "POST");
752         return;
753      }
754      var cookieValue = readCookie(req);
755      JWT idTokenHint = null;
756      if (cookieValue != null) {
757         idTokenHint = idTokenHintFromSession(cookieValue);
758         sessionStore.invalidate(cookieValue);
759      }
760      noStore(res);
761      res.addHeader("Set-Cookie", buildSetCookie("", 0));
762
763      var endSession = metadata().endSessionEndpoint();
764      if (endSession != null) {
765         var logoutReq = new LogoutRequest(endSession, idTokenHint, postLogoutRedirectUri, null);
766         res.sendRedirect(logoutReq.toURI().toString());
767      } else {
768         res.sendRedirect(postLogoutRedirectUri != null ? postLogoutRedirectUri.toString() : postLoginRedirect);
769      }
770   }
771
772   /**
773    * Refreshes the current session's access token using the rotating-refresh-token grant.
774    *
775    * <p>
776    * Replaces the stored refresh token with the one the IdP returns; if the IdP rejects the refresh
777    * (e.g. a rotated token was reused / revoked), the session is invalidated.  Only applies to stores
778    * that retain tokens (server-side); {@link SignedCookieSessionStore} sessions carry no tokens and
779    * yield {@link Optional#empty()}.
780    *
781    * @param req The HTTP request.
782    * @param res The HTTP response (a refreshed session resets the cookie).
783    * @return The refreshed session, or {@link Optional#empty()} if there was nothing to refresh.
784    */
785   public Optional<OidcSession> refresh(HttpServletRequest req, HttpServletResponse res) {
786      reqnn("req", req);
787      reqnn("res", res);
788      var cookieValue = readCookie(req);
789      if (cookieValue == null)
790         return oe();
791      var existing = sessionStore.lookup(cookieValue);
792      if (existing.isEmpty())
793         return oe();
794      var tokenOpt = existing.get().token();
795      if (tokenOpt.isEmpty())
796         return oe();
797      var oldToken = tokenOpt.get();
798      var refreshTokenOpt = oldToken.refreshToken();
799      if (refreshTokenOpt.isEmpty())
800         return oe();
801
802      OAuthToken refreshed;
803      try {
804         var flowBuilder = OAuthRefreshTokenFlow.create()
805            .tokenEndpoint(metadata().tokenEndpoint())
806            .clientId(clientId)
807            .refreshToken(refreshTokenOpt.get());
808         if (clientSecretSupplier != null) // HTT: false branch (null secret = public client) reachable via refresh path only; no dedicated public-client refresh test
809            flowBuilder.clientSecretSupplier(clientSecretSupplier);
810         if (httpRequestConfigurator != null) // HTT: false branch (no configurator) unreachable in current refresh tests because the test RP always omits a configurator, so this block is never entered in tests
811            flowBuilder.httpRequestConfigurator(httpRequestConfigurator);
812         refreshed = flowBuilder.build().acquire();
813      } catch (OAuthFlowException e) {
814         // Rotating-refresh-token reuse / revocation -> invalidate the session (fail-closed).
815         sessionStore.invalidate(cookieValue);
816         res.addHeader("Set-Cookie", buildSetCookie("", 0));
817         return oe();
818      }
819
820      var old = existing.get();
821      var now = clock.instant();
822      var newSession = new OidcSession(
823         new State().getValue(),
824         old.subject(),
825         old.sid(),
826         old.principal(),
827         old.roles(),
828         o(refreshed),
829         old.createdAt(),
830         now.plus(sessionTtl));
831      sessionStore.invalidate(cookieValue);
832      var newCookie = sessionStore.createSessionCookieValue(newSession);
833      noStore(res);
834      res.addHeader("Set-Cookie", buildSetCookie(newCookie, sessionTtl.toSeconds()));
835      return o(newSession);
836   }
837
838   /**
839    * Processes an IdP-pushed OpenID Connect back-channel logout token, invalidating the matching
840    * server-side session(s).
841    *
842    * <p>
843    * The logout token is validated via Nimbus's {@link LogoutTokenValidator} (signature against the
844    * JWKS, {@code iss}, {@code aud}, the back-channel {@code events} claim, and the {@code sub} /
845    * {@code sid} presence rule).  Sessions are then revoked by {@code sid} (preferred, single-session)
846    * or {@code sub} (all of a subject's sessions).
847    *
848    * <p>
849    * Requires a {@link SessionStore#supportsServerSideRevocation() server-side-revocable} store
850    * &mdash; the default {@link SignedCookieSessionStore} cannot satisfy back-channel logout because a
851    * stateless cookie is not server-revocable.
852    *
853    * @param logoutToken The raw {@code logout_token} JWT pushed by the IdP.  Must not be <jk>null</jk>
854    *    or blank.
855    * @return The number of sessions invalidated.
856    * @throws AuthenticationException If the logout token fails validation.
857    * @throws IllegalStateException If the configured session store does not support server-side
858    *    revocation.
859    */
860   public int backChannelLogout(String logoutToken) throws AuthenticationException {
861      reqnb("logoutToken", logoutToken);
862      if (! sessionStore.supportsServerSideRevocation())
863         throw new IllegalStateException("Back-channel logout requires a server-side-revocable SessionStore (InMemorySessionStore or a distributed store); the configured store is stateless.");
864      JWT jwt;
865      try {
866         jwt = JWTParser.parse(logoutToken);
867      } catch (java.text.ParseException e) {
868         throw new AuthenticationException(e, "Logout token could not be parsed");
869      }
870      LogoutTokenClaimsSet claims;
871      try {
872         var verified = logoutTokenProcessor().process(jwt, null);
873         claims = new LogoutTokenClaimsSet(verified);
874      } catch (com.nimbusds.jose.proc.BadJOSEException | com.nimbusds.jose.JOSEException e) {
875         throw new AuthenticationException(e, "Logout token validation failed: %s", e.getMessage());
876      } catch (com.nimbusds.oauth2.sdk.ParseException e) {
877         throw new AuthenticationException(e, "Logout token claims could not be parsed");
878      }
879      var sid = claims.getSessionID();
880      if (sid != null)
881         return sessionStore.invalidateBySessionId(sid.getValue());
882      var sub = claims.getSubject();
883      if (sub != null) // HTT: false branch (sub==null with sid==null) rejected by LogoutTokenClaimsVerifier which requires at least one of sub or sid; defensive dead code
884         return sessionStore.invalidateBySubject(sub.getValue());
885      return 0;
886   }
887
888   /**
889    * Returns a request-time {@link AuthFilter} that resolves this RP's session cookie into a
890    * {@link ClaimsPrincipal}.
891    *
892    * @return A new {@link OidcSessionAuthFilter} bound to this RP's session store + cookie name.
893    */
894   public OidcSessionAuthFilter authFilter() {
895      return new OidcSessionAuthFilter(sessionStore, cookieName);
896   }
897
898   /**
899    * Returns the configured session store.
900    *
901    * @return The session store.
902    */
903   public SessionStore sessionStore() {
904      return sessionStore;
905   }
906
907   /**
908    * Returns the session cookie name.
909    *
910    * @return The cookie name.
911    */
912   public String cookieName() {
913      return cookieName;
914   }
915
916   //-----------------------------------------------------------------------------------------------------------------
917   // Internals
918   //-----------------------------------------------------------------------------------------------------------------
919
920   private OidcMetadata metadata() {
921      var m = metadataCache;
922      if (m != null)
923         return m;
924      synchronized (this) {
925         if (metadataCache != null) // HTT: DCL second-check; true branch requires concurrent initialization race
926            return metadataCache;
927         if (explicitMetadata != null) { // HTT: false branch = discovery path; all tests inject .metadata(...) directly so explicitMetadata is always non-null
928            metadataCache = validateEndpoints(explicitMetadata);
929            return metadataCache;
930         }
931         try {
932            var clientBuilder = OidcDiscoveryClient.create().issuer(issuer);
933            if (httpRequestConfigurator != null) // HTT: true branch requires discovery path (no explicit metadata) plus httpRequestConfigurator; all tests inject metadata directly
934               clientBuilder.httpRequestConfigurator(httpRequestConfigurator);
935            metadataCache = validateEndpoints(clientBuilder.build().discover());
936         } catch (IOException | OidcDiscoveryException e) {
937            throw isex(e, "OIDC discovery failed for issuer %s", issuer);
938         }
939         return metadataCache;
940      }
941   }
942
943   /**
944    * Requires the token-bearing endpoints resolved from metadata (issuer, token, JWKS, authorization, UserInfo, end-session) to use https or a
945    * loopback host, so key material and client credentials are never exchanged over plaintext to a remote host.
946    */
947   private static OidcMetadata validateEndpoints(OidcMetadata m) {
948      if (m.issuer() != null) // HTT: null issuer unreachable; OIDC metadata always carries an issuer
949         UriUtils.assertSecureOrLoopback(m.issuer());
950      if (m.tokenEndpoint() != null)
951         UriUtils.assertSecureOrLoopback(m.tokenEndpoint());
952      if (m.jwksUri() != null)
953         UriUtils.assertSecureOrLoopback(m.jwksUri());
954      if (m.authorizationEndpoint() != null)
955         UriUtils.assertSecureOrLoopback(m.authorizationEndpoint());
956      if (m.userinfoEndpoint() != null)
957         UriUtils.assertSecureOrLoopback(m.userinfoEndpoint());
958      if (m.endSessionEndpoint() != null)
959         UriUtils.assertSecureOrLoopback(m.endSessionEndpoint());
960      return m;
961   }
962
963   private OAuthAuthorizationCodeFlow codeFlow() {
964      var f = codeFlowCache;
965      if (f != null)
966         return f;
967      synchronized (this) {
968         if (codeFlowCache != null) // HTT: DCL second-check; true branch requires concurrent initialization race
969            return codeFlowCache;
970         var md = metadata();
971         var b = OAuthAuthorizationCodeFlow.create()
972            .authorizationEndpoint(md.authorizationEndpoint())
973            .tokenEndpoint(md.tokenEndpoint())
974            .clientId(clientId)
975            .redirectUri(redirectUri)
976            .scope(scopes.toArray(new String[0]));
977         if (clientSecretSupplier != null) // HTT: false branch (public client with no secret) not covered; all test RPs set a client secret
978            b.clientSecretSupplier(clientSecretSupplier);
979         if (httpRequestConfigurator != null) // HTT: false branch not hit in codeFlow init; test RPs don't set an httpRequestConfigurator
980            b.httpRequestConfigurator(httpRequestConfigurator);
981         codeFlowCache = b.build();
982         return codeFlowCache;
983      }
984   }
985
986   private IdTokenValidatorAdapter idTokenValidator() {
987      var v = idTokenValidatorCache;
988      if (v != null)
989         return v;
990      synchronized (this) {
991         if (idTokenValidatorCache != null) // HTT: DCL second-check; true branch requires concurrent initialization race
992            return idTokenValidatorCache;
993         var b = IdTokenValidatorAdapter.create()
994            .issuer(metadata().issuer().toString())
995            .clientId(clientId)
996            .jwkSource(jwkSource())
997            .maxClockSkewSeconds(clockSkewSeconds);
998         if (idTokenAlgorithms != null) // HTT: false branch (custom algorithm list) not covered; test RPs use default RS256/ES256
999            b.algorithms(idTokenAlgorithms);
1000         idTokenValidatorCache = b.build();
1001         return idTokenValidatorCache;
1002      }
1003   }
1004
1005   private JWKSource<SecurityContext> jwkSource() {
1006      var s = jwkSourceCache;
1007      if (s != null)
1008         return s;
1009      synchronized (this) {
1010         if (jwkSourceCache != null) // HTT: DCL second-check; true branch requires concurrent initialization race
1011            return jwkSourceCache;
1012         if (injectedJwkSource != null) { // HTT: true branch requires jwkSource(JWKSource) builder call, which no current test uses (tests inject jwkSet instead)
1013            jwkSourceCache = injectedJwkSource;
1014         } else if (jwkSet != null) { // HTT: false branch (no jwkSet → use JWKS URI from discovery) requires a live IdP and no injected jwkSet; all tests inject jwkSet
1015            jwkSourceCache = new ImmutableJWKSet<>(jwkSet);
1016         } else {
1017            try {
1018               jwkSourceCache = JWKSourceBuilder.create(metadata().jwksUri().toURL()).build();
1019            } catch (MalformedURLException e) {
1020               throw isex(e, "Invalid JWKS URI: %s", metadata().jwksUri());
1021            }
1022         }
1023         return jwkSourceCache;
1024      }
1025   }
1026
1027   /**
1028    * Builds (and caches) the JWT processor used to validate back-channel logout tokens.
1029    *
1030    * <p>
1031    * Nimbus's {@link LogoutTokenValidator} hardcodes a {@link LogoutTokenClaimsVerifier} internally and
1032    * exposes no clock hook, so we drive an equivalent {@link DefaultJWTProcessor} directly: the JWS type
1033    * verifier replicates {@code LogoutTokenValidator}'s default (accept untyped, {@code logout+jwt}, or
1034    * {@code JWT}), and the claims verifier is a {@link ClockAwareLogoutTokenClaimsVerifier} that sources
1035    * "now" from {@link #clock}.  With {@link Clock#systemUTC()} the behavior is identical to stock
1036    * {@code LogoutTokenValidator}.
1037    */
1038   private ConfigurableJWTProcessor<SecurityContext> logoutTokenProcessor() {
1039      var p = logoutTokenProcessorCache;
1040      if (p != null)
1041         return p;
1042      synchronized (this) {
1043         if (logoutTokenProcessorCache != null) // HTT: DCL second-check; true branch requires concurrent initialization race
1044            return logoutTokenProcessorCache;
1045         Set<JWSAlgorithm> algs = idTokenAlgorithms != null
1046            ? new LinkedHashSet<>(Arrays.asList(idTokenAlgorithms))
1047            : new LinkedHashSet<>(Arrays.asList(JWSAlgorithm.RS256, JWSAlgorithm.ES256));
1048         var keySelector = new JWSVerificationKeySelector<SecurityContext>(algs, jwkSource());
1049         var expectedIssuer = new Issuer(metadata().issuer().toString());
1050         var processor = new DefaultJWTProcessor<SecurityContext>();
1051         processor.setJWSTypeVerifier(new DefaultJOSEObjectTypeVerifier<>(LogoutTokenValidator.TYPE, JOSEObjectType.JWT, null));
1052         processor.setJWSKeySelector(keySelector);
1053         @SuppressWarnings({
1054            "unchecked" // ClockAwareLogoutTokenClaimsVerifier conforms to JWTClaimsSetVerifier<SecurityContext>; Nimbus's raw type forces an unchecked conversion here.
1055         })
1056         JWTClaimsSetVerifier<SecurityContext> claimsVerifier = new ClockAwareLogoutTokenClaimsVerifier(expectedIssuer, new ClientID(clientId), clock);
1057         processor.setJWTClaimsSetVerifier(claimsVerifier);
1058         logoutTokenProcessorCache = processor;
1059         return logoutTokenProcessorCache;
1060      }
1061   }
1062
1063   private ClaimsPrincipal maybeBackfillUserInfo(ClaimsPrincipal principal, OAuthToken token) {
1064      if (userInfoClaims.isEmpty())
1065         return principal;
1066      var endpoint = metadata().userinfoEndpoint();
1067      if (endpoint == null)
1068         return principal;
1069      var missing = userInfoClaims.stream().anyMatch(c -> ! principal.hasClaim(c));
1070      if (! missing)
1071         return principal;
1072      try {
1073         var http = new UserInfoRequest(endpoint, new BearerAccessToken(token.accessToken())).toHTTPRequest();
1074         http.setConnectTimeout(USERINFO_TIMEOUT_MS);
1075         http.setReadTimeout(USERINFO_TIMEOUT_MS);
1076         http.setFollowRedirects(false);
1077         if (httpRequestConfigurator != null)
1078            httpRequestConfigurator.accept(http);
1079         var resp = UserInfoResponse.parse(http.send());
1080         if (! resp.indicatesSuccess())
1081            return principal;
1082         var ui = resp.toSuccessResponse().getUserInfo().toJSONObject();
1083         if (! Objects.equals(principal.getName(), ui.get("sub")))
1084            return principal;  // The UserInfo subject must match the ID-token subject.
1085         var merged = new LinkedHashMap<String,Object>(principal.getClaims());
1086         for (var c : userInfoClaims)
1087            if (! merged.containsKey(c) && ui.containsKey(c))
1088               merged.put(c, ui.get(c));
1089         return new ClaimsPrincipal(principal.getName(), merged);
1090      } catch (IOException | com.nimbusds.oauth2.sdk.ParseException | RuntimeException e) {
1091         return principal;  // UserInfo backfill is best-effort; never fail the login on it.
1092      }
1093   }
1094
1095   private Set<String> extractRoles(ClaimsPrincipal principal) {
1096      var v = principal.getClaims().get(rolesClaim);
1097      if (v == null)
1098         return Collections.emptySet();
1099      var out = new LinkedHashSet<String>();
1100      if (v instanceof String v2) {
1101         for (var piece : v2.split("\\s+"))
1102            if (! piece.isBlank())
1103               out.add(piece);
1104      } else if (v instanceof Collection<?> v2) {
1105         for (var item : v2)
1106            if (item instanceof String item2)
1107               out.add(item2);
1108      }
1109      return out;
1110   }
1111
1112   private String buildSetCookie(String value, long maxAgeSeconds) {
1113      var sb = new StringBuilder();
1114      sb.append(cookieName).append('=').append(value);
1115      sb.append("; Path=/");
1116      sb.append("; Max-Age=").append(maxAgeSeconds);
1117      if (cookieHttpOnly)
1118         sb.append("; HttpOnly");
1119      if (cookieSecure)
1120         sb.append("; Secure");
1121      if (cookieSameSite != null) // HTT: false branch requires null cookieSameSite, which the builder's reqnb guard prevents
1122         sb.append("; SameSite=").append(cookieSameSite);
1123      return sb.toString();
1124   }
1125
1126   /**
1127    * Best-effort extraction of the {@code id_token_hint} for the RP-initiated logout request from the
1128    * session referenced by the given cookie value.  Returns <jk>null</jk> when the session, its token,
1129    * or its id_token is absent, or when the id_token cannot be parsed.
1130    */
1131   private JWT idTokenHintFromSession(String cookieValue) {
1132      var session = sessionStore.lookup(cookieValue);
1133      if (session.isEmpty())
1134         return null;
1135      var token = session.get().token();
1136      if (token.isEmpty())
1137         return null;
1138      var idt = token.get().idToken();
1139      if (idt.isEmpty()) // HTT: requires OAuthToken with no id_token; code-exchange always produces one when idToken is set on the stub, and the field is final
1140         return null;
1141      try {
1142         return JWTParser.parse(idt.get());
1143      } catch (java.text.ParseException e) {
1144         return null;  // HTT - best-effort hint only
1145      }
1146   }
1147
1148   private String readCookie(HttpServletRequest req) {
1149      return readCookie(req, cookieName);
1150   }
1151
1152   private String loginBindingCookieName() {
1153      return cookieName + "_LOGIN";
1154   }
1155
1156   private String buildLoginBindingCookie(String value, long maxAgeSeconds) {
1157      // SameSite=Lax regardless of the session-cookie setting: the IdP callback is a cross-site top-level navigation.
1158      var sb = new StringBuilder();
1159      sb.append(loginBindingCookieName()).append('=').append(value);
1160      sb.append("; Path=/; Max-Age=").append(maxAgeSeconds).append("; HttpOnly");
1161      if (cookieSecure)
1162         sb.append("; Secure");
1163      sb.append("; SameSite=Lax");
1164      return sb.toString();
1165   }
1166
1167   private static String hashBinding(String value) {
1168      try {
1169         return Base64.getUrlEncoder().withoutPadding().encodeToString(
1170            MessageDigest.getInstance("SHA-256").digest(value.getBytes(StandardCharsets.UTF_8)));
1171      } catch (NoSuchAlgorithmException e) {
1172         throw new IllegalStateException(e);  // HTT: SHA-256 is always available
1173      }
1174   }
1175
1176   private static boolean bindingMatches(String cookieValue, String expectedHash) {
1177      if (cookieValue == null || expectedHash == null)
1178         return false;
1179      return MessageDigest.isEqual(
1180         hashBinding(cookieValue).getBytes(StandardCharsets.UTF_8),
1181         expectedHash.getBytes(StandardCharsets.UTF_8));
1182   }
1183
1184   private static String readCookie(HttpServletRequest req, String name) {
1185      var cookies = req.getCookies();
1186      if (cookies == null)
1187         return null;
1188      for (var c : cookies)
1189         if (eq(name, c.getName()) && c.getValue() != null && ! c.getValue().isBlank())
1190            return c.getValue();
1191      return null;
1192   }
1193
1194   private static void noStore(HttpServletResponse res) {
1195      res.setHeader("Cache-Control", "no-store");
1196      res.setHeader("Pragma", "no-cache");
1197   }
1198
1199   private static URI fullRequestUri(HttpServletRequest req) {
1200      var url = new StringBuilder(req.getRequestURL());
1201      var qs = req.getQueryString();
1202      if (qs != null) // HTT: false branch (no QS) would cause Nimbus to fail to parse the callback; all test callbacks include query params
1203         url.append('?').append(qs);
1204      return URI.create(url.toString());
1205   }
1206
1207   /**
1208    * Returns the value only if it is a safe app-relative path (defeats open-redirect via the
1209    * {@code redirect} parameter).
1210    */
1211   private static String safeRelativePath(String value) {
1212      if (isBlank(value))
1213         return null;
1214      if (! value.startsWith("/"))
1215         return null;
1216      if (value.startsWith("//") || value.contains("\\") || value.contains("://"))
1217         return null;
1218      for (var i = 0; i < value.length(); i++) {
1219         var ch = value.charAt(i);
1220         if (ch <= 0x20 || ch == 0x7f)
1221            return null;
1222      }
1223      return value;
1224   }
1225
1226   /**
1227    * A {@link LogoutTokenClaimsVerifier} whose {@code exp} window is evaluated against an injected
1228    * {@link Clock} instead of {@code new Date()}.
1229    *
1230    * <p>
1231    * {@link LogoutTokenClaimsVerifier} extends Nimbus's {@link DefaultJWTClaimsVerifier}, which exposes
1232    * an overridable {@link DefaultJWTClaimsVerifier#currentTime() currentTime()} hook &mdash; so this is
1233    * a one-method override that injects the clock without cloning any Nimbus claim-checking logic.  With
1234    * {@link Clock#systemUTC()} the behavior is identical to stock Nimbus.
1235    */
1236   private static final class ClockAwareLogoutTokenClaimsVerifier extends LogoutTokenClaimsVerifier {
1237
1238      private final Clock clock;
1239
1240      ClockAwareLogoutTokenClaimsVerifier(Issuer issuer, ClientID clientId, Clock clock) {
1241         super(issuer, clientId);
1242         this.clock = clock;
1243      }
1244
1245      @Override /* DefaultJWTClaimsVerifier */
1246      protected Date currentTime() {
1247         return Date.from(clock.instant());
1248      }
1249   }
1250}