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 */ 016package com.revetsec.oauth; 017 018import static java.util.Objects.requireNonNull; 019import com.google.errorprone.annotations.CheckReturnValue; 020import com.revetsec.internal.Limits; 021import com.revetsec.internal.ObserverDispatch; 022import com.revetsec.internal.http.*; 023import com.revetsec.internal.jose.*; 024import com.revetsec.jose.*; 025import com.revetsec.json.*; 026import java.net.URI; 027import java.time.*; 028import java.util.*; 029import javax.annotation.concurrent.NotThreadSafe; 030import javax.annotation.concurrent.ThreadSafe; 031import org.jspecify.annotations.NonNull; 032import org.jspecify.annotations.Nullable; 033 034/** 035 * Audience-checked RFC7662 JSON introspection using the supplied OAuth client settings. 036 * No credential result is cached; an admitted validation performs its own single authenticated POST. 037 * Endpoint health backoff can prevent that POST: 401/429 opens it immediately. Transport failures and 038 * 5xx responses count together; three within one cooldown window, measured from the first and with no 039 * valid response in between, open it. Other client errors remain local to their request. Blocked callers receive fresh infrastructure exceptions, never 040 * another request's endpoint rejection. A valid parsed response, including inactive, restores health. 041 * @author <a href="https://www.revetkn.com">Mark Allen</a> 042 * @since 1.0.0 043 */ 044@ThreadSafe 045public final class TokenIntrospectionClient implements AccessTokenValidator { 046 047 private final OAuthClient client; 048 049 private final OAuthClient.ResourceSettings settings; 050 051 private final Set<String> audiences; 052 053 private final Set<String> required; 054 055 private final int maximumTokenLength; 056 057 private final Duration skew; 058 059 private final AccessTokenObserver observer; 060 061 @Nullable 062 private final ResourceServerMetadata target; 063 064 @Nullable 065 private final ResourceServerMetadataCache<ResourceServerMetadata> cache; 066 067 private final IntrospectionFailureGuard guard; 068 069 private TokenIntrospectionClient(@NonNull Builder builder) { 070 this.client = builder.client; 071 this.settings = this.client.resourceSettings(); 072 this.audiences = requireNonNull(builder.expectedAudiences); 073 this.required = builder.requiredClaims; 074 this.maximumTokenLength = builder.maximumTokenLength; 075 this.skew = builder.clockSkew; 076 this.observer = builder.observer; 077 this.guard = new IntrospectionFailureGuard(this.settings.cooldown(), System::nanoTime); 078 AuthorizationServerMetadata configured = this.settings.metadata(); 079 URI endpoint = builder.introspectionEndpoint != null ? builder.introspectionEndpoint : configured == null ? null : configured.getIntrospectionEndpoint().orElse(null); 080 if (endpoint != null) { 081 UriChecks.requirePermitted(endpoint, this.settings.policy(), this.settings.allowLoopback()); 082 // Only metadata for the same endpoint governs an explicit override's role policy. 083 boolean applicable = configured != null && configured.getIntrospectionEndpoint().map(uri -> ClientAssertionPreparation.sameEndpoint(uri, endpoint)).orElse(false); 084 Set<String> methods = applicable ? requireNonNull(configured).getIntrospectionEndpointAuthMethodsSupported().orElse(null) : null; 085 Set<String> algorithms = applicable ? requireNonNull(configured).getIntrospectionEndpointAuthSigningAlgValuesSupported().orElse(null) : null; 086 this.client.requireIntrospectionAuthentication(methods); 087 this.target = new ResourceServerMetadata(this.settings.issuer(), endpoint, methods, algorithms, 088 configured == null ? null : configured.getTokenEndpoint()); 089 this.cache = null; 090 } else { 091 this.target = null; 092 this.cache = new ResourceServerMetadataCache<>(URI.create(this.settings.issuer()), ResourceServerMetadata.Role.INTROSPECTION, this.settings.exchange(), this.settings.policy(), this.settings.allowLoopback(), this.settings.requestTimeout(), this.settings.clock(), this.client.resourceObserver(this.observer), this.settings.minimumTtl(), this.settings.defaultTtl(), this.settings.maximumTtl(), this.settings.cooldown(), metadata -> { 093 if (!UriChecks.isPermitted(metadata.endpoint(), this.settings.policy(), this.settings.allowLoopback())) 094 throw OAuthValidationException.fromReason(OAuthException.Reason.METADATA_INVALID); 095 this.client.requireIntrospectionAuthentication(metadata.authenticationMethods()); 096 return metadata; 097 }, System::nanoTime); 098 } 099 } 100 101 private @NonNull ResourceServerMetadata endpoint(@NonNull Deadline deadline) { 102 return this.target != null ? this.target : requireNonNull(this.cache).get(deadline); 103 } 104 private @NonNull ResourceServerMetadata assertionTarget(@NonNull Deadline deadline) { 105 try { return endpoint(deadline); } 106 catch (OAuthException failure) { 107 this.client.assertionMetadataFailure(OAuthEndpoint.INTROSPECTION, failure, this.client.resourceObserver(this.observer)); 108 throw failure; 109 } 110 } 111 112 /** 113 * Starts introspection with one configured confidential authentication strategy. 114 * @param client OAuth client supplying issuer, credentials, transport, clock and deadlines 115 * @return builder 116 * @since 1.0.0 117 */ 118 @NonNull 119 public static Builder withOAuthClient(@NonNull OAuthClient client) { 120 return new Builder(client); 121 } 122 123 /** 124 * Warms role-specific discovery without sending a credential. 125 * @since 1.0.0 126 */ 127 public void warmUp() { 128 endpoint(Deadline.fromNow(this.settings.totalDeadline())); 129 } 130 131 /** 132 * Performs one uncached authenticated introspection and all audience/profile checks. 133 * @param token unverified bearer credential 134 * @return fully checked proof with no received credential 135 * @since 1.0.0 136 */ 137 @NonNull 138 private VerifiedAccessToken validateCredential(@NonNull BearerToken token) { 139 requireNonNull(token); 140 Deadline deadline = Deadline.fromNow(this.settings.totalDeadline()); 141 try { 142 if (token.value().length() > this.maximumTokenLength) 143 throw AccessTokenValidationException.fromReason(AccessTokenValidationException.Reason.MALFORMED_REQUEST); 144 ResourceServerMetadata target = assertionTarget(deadline); 145 IntrospectionFailureGuard.Attempt attempt = this.guard.acquire(deadline, this.settings.requestTimeout()); 146 IntrospectionResponse parsed; 147 long started = System.nanoTime(); 148 Instant requestStart = this.settings.clock().instant(); 149 boolean receivedResponse = false; 150 try { 151 RawResponse response = this.client.introspectionRequest(token, target, deadline, this.observer); 152 receivedResponse = true; 153 parsed = IntrospectionResponse.parse(response, requestStart); 154 this.guard.healthy(attempt); 155 } catch (OAuthException failure) { 156 if (failure.getReason() == OAuthException.Reason.INTERRUPTED || deadline.isExpired()) this.guard.abandon(attempt); 157 else this.guard.failed(attempt, failure); 158 if (receivedResponse) 159 this.client.introspectionResponseFailure(target.endpoint(), failure, Duration.ofNanos(System.nanoTime() - started), this.observer); 160 throw failure; 161 } catch (RuntimeException misuse) { 162 this.guard.abandon(attempt); 163 throw misuse; 164 } 165 VerifiedAccessToken result = parsed.validate(this.settings.issuer(), this.audiences, this.required, this.settings.clock().instant(), this.skew); 166 ObserverDispatch.dispatch(this.observer, AccessTokenObserver::didValidateAccessToken); 167 return result; 168 } catch (AccessTokenValidationException rejection) { 169 ObserverDispatch.dispatch(this.observer, o -> o.didRejectAccessToken(rejection)); 170 throw rejection; 171 } 172 } 173 174 /** 175 * Returns a credential verdict or a distinct checked endpoint rejection. Transient provider failures, 176 * malformed responses, metadata failures and transport failures remain exceptions. 177 * @param token unverified bearer credential 178 * @return outcome 179 * @since 1.0.0 180 */ 181 @Override 182 @CheckReturnValue 183 @NonNull 184 public AccessTokenValidationResult validateResult(@NonNull BearerToken token) { 185 try { 186 return AccessTokenValidationResult.fromToken(validateCredential(token)); 187 } catch (AccessTokenValidationException rejection) { 188 return AccessTokenValidationResult.fromRejection(rejection); 189 } catch (OAuthErrorResponseException failure) { 190 if (!failure.isEndpointRejection()) throw failure; 191 return AccessTokenValidationResult.fromEndpoint(failure); 192 } 193 } 194 195 /** 196 * Returns a redacted description. 197 * @return description 198 * @since 1.0.0 199 */ 200 @Override 201 @NonNull 202 public String toString() { 203 return "TokenIntrospectionClient{data=<redacted>}"; 204 } 205 206 /** 207 * Configures required audiences and optional introspection policy; OAuth settings are inherited. 208 * @author <a href="https://www.revetkn.com">Mark Allen</a> 209 * @since 1.0.0 210 */ 211 @NotThreadSafe 212 @CheckReturnValue 213 public static final class Builder { 214 215 private final OAuthClient client; 216 217 @Nullable 218 private Set<@NonNull String> expectedAudiences; 219 220 private Set<@NonNull String> requiredClaims = Set.of(); 221 222 private int maximumTokenLength = Limits.BEARER_CREDENTIAL_SIZE.getDefaultIntValue(); 223 224 @Nullable 225 private URI introspectionEndpoint; 226 227 private Duration clockSkew = Limits.JOSE_CLOCK_SKEW.getDefaultDuration(); 228 229 private AccessTokenObserver observer = AccessTokenObserver.disabledInstance(); 230 231 private Builder(@NonNull OAuthClient client) { 232 this.client = requireNonNull(client); 233 } 234 235 /** 236 * Sets required exact audiences. 237 * @param value setting, or null to restore its default or absence 238 * @return this builder 239 * @since 1.0.0 240 */ 241 @NonNull 242 public Builder expectedAudiences(@Nullable Set<@NonNull String> value) { 243 this.expectedAudiences = value == null ? null : AccessTokenClaims.names(value, true); 244 return this; 245 } 246 247 /** 248 * Sets required claims. 249 * @param value setting, or null to restore its default or absence 250 * @return this builder 251 * @since 1.0.0 252 */ 253 @NonNull 254 public Builder requiredClaims(@Nullable Set<@NonNull String> value) { 255 this.requiredClaims = value == null ? Set.of() : AccessTokenClaims.names(value, false); 256 return this; 257 } 258 259 /** 260 * Sets credential bound. 261 * @param value setting, or null to restore its default or absence 262 * @return this builder 263 * @since 1.0.0 264 */ 265 @NonNull 266 public Builder maximumTokenLength(@Nullable Integer value) { 267 this.maximumTokenLength = value == null ? Limits.BEARER_CREDENTIAL_SIZE.getDefaultIntValue() : Limits.BEARER_CREDENTIAL_SIZE.require(value); 268 return this; 269 } 270 271 /** 272 * Sets manual introspection endpoint. 273 * @param value setting, or null to restore its default or absence 274 * @return this builder 275 * @since 1.0.0 276 */ 277 @NonNull 278 public Builder introspectionEndpoint(@Nullable URI value) { 279 this.introspectionEndpoint = value; 280 return this; 281 } 282 283 /** 284 * Sets clock skew. 285 * @param value setting, or null to restore its default or absence 286 * @return this builder 287 * @since 1.0.0 288 */ 289 @NonNull 290 public Builder clockSkew(@Nullable Duration value) { 291 this.clockSkew = value == null ? Limits.JOSE_CLOCK_SKEW.getDefaultDuration() : Limits.JOSE_CLOCK_SKEW.require(value); 292 return this; 293 } 294 295 /** 296 * Sets resource observer. 297 * @param value setting, or null to restore its default or absence 298 * @return this builder 299 * @since 1.0.0 300 */ 301 @NonNull 302 public Builder observer(@Nullable AccessTokenObserver value) { 303 this.observer = value == null ? AccessTokenObserver.disabledInstance() : value; 304 return this; 305 } 306 307 /** 308 * Builds without I/O or new threads. 309 * @return introspection client 310 * @since 1.0.0 311 */ 312 @NonNull 313 public TokenIntrospectionClient build() { 314 if (this.expectedAudiences == null) 315 throw new IllegalStateException("Expected audiences are required."); 316 this.client.requireIntrospectionAuthentication(null); 317 return new TokenIntrospectionClient(this); 318 } 319 } 320}