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.client.mcp.auth; 018 019import static org.apache.juneau.commons.utils.Shorts.*; 020import static org.apache.juneau.commons.utils.UriUtils.*; 021 022import java.net.*; 023import java.time.*; 024import java.util.*; 025import java.util.function.*; 026 027import org.apache.juneau.rest.client.mcp.*; 028import org.apache.juneau.rest.auth.oauth.flow.*; 029 030import com.nimbusds.oauth2.sdk.http.*; 031 032/** 033 * A headless bearer-token provider that feeds the {@link McpAuthInterceptor} token seam ({@code Supplier<String>}). 034 * 035 * <p> 036 * This is the client-side token-manager: it acquires, caches, and refreshes an access token and returns the current 037 * valid bearer credential from {@link #get()}. Three modes are supported: 038 * <ul> 039 * <li><b>Pre-provisioned / static</b> ({@link #ofStaticToken(String)}) — always returns a fixed token. 040 * <li><b>Client-credentials</b> ({@link Builder#clientCredentials()}) — RFC 6749 §4.4 grant, re-acquired 041 * on expiry. 042 * <li><b>Refresh-token</b> ({@link Builder#refreshToken(String)}, SEP-2207) — RFC 6749 §6 grant; rotated 043 * refresh tokens returned by the IdP are captured and used for the next refresh without re-consent, and the 044 * refreshed access token is fed back to the supplier. 045 * </ul> 046 * 047 * <p> 048 * The dynamic modes (client-credentials, refresh-token) require {@link Builder#resource(URI)} and carry that RFC 8707 049 * {@code resource} indicator on every token request, binding the token's audience to the target MCP server. The static 050 * mode issues no token request, so it takes no resource indicator. 051 * 052 * <p> 053 * {@link #get()} never returns a blank token: dynamic modes return the IdP-issued (non-blank) access token or throw 054 * {@link McpAuthException}/{@link OAuthFlowException} on failure (which aborts the intercepted request), and the static 055 * mode rejects a blank token at construction. This satisfies the {@code McpAuthInterceptor} "supply a non-blank token 056 * or suppress the header" contract. 057 * 058 * <p> 059 * Thread-safe. <b>Never logged:</b> {@link #toString()} discloses only non-secret configuration. 060 * 061 * @since 10.0.0 062 */ 063@SuppressWarnings({ 064 "java:S1192" // Duplicated literals (argument/property names) read more clearly inline than as constants 065}) 066public class McpTokenProvider implements Supplier<String> { 067 068 private enum Mode { STATIC, CLIENT_CREDENTIALS, REFRESH } 069 070 /** 071 * Creates a provider that always returns the supplied pre-provisioned bearer token. 072 * 073 * @param token The static bearer token. Must not be <jk>null</jk> or blank. 074 * @return A new provider. 075 */ 076 public static McpTokenProvider ofStaticToken(String token) { 077 reqnb("token", token); 078 return new Builder(Mode.STATIC).staticToken(token).build(); 079 } 080 081 /** 082 * Creates a builder for the client-credentials grant. 083 * 084 * @return A new builder. 085 */ 086 public static Builder clientCredentials() { 087 return new Builder(Mode.CLIENT_CREDENTIALS); 088 } 089 090 /** 091 * Creates a builder for the refresh-token grant, seeded with the initial refresh token. 092 * 093 * @param initialRefreshToken The initial refresh token. Must not be <jk>null</jk> or blank. 094 * @return A new builder. 095 */ 096 public static Builder refreshToken(String initialRefreshToken) { 097 reqnb("initialRefreshToken", initialRefreshToken); 098 return new Builder(Mode.REFRESH).initialRefreshToken(initialRefreshToken); 099 } 100 101 /** 102 * Builder. 103 */ 104 public static class Builder { 105 private final Mode mode; 106 private String staticToken; 107 private URI tokenEndpoint; 108 private String clientId; 109 private Supplier<String> clientSecretSupplier; 110 private String initialRefreshToken; 111 private final Set<String> scopes = st(); 112 private URI resource; 113 private Duration expirySkew = Duration.ofSeconds(30); 114 private Clock clock = Clock.systemUTC(); 115 private Duration httpTimeout = Duration.ofSeconds(10); 116 private Consumer<HTTPRequest> httpRequestConfigurator; 117 118 /** 119 * Constructor. 120 * 121 * @param mode The grant mode. 122 */ 123 protected Builder(Mode mode) { 124 this.mode = mode; 125 } 126 127 Builder staticToken(String value) { 128 staticToken = value; 129 return this; 130 } 131 132 Builder initialRefreshToken(String value) { 133 initialRefreshToken = value; 134 return this; 135 } 136 137 /** 138 * Sets the token endpoint URL. Required for the client-credentials and refresh-token modes. 139 * 140 * @param value The endpoint URL. Must not be <jk>null</jk>. 141 * @return This object. 142 */ 143 public Builder tokenEndpoint(URI value) { 144 tokenEndpoint = assertSecureOrLoopback(reqnn("value", value)); 145 return this; 146 } 147 148 /** 149 * Sets the OAuth client ID. Required for the client-credentials and refresh-token modes. 150 * 151 * @param value The client ID. Must not be <jk>null</jk> or blank. 152 * @return This object. 153 */ 154 public Builder clientId(String value) { 155 clientId = reqnb("value", value); 156 return this; 157 } 158 159 /** 160 * Sets the OAuth client secret as a literal string. 161 * 162 * @param value The client secret. Must not be <jk>null</jk> or blank. 163 * @return This object. 164 */ 165 public Builder clientSecret(String value) { 166 reqnb("value", value); 167 clientSecretSupplier = () -> value; 168 return this; 169 } 170 171 /** 172 * Sets the OAuth client secret via a supplier. 173 * 174 * @param value The supplier. Must not be <jk>null</jk>. 175 * @return This object. 176 */ 177 public Builder clientSecretSupplier(Supplier<String> value) { 178 clientSecretSupplier = reqnn("value", value); 179 return this; 180 } 181 182 /** 183 * Adds requested OAuth scopes. 184 * 185 * @param values The scopes. 186 * @return This object. 187 */ 188 public Builder scope(String... values) { 189 reqnn("values", values); 190 for (var v : values) { 191 reqnb("scope", v); 192 scopes.add(v); 193 } 194 return this; 195 } 196 197 /** 198 * Sets the RFC 8707 {@code resource} indicator (the canonical MCP server URI) sent on every token request. 199 * 200 * @param value The canonical resource URI. Must not be <jk>null</jk>. 201 * @return This object. 202 */ 203 public Builder resource(URI value) { 204 resource = reqnn("value", value); 205 return this; 206 } 207 208 /** 209 * Sets the skew subtracted from a cached token's expiry before it is treated as expired. Default 30s. 210 * 211 * @param value The skew. Must be non-negative. 212 * @return This object. 213 */ 214 public Builder expirySkew(Duration value) { 215 reqnn("value", value); 216 req(!value.isNegative(), "expirySkew must be non-negative (was %s)", value); 217 expirySkew = value; 218 return this; 219 } 220 221 /** 222 * Sets the clock used for token-expiry comparisons. Primarily for tests. 223 * 224 * @param value The clock. Must not be <jk>null</jk>. 225 * @return This object. 226 */ 227 public Builder clock(Clock value) { 228 clock = reqnn("value", value); 229 return this; 230 } 231 232 /** 233 * Sets the connect/read timeout applied to each token request. Default 10 seconds. 234 * 235 * @param value The timeout. Must not be <jk>null</jk> and must be positive. 236 * @return This object. 237 */ 238 public Builder httpTimeout(Duration value) { 239 reqnn("value", value); 240 req(!value.isZero() && !value.isNegative(), "httpTimeout must be positive (was %s)", value); 241 httpTimeout = value; 242 return this; 243 } 244 245 /** 246 * Sets a callback that customizes the Nimbus {@link HTTPRequest} for each token request. 247 * 248 * @param value The callback. Must not be <jk>null</jk>. 249 * @return This object. 250 */ 251 public Builder httpRequestConfigurator(Consumer<HTTPRequest> value) { 252 httpRequestConfigurator = reqnn("value", value); 253 return this; 254 } 255 256 /** 257 * Builds the provider. 258 * 259 * @return A new {@link McpTokenProvider}. 260 */ 261 public McpTokenProvider build() { 262 if (mode != Mode.STATIC) { 263 if (tokenEndpoint == null) 264 throw isex("McpTokenProvider requires tokenEndpoint(...)"); 265 if (clientId == null) 266 throw isex("McpTokenProvider requires clientId(...)"); 267 if (resource == null) 268 throw isex("McpTokenProvider requires resource(...) (RFC 8707 resource indicator)"); 269 } 270 if (mode == Mode.CLIENT_CREDENTIALS && clientSecretSupplier == null) 271 throw isex("McpTokenProvider (client-credentials) requires clientSecret(...) or clientSecretSupplier(...)"); 272 return new McpTokenProvider(this); 273 } 274 } 275 276 private final Mode mode; 277 private final String staticToken; 278 private final URI tokenEndpoint; 279 private final String clientId; 280 private final Supplier<String> clientSecretSupplier; 281 private final Set<String> scopes; 282 private final URI resource; 283 private final Duration expirySkew; 284 private final Clock clock; 285 private final Duration httpTimeout; 286 private final Consumer<HTTPRequest> httpRequestConfigurator; 287 288 private final Object lock = new Object(); 289 private OAuthToken currentToken; 290 @SuppressWarnings({ 291 "java:S9438" // Reassigned inside a lambda in the token-fetch path; Sonar misses the lambda assignment. 292 }) 293 private String currentRefreshToken; 294 private boolean refreshTerminallyRejected; 295 296 /** 297 * Constructor. 298 * 299 * @param b The builder. 300 */ 301 protected McpTokenProvider(Builder b) { 302 this.mode = b.mode; 303 this.staticToken = b.staticToken; 304 this.tokenEndpoint = b.tokenEndpoint; 305 this.clientId = b.clientId; 306 this.clientSecretSupplier = b.clientSecretSupplier; 307 this.scopes = u(cp(b.scopes)); 308 this.resource = b.resource; 309 this.expirySkew = b.expirySkew; 310 this.clock = b.clock; 311 this.httpTimeout = b.httpTimeout; 312 this.httpRequestConfigurator = b.httpRequestConfigurator; 313 this.currentRefreshToken = b.initialRefreshToken; 314 } 315 316 /** 317 * Returns the current valid bearer token, acquiring or refreshing one on demand. 318 * 319 * <p> 320 * Dynamic modes acquire under a single-flight monitor so concurrent callers don't stampede the IdP; the per-request 321 * HTTP timeout ({@link Builder#httpTimeout(Duration)}, default 10s) is the backstop that prevents one hung IdP from 322 * wedging the monitor indefinitely. In refresh mode a terminal {@code invalid_grant} latches the provider: every 323 * subsequent call throws a distinguishable {@link McpAuthException} rather than re-hammering the IdP with a dead 324 * refresh token (SEP-2207). 325 * 326 * @return A non-blank bearer token. Never {@code null} for a successfully configured provider. 327 * @throws OAuthFlowException If a token acquisition/refresh HTTP round-trip fails or the IdP returns an error. 328 * @throws McpAuthException If a prior refresh was terminally rejected ({@code invalid_grant}); re-authorization is 329 * required. 330 */ 331 @Override 332 public String get() { 333 if (mode == Mode.STATIC) 334 return staticToken; 335 synchronized (lock) { 336 if (mode == Mode.REFRESH && refreshTerminallyRejected) 337 throw new McpAuthException("Refresh token was rejected by the authorization server (invalid_grant); re-authorization required"); 338 if (currentToken != null && !currentToken.isExpired(clock.instant(), expirySkew)) 339 return currentToken.accessToken(); 340 OAuthToken t; 341 try { 342 t = acquire(); 343 } catch (OAuthFlowException e) { 344 if (mode == Mode.REFRESH && e.errorCode().filter("invalid_grant"::equals).isPresent()) { 345 refreshTerminallyRejected = true; 346 throw new McpAuthException("Refresh token was rejected by the authorization server (invalid_grant); re-authorization required", e); 347 } 348 throw e; 349 } 350 currentToken = t; 351 if (mode == Mode.REFRESH) 352 t.refreshToken().ifPresent(rt -> currentRefreshToken = rt); 353 return t.accessToken(); 354 } 355 } 356 357 private OAuthToken acquire() { 358 if (mode == Mode.CLIENT_CREDENTIALS) { 359 var f = OAuthClientCredentialsFlow.create() 360 .tokenEndpoint(tokenEndpoint) 361 .clientId(clientId) 362 .clientSecretSupplier(clientSecretSupplier); 363 f.httpTimeout(httpTimeout); 364 scopes.forEach(f::scope); 365 f.resource(resource); 366 if (httpRequestConfigurator != null) 367 f.httpRequestConfigurator(httpRequestConfigurator); 368 return f.build().acquire(); 369 } 370 // REFRESH 371 var f = OAuthRefreshTokenFlow.create() 372 .tokenEndpoint(tokenEndpoint) 373 .clientId(clientId) 374 .refreshToken(currentRefreshToken); 375 if (clientSecretSupplier != null) 376 f.clientSecretSupplier(clientSecretSupplier); 377 f.httpTimeout(httpTimeout); 378 scopes.forEach(f::scope); 379 f.resource(resource); 380 if (httpRequestConfigurator != null) 381 f.httpRequestConfigurator(httpRequestConfigurator); 382 return f.build().acquire(); 383 } 384 385 /** 386 * Returns the refresh token currently held (the most recently rotated value in refresh mode). 387 * 388 * <p> 389 * Callers persisting refresh tokens across process restarts read this after each {@link #get()} to capture a 390 * rotated token (SEP-2207). 391 * 392 * @return The current refresh token, or {@link Optional#empty()} if none is held. 393 */ 394 public Optional<String> currentRefreshToken() { 395 synchronized (lock) { 396 return o(currentRefreshToken); 397 } 398 } 399 400 /** 401 * Creates an {@link McpAuthInterceptor} backed by this provider, ready to attach to an MCP client builder. 402 * 403 * @return A new interceptor. 404 */ 405 public McpAuthInterceptor interceptor() { 406 return new McpAuthInterceptor(this); 407 } 408 409 /** 410 * Redacts token/secret material so nothing sensitive reaches logs via this provider's {@code toString()}. 411 * 412 * @return A redacted string form disclosing only non-secret configuration. 413 */ 414 @Override 415 public String toString() { 416 return "McpTokenProvider[mode=" + mode 417 + ", tokenEndpoint=" + tokenEndpoint 418 + ", clientId=" + clientId 419 + ", scopes=" + scopes 420 + ", resource=" + resource 421 + ", staticToken=" + (staticToken != null ? "<redacted>" : "<none>") 422 + ", refreshToken=" + (currentRefreshToken != null ? "<redacted>" : "<none>") 423 + "]"; 424 } 425}