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.oauth;
018
019import static org.apache.juneau.commons.utils.Shorts.*;
020
021import java.io.*;
022import java.net.*;
023import java.nio.charset.*;
024import java.security.*;
025import java.time.*;
026import java.util.*;
027import java.util.function.*;
028import java.util.stream.*;
029
030import org.apache.juneau.commons.utils.*;
031import org.apache.juneau.rest.server.auth.*;
032
033import com.nimbusds.oauth2.sdk.*;
034import com.nimbusds.oauth2.sdk.auth.*;
035import com.nimbusds.oauth2.sdk.http.*;
036import com.nimbusds.oauth2.sdk.id.*;
037import com.nimbusds.oauth2.sdk.token.*;
038
039/**
040 * {@link TokenValidator} that validates opaque OAuth 2.0 access tokens via the
041 * <a class="doclink" href="https://datatracker.ietf.org/doc/html/rfc7662">RFC 7662</a> Token Introspection
042 * endpoint.
043 *
044 * <p>
045 * Wraps Nimbus's {@code TokenIntrospectionRequest} / {@code TokenIntrospectionResponse} for the HTTP
046 * round-trip and the JSON parsing.  A {@link TokenCache} (default: bounded LRU cache) short-circuits
047 * the round-trip on repeated lookups within the configured TTL window.
048 *
049 * <h2 class='topic'>Usage</h2>
050 *
051 * <p class='bjava'>
052 *    <jk>var</jk> validator = OAuthIntrospectionValidator.<jsm>create</jsm>()
053 *       .introspectionEndpoint(URI.<jsm>create</jsm>(<js>"https://idp.example.com/oauth2/introspect"</js>))
054 *       .clientId(<js>"api-server"</js>)
055 *       .clientSecret(<js>"..."</js>)
056 *       .audience(<js>"https://api.example.com"</js>)
057 *       .requiredScopes(<js>"read:orders"</js>)
058 *       .build();
059 * </p>
060 *
061 * <h2 class='topic'>Defaults</h2>
062 * <ul>
063 *    <li>Audience: required.  {@link Builder#build()} fails unless {@link Builder#audience(String...)} (or
064 *       {@link Builder#resource(String...)}) or an explicit {@link Builder#anyAudience()} is set.
065 *    <li>HTTP timeouts: 5 seconds connect and read.
066 *    <li>Cache TTL: 5 minutes, capped at 1 hour.
067 *    <li>Cache size: 1000 entries.
068 *    <li>Negative cache: inactive or rejected tokens are remembered for 30 seconds.
069 *    <li>Required scopes: none (scope enforcement lives on the validator, not the filter).
070 * </ul>
071 *
072 * <h2 class='section'>See Also:</h2>
073 * <ul>
074 *    <li class='jc'>{@link OAuthFilter}
075 *    <li class='jc'>{@link TokenValidator}
076 *    <li class='link'><a class="doclink" href="https://datatracker.ietf.org/doc/html/rfc7662">RFC 7662 &mdash; OAuth 2.0 Token Introspection</a>
077 * </ul>
078 *
079 * @since 10.0.0
080 */
081@SuppressWarnings({
082   "java:S1192" // Duplicate string literals are OAuth introspection response field names; intentional
083})
084public class OAuthIntrospectionValidator implements TokenValidator {
085
086   /** Default cache TTL. */
087   public static final Duration DEFAULT_CACHE_TTL = Duration.ofMinutes(5);
088
089   /** Maximum cache TTL. */
090   public static final Duration MAX_CACHE_TTL = Duration.ofHours(1);
091
092   /** Default connect/read timeout for the introspection call. */
093   public static final Duration DEFAULT_HTTP_TIMEOUT = Duration.ofSeconds(5);
094
095   /** Default time an inactive or rejected token is remembered. */
096   public static final Duration DEFAULT_NEGATIVE_CACHE_TTL = Duration.ofSeconds(30);
097
098   private static final int MAX_NEGATIVE_ENTRIES = 1000;
099
100   /**
101    * Static creator.
102    *
103    * @return A new builder.
104    */
105   public static Builder create() {
106      return new Builder();
107   }
108
109   /**
110    * Builder for {@link OAuthIntrospectionValidator}.
111    */
112   public static class Builder {
113      private URI introspectionEndpoint;
114      private String clientId;
115      private Supplier<String> clientSecretSupplier;
116      private TokenCache tokenCache;
117      private Duration cacheTtl = DEFAULT_CACHE_TTL;
118      private final Set<String> requiredScopes = st();
119      private final Set<String> expectedAudiences = st();
120      private Clock clock = Clock.systemUTC();
121      private Consumer<HTTPRequest> httpRequestConfigurator;
122      private String issuer;
123      private boolean anyAudience;
124      private Duration httpTimeout = DEFAULT_HTTP_TIMEOUT;
125      private Duration negativeCacheTtl = DEFAULT_NEGATIVE_CACHE_TTL;
126
127      /** Constructor. */
128      protected Builder() {}
129
130      /**
131       * Sets the introspection endpoint URL.  Required.
132       *
133       * <p>
134       * Each introspection call transmits the client secret (HTTP Basic) and the access token under
135       * validation to this endpoint, so the URL must use <js>"https"</js> or target a loopback host; a
136       * plaintext transport to a non-loopback host is rejected.
137       *
138       * @param value The endpoint URL.  Must not be <jk>null</jk> and must use HTTPS or target a loopback host.
139       * @return This object.
140       */
141      public Builder introspectionEndpoint(URI value) {
142         introspectionEndpoint = UriUtils.assertSecureOrLoopback(reqnn("value", value));
143         return this;
144      }
145
146      /**
147       * Sets the OAuth client ID used for HTTP Basic auth against the introspection endpoint.
148       *
149       * @param value The client ID.  Must not be <jk>null</jk> or blank.
150       * @return This object.
151       */
152      public Builder clientId(String value) {
153         clientId = reqnb("value", value);
154         return this;
155      }
156
157      /**
158       * Sets the OAuth client secret as a literal string.
159       *
160       * <p>
161       * Mutually exclusive with {@link #clientSecretSupplier(Supplier)}.
162       *
163       * @param value The client secret.  Must not be <jk>null</jk> or blank.
164       * @return This object.
165       */
166      public Builder clientSecret(String value) {
167         reqnb("value", value);
168         clientSecretSupplier = () -> value;
169         return this;
170      }
171
172      /**
173       * Sets the OAuth client secret via a supplier (useful for rotating secrets).
174       *
175       * @param value The supplier.  Must not be <jk>null</jk>.
176       * @return This object.
177       */
178      public Builder clientSecretSupplier(Supplier<String> value) {
179         clientSecretSupplier = reqnn("value", value);
180         return this;
181      }
182
183      /**
184       * Sets a custom token cache.  Defaults to a {@link BoundedLruTokenCache} with 1000 entries.
185       *
186       * @param value The cache.  Must not be <jk>null</jk>.
187       * @return This object.
188       */
189      public Builder tokenCache(TokenCache value) {
190         tokenCache = reqnn("value", value);
191         return this;
192      }
193
194      /**
195       * Sets the cache TTL.  Defaults to {@link #DEFAULT_CACHE_TTL 5 minutes}; capped at
196       * {@link #MAX_CACHE_TTL 1 hour}.  Capped by the token's own {@code exp} when shorter.
197       *
198       * @param value The TTL.  Must be positive and not exceed 1 hour.
199       * @return This object.
200       */
201      public Builder cacheTtl(Duration value) {
202         reqnn("value", value);
203         if (value.isZero() || value.isNegative())
204            throw iaex("cacheTtl must be positive");
205         if (value.compareTo(MAX_CACHE_TTL) > 0)
206            throw iaex("cacheTtl must not exceed 1 hour (was %s)", value);
207         cacheTtl = value;
208         return this;
209      }
210
211      /**
212       * Adds required scopes (scope enforcement lives on the validator, not the filter).
213       *
214       * <p>
215       * If any required scope is missing from the introspection response's {@code scope} claim, the
216       * validator throws {@link AuthenticationException} with
217       * {@code WWW-Authenticate: Bearer error="insufficient_scope"}.
218       *
219       * @param scopes The required scopes.  Must contain at least one non-blank entry.
220       * @return This object.
221       */
222      public Builder requiredScopes(String... scopes) {
223         reqnn("scopes", scopes);
224         for (var s : scopes) {
225            reqnb("scope", s);
226            requiredScopes.add(s);
227         }
228         return this;
229      }
230
231      /**
232       * Adds expected audience values (RFC 7662 {@code aud}) that a token must carry to be accepted.
233       *
234       * <p>
235       * When at least one value is configured here (via this method or {@link #resource(String...)}), the
236       * introspection response's {@code aud} claim must contain <b>at least one</b> matching value, or the
237       * token is rejected as {@code invalid_token} &mdash; even when {@code active=true} and required scopes
238       * match.  This binds the token to the resource server it was minted for, so a token issued for a
239       * different API cannot be replayed against this one.
240       *
241       * <p>
242       * An audience is required: {@link #build()} fails unless at least one value is configured here or
243       * {@link #anyAudience()} is called.
244       *
245       * @param values The expected audience values.  Must contain at least one non-blank entry.
246       * @return This object.
247       */
248      public Builder audience(String... values) {
249         reqnn("values", values);
250         for (var v : values) {
251            reqnb("audience", v);
252            expectedAudiences.add(v);
253         }
254         return this;
255      }
256
257      /**
258       * Explicitly disables the audience check.
259       *
260       * <p>
261       * Use only for authorization servers that cannot emit an {@code aud} claim.  Without this call (or an
262       * {@link #audience(String...)} value), {@link #build()} fails.
263       *
264       * @return This object.
265       */
266      public Builder anyAudience() {
267         anyAudience = true;
268         return this;
269      }
270
271      /**
272       * Sets the expected token issuer.
273       *
274       * <p>
275       * When set, the introspection response's {@code iss} claim must equal this value or the token is rejected.
276       *
277       * @param value The expected issuer.  Must not be <jk>null</jk> or blank.
278       * @return This object.
279       */
280      public Builder issuer(String value) {
281         issuer = reqnb("value", value);
282         return this;
283      }
284
285      /**
286       * Sets the connect/read timeout of the introspection call.  Defaults to {@link #DEFAULT_HTTP_TIMEOUT 5 seconds}.
287       *
288       * <p>
289       * Applied before {@link #httpRequestConfigurator(Consumer)} runs, so the configurator can override it.
290       *
291       * @param value The timeout.  Must be positive.
292       * @return This object.
293       */
294      public Builder httpTimeout(Duration value) {
295         reqnn("value", value);
296         if (value.isZero() || value.isNegative())
297            throw iaex("httpTimeout must be positive");
298         httpTimeout = value;
299         return this;
300      }
301
302      /**
303       * Sets how long an inactive or rejected token is remembered so repeated presentations do not each trigger
304       * an introspection call.  Defaults to {@link #DEFAULT_NEGATIVE_CACHE_TTL 30 seconds}; {@link Duration#ZERO} disables it.
305       *
306       * @param value The TTL.  Must not be negative.
307       * @return This object.
308       */
309      public Builder negativeCacheTtl(Duration value) {
310         reqnn("value", value);
311         if (value.isNegative())
312            throw iaex("negativeCacheTtl must not be negative");
313         negativeCacheTtl = value;
314         return this;
315      }
316
317      /**
318       * Adds expected resource-indicator values (RFC 8707).
319       *
320       * <p>
321       * Alias for {@link #audience(String...)}: RFC 8707 resource indicators are echoed back by
322       * conformant authorization servers in the same introspection {@code aud} claim as RFC 7662
323       * audiences, so both methods add to the same expected-value set.
324       *
325       * @param values The expected resource values.  Must contain at least one non-blank entry.
326       * @return This object.
327       */
328      public Builder resource(String... values) {
329         return audience(values);
330      }
331
332      /**
333       * Overrides the {@link Clock} used for cache expiry.  Useful in tests.
334       *
335       * @param value The clock.  Must not be <jk>null</jk>.
336       * @return This object.
337       */
338      public Builder clock(Clock value) {
339         clock = reqnn("value", value);
340         return this;
341      }
342
343      /**
344       * Sets a callback that customizes the Nimbus {@link HTTPRequest} before it is sent.
345       *
346       * <p>
347       * This is the escape hatch for custom HTTP behavior (proxies, TLS overrides,
348       * timeout overrides).  The callback is invoked on every introspection call.
349       *
350       * @param value The configurator callback.  Must not be <jk>null</jk>.
351       * @return This object.
352       */
353      public Builder httpRequestConfigurator(Consumer<HTTPRequest> value) {
354         httpRequestConfigurator = reqnn("value", value);
355         return this;
356      }
357
358      /**
359       * Builds the validator.
360       *
361       * @return A new {@link OAuthIntrospectionValidator}.
362       */
363      public OAuthIntrospectionValidator build() {
364         if (introspectionEndpoint == null)
365            throw new IllegalStateException("OAuthIntrospectionValidator requires introspectionEndpoint(...)");
366         if (clientId == null)
367            throw new IllegalStateException("OAuthIntrospectionValidator requires clientId(...)");
368         if (clientSecretSupplier == null)
369            throw new IllegalStateException("OAuthIntrospectionValidator requires clientSecret(...) or clientSecretSupplier(...)");
370         if (expectedAudiences.isEmpty() && ! anyAudience)
371            throw new IllegalStateException("OAuthIntrospectionValidator requires audience(...) or an explicit anyAudience()");
372         if (tokenCache == null)
373            tokenCache = BoundedLruTokenCache.create();
374         return new OAuthIntrospectionValidator(this);
375      }
376   }
377
378   private final URI introspectionEndpoint;
379   private final String clientId;
380   private final Supplier<String> clientSecretSupplier;
381   private final TokenCache tokenCache;
382   private final Duration cacheTtl;
383   private final Set<String> requiredScopes;
384   private final Set<String> expectedAudiences;
385   private final Clock clock;
386   private final Consumer<HTTPRequest> httpRequestConfigurator;
387   private final String issuer;
388   private final Duration httpTimeout;
389   private final Duration negativeCacheTtl;
390   private final Map<String,NegativeEntry> negativeCache = new LinkedHashMap<>(16, 0.75f, true) {
391      private static final long serialVersionUID = 1L;
392      @Override
393      protected boolean removeEldestEntry(Map.Entry<String,NegativeEntry> eldest) {
394         return size() > MAX_NEGATIVE_ENTRIES;
395      }
396   };
397
398   /** Raw introspection result as stored in the token cache; carries no per-validator decisions. */
399   private record RawIntrospection(TokenIntrospectionSuccessResponse response) implements Principal {
400      @Override /* Overridden from Principal */
401      public String getName() {
402         return response.getSubject() == null ? "" : response.getSubject().getValue();
403      }
404   }
405
406   private record NegativeEntry(String message, String wwwAuthenticate, Instant expires) {}
407
408   private static final class Rejection extends Exception {
409      private static final long serialVersionUID = 1L;
410      private final String challenge;
411      Rejection(String message, String challenge) {
412         super(message);
413         this.challenge = challenge;
414      }
415      AuthenticationException toException() {
416         return new AuthenticationException(getMessage()).wwwAuthenticate(challenge);
417      }
418   }
419
420   /**
421    * Constructor.
422    *
423    * @param b The builder.
424    */
425   protected OAuthIntrospectionValidator(Builder b) {
426      this.introspectionEndpoint = b.introspectionEndpoint;
427      this.clientId = b.clientId;
428      this.clientSecretSupplier = b.clientSecretSupplier;
429      this.tokenCache = b.tokenCache;
430      this.cacheTtl = b.cacheTtl;
431      this.requiredScopes = u(cp(b.requiredScopes));
432      this.expectedAudiences = u(cp(b.expectedAudiences));
433      this.clock = b.clock;
434      this.httpRequestConfigurator = b.httpRequestConfigurator;
435      this.issuer = b.issuer;
436      this.httpTimeout = b.httpTimeout;
437      this.negativeCacheTtl = b.negativeCacheTtl;
438   }
439
440   /**
441    * Returns the configured introspection endpoint URL.
442    *
443    * @return The endpoint.
444    */
445   public URI getIntrospectionEndpoint() {
446      return introspectionEndpoint;
447   }
448
449   /**
450    * Returns the configured OAuth client ID.
451    *
452    * @return The client ID.
453    */
454   public String getClientId() {
455      return clientId;
456   }
457
458   /**
459    * Returns the cache TTL.
460    *
461    * @return The TTL.
462    */
463   public Duration getCacheTtl() {
464      return cacheTtl;
465   }
466
467   /**
468    * Returns the required-scope set.
469    *
470    * @return An unmodifiable view.
471    */
472   public Set<String> getRequiredScopes() {
473      return requiredScopes;
474   }
475
476   /**
477    * Returns the configured expected audience / resource-indicator set.
478    *
479    * @return An unmodifiable view.  Empty only when {@link Builder#anyAudience()} was used.
480    */
481   public Set<String> getExpectedAudiences() {
482      return expectedAudiences;
483   }
484
485   /**
486    * Returns the underlying token cache.
487    *
488    * @return The token cache.
489    */
490   public TokenCache getTokenCache() {
491      return tokenCache;
492   }
493
494   @Override /* Overridden from TokenValidator */
495   public Principal validate(String token) throws AuthenticationException {
496      reqnb("token", token);
497      var cached = tokenCache.getPrincipal(token);
498      if (cached.isPresent() && cached.get() instanceof RawIntrospection raw) {
499         // The cache holds only the raw introspection result, so a cache shared with a differently
500         // configured validator can never skip this validator's own checks.
501         try {
502            enforceNotExpired(raw.response());
503            return toPrincipal(raw.response());
504         } catch (Rejection e) {
505            throw e.toException();
506         }
507      }
508      checkNegativeCache(token);
509      return introspect(token);
510   }
511
512   private static String negativeKey(String token) {
513      try {
514         return HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(token.getBytes(StandardCharsets.UTF_8)));
515      } catch (NoSuchAlgorithmException e) {
516         throw new IllegalStateException(e);
517      }
518   }
519
520   private void checkNegativeCache(String token) throws AuthenticationException {
521      if (negativeCacheTtl.isZero())
522         return;
523      NegativeEntry e;
524      synchronized (negativeCache) {
525         var key = negativeKey(token);
526         e = negativeCache.get(key);
527         if (e != null && ! e.expires().isAfter(clock.instant())) {
528            negativeCache.remove(key);
529            e = null;
530         }
531      }
532      if (e != null)
533         throw new AuthenticationException(e.message()).wwwAuthenticate(e.wwwAuthenticate());
534   }
535
536   private AuthenticationException remember(String token, Rejection r) {
537      if (! negativeCacheTtl.isZero()) {
538         synchronized (negativeCache) {
539            negativeCache.put(negativeKey(token), new NegativeEntry(r.getMessage(), r.challenge, clock.instant().plus(negativeCacheTtl)));
540         }
541      }
542      return r.toException();
543   }
544
545   private Principal introspect(String token) throws AuthenticationException {
546      var clientAuth = new ClientSecretBasic(new ClientID(clientId),
547         new com.nimbusds.oauth2.sdk.auth.Secret(clientSecretSupplier.get()));
548      AccessToken accessToken = new BearerAccessToken(token);
549      var req = new TokenIntrospectionRequest(introspectionEndpoint, clientAuth, accessToken);
550      var http = req.toHTTPRequest();
551      var timeoutMs = (int)Math.min(httpTimeout.toMillis(), Integer.MAX_VALUE);
552      http.setConnectTimeout(timeoutMs);
553      http.setReadTimeout(timeoutMs);
554      http.setFollowRedirects(false);
555      if (httpRequestConfigurator != null)
556         httpRequestConfigurator.accept(http);
557
558      com.nimbusds.oauth2.sdk.http.HTTPResponse httpResp;
559      try {
560         httpResp = http.send();
561      } catch (IOException e) {
562         throw new AuthenticationException(e, "OAuth introspection HTTP call failed")
563            .wwwAuthenticate(bearerError("invalid_token", "introspection unreachable"));
564      }
565      TokenIntrospectionResponse resp;
566      try {
567         resp = TokenIntrospectionResponse.parse(httpResp);
568      } catch (ParseException e) {
569         throw new AuthenticationException(e, "OAuth introspection response could not be parsed")
570            .wwwAuthenticate(bearerError("invalid_token", "introspection parse failed"));
571      }
572      if (!resp.indicatesSuccess())
573         throw remember(token, new Rejection("OAuth introspection error: " + safeErrorCode(resp.toErrorResponse().getErrorObject().getCode()),
574            bearerError("invalid_token", safeErrorCode(resp.toErrorResponse().getErrorObject().getCode()))));
575      var success = resp.toSuccessResponse();
576      if (!success.isActive())
577         throw remember(token, new Rejection("OAuth token inactive", bearerError("invalid_token", "token inactive")));
578      Principal principal;
579      try {
580         principal = toPrincipal(success);
581      } catch (Rejection e) {
582         throw remember(token, e);
583      }
584      tokenCache.putPrincipal(token, new RawIntrospection(success), resolveTtl(success));
585      return principal;
586   }
587
588   private Principal toPrincipal(TokenIntrospectionSuccessResponse success) throws Rejection {
589      enforceIssuer(success);
590      enforceAudience(success);
591      var scopes = extractScopes(success);
592      enforceRequiredScopes(scopes);
593      var claims = buildClaims(success, scopes);
594      if (success.getSubject() == null || success.getSubject().getValue().isBlank())
595         throw new Rejection("OAuth token has no subject", bearerError("invalid_token", "subject missing"));
596      var subject = success.getSubject().getValue();
597      return new ClaimsPrincipal(subject, claims);
598   }
599
600   private void enforceNotExpired(TokenIntrospectionSuccessResponse success) throws Rejection {
601      var exp = success.getExpirationTime();
602      if (exp != null && ! exp.toInstant().isAfter(clock.instant()))
603         throw new Rejection("OAuth token expired", bearerError("invalid_token", "token expired"));
604   }
605
606   private void enforceIssuer(TokenIntrospectionSuccessResponse success) throws Rejection {
607      if (issuer == null)
608         return;
609      var iss = success.getIssuer();
610      if (iss == null || ! issuer.equals(iss.getValue()))
611         throw new Rejection("OAuth token issuer mismatch", bearerError("invalid_token", "issuer mismatch"));
612   }
613
614   private Set<String> extractScopes(TokenIntrospectionSuccessResponse success) {
615      var s = success.getScope();
616      if (s == null)
617         return Collections.emptySet();
618      return s.toStringList().stream()
619         .filter(v -> v != null && !v.isBlank()) // HTT: v==null branch unreachable; Nimbus Scope.toStringList() never returns null entries
620         .collect(Collectors.toCollection(LinkedHashSet::new));
621   }
622
623   /**
624    * Rejects the token when an expected audience/resource set is configured and the introspection
625    * response's {@code aud} claim contains none of the expected values.  No-op when
626    * {@link #expectedAudiences} is empty (explicit {@code anyAudience()}).
627    */
628   private void enforceAudience(TokenIntrospectionSuccessResponse success) throws Rejection {
629      if (expectedAudiences.isEmpty())
630         return;
631      var tokenAudiences = success.getAudience();
632      var matched = tokenAudiences != null && tokenAudiences.stream()
633         .map(Audience::getValue)
634         .anyMatch(expectedAudiences::contains);
635      if (!matched)
636         throw new Rejection("OAuth token audience/resource mismatch", bearerError("invalid_token", "audience mismatch"));
637   }
638
639   private void enforceRequiredScopes(Set<String> tokenScopes) throws Rejection {
640      for (var req : requiredScopes) {
641         if (!tokenScopes.contains(req))
642            throw new Rejection("Required scope missing: " + req, bearerError("insufficient_scope", "scope " + req + " missing"));
643      }
644   }
645
646   private Map<String,Object> buildClaims(TokenIntrospectionSuccessResponse success, Set<String> scopes) {
647      var claims = new LinkedHashMap<String,Object>(success.toJSONObject());
648      if (!scopes.isEmpty())
649         claims.put("scope", new ArrayList<>(scopes));
650      return claims;
651   }
652
653   private Duration resolveTtl(TokenIntrospectionSuccessResponse success) {
654      var ttl = cacheTtl;
655      var exp = success.getExpirationTime();
656      if (exp != null) {
657         var until = Duration.between(clock.instant(), exp.toInstant());
658         if (until.isNegative() || until.isZero())
659            until = Duration.ofSeconds(1);
660         if (until.compareTo(ttl) < 0)
661            ttl = until;
662      }
663      return ttl;
664   }
665
666   private static String bearerError(String code, String description) {
667      return "Bearer error=\"" + code + "\", error_description=\"" + description.replace('"', ' ') + "\"";
668   }
669
670   private static String safeErrorCode(String code) {
671      if (code == null || code.isEmpty() || ! code.matches("[\\x20\\x21\\x23-\\x5B\\x5D-\\x7E]+"))
672         return "invalid_token";
673      return code;
674   }
675}