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.io.*;
023import java.net.*;
024import java.time.*;
025import java.util.*;
026import java.util.function.*;
027
028import org.apache.juneau.rest.auth.oauth.flow.*;
029import org.apache.juneau.rest.auth.oauth.oidc.*;
030
031import com.nimbusds.oauth2.sdk.*;
032import com.nimbusds.oauth2.sdk.http.*;
033import com.nimbusds.oauth2.sdk.id.*;
034import com.nimbusds.oauth2.sdk.pkce.*;
035
036/**
037 * Interactive authorization-code + PKCE (S256) token acquisition for headless / CLI use.
038 *
039 * <p>
040 * Builds on the relocated {@link OAuthAuthorizationCodeFlow}: opens a {@link LoopbackRedirectReceiver}, generates the
041 * {@code state} and PKCE {@code code_verifier}/{@code code_challenge}, hands the authorization URL to a caller-supplied
042 * browser launcher, waits for the loopback redirect, and exchanges the returned code for a token.
043 *
044 * <p>
045 * Security checks on the callback:
046 * <ul>
047 *    <li><b>CSRF</b> &mdash; the returned {@code state} must match the one that was issued (single-use via
048 *       {@link EphemeralStore}).
049 *    <li><b>SEP-2468 ({@code iss}, RFC 9207)</b> &mdash; the callback {@code iss} parameter must equal the
050 *       discovered/expected issuer; a mismatch is rejected.  The check gates BOTH the success and error paths (a client
051 *       MUST NOT act on an error response whose issuer doesn't match).  {@link Builder#expectedIssuer(URI)} is required
052 *       by default (opt out with {@link Builder#skipIssuerValidation(boolean)}); a missing {@code iss} is accepted
053 *       unless {@link Builder#requireIssuerResponseParameter(boolean)} is set.
054 * </ul>
055 *
056 * <p>
057 * {@link Builder#resource(URI)} (the RFC 8707 resource indicator) is required so the acquired token's audience is bound
058 * to the target MCP server.
059 *
060 * <p>
061 * The optional {@link Builder#offlineAccess(boolean)} adds the {@code offline_access} scope so the IdP issues a refresh
062 * token that can subsequently drive an {@link McpTokenProvider} refresh-token provider (SEP-2207).
063 *
064 * @since 10.0.0
065 */
066@SuppressWarnings({
067   "java:S1192" // Duplicated literals (argument/property names) read more clearly inline than as constants
068})
069public class McpAuthorizationCodeAcquirer {
070
071   /**
072    * Static creator.
073    *
074    * @return A new builder.
075    */
076   public static Builder create() {
077      return new Builder();
078   }
079
080   /**
081    * Builder.
082    */
083   public static class Builder {
084      private URI authorizationEndpoint;
085      private URI tokenEndpoint;
086      private String clientId;
087      private Supplier<String> clientSecretSupplier;
088      private final Set<String> scopes = st();
089      private boolean offlineAccess;
090      private URI resource;
091      private URI expectedIssuer;
092      private boolean skipIssuerValidation;
093      private boolean requireIssuerResponseParameter;
094      private String redirectPath = DEFAULT_REDIRECT_PATH;
095      private int redirectPort;  // 0 == ephemeral / port-agnostic (the default).
096      private Consumer<URI> browserLauncher = McpAuthorizationCodeAcquirer::printAuthorizationUrl;
097      private EphemeralStore store;
098      private Duration httpTimeout = DEFAULT_HTTP_TIMEOUT;
099      private Consumer<HTTPRequest> httpRequestConfigurator;
100
101      /** Constructor. */
102      protected Builder() {}
103
104      /**
105       * Sets the authorization endpoint URL.  Required.
106       *
107       * @param value The endpoint URL.
108       * @return This object.
109       */
110      public Builder authorizationEndpoint(URI value) {
111         authorizationEndpoint = assertSecureOrLoopback(reqnn("value", value));
112         return this;
113      }
114
115      /**
116       * Sets the token endpoint URL.  Required.
117       *
118       * @param value The endpoint URL.
119       * @return This object.
120       */
121      public Builder tokenEndpoint(URI value) {
122         tokenEndpoint = assertSecureOrLoopback(reqnn("value", value));
123         return this;
124      }
125
126      /**
127       * Sets the OAuth client ID.  Required.
128       *
129       * @param value The client ID.
130       * @return This object.
131       */
132      public Builder clientId(String value) {
133         clientId = reqnb("value", value);
134         return this;
135      }
136
137      /**
138       * Sets the client secret (omit for a public/native PKCE-only client).
139       *
140       * @param value The client secret.
141       * @return This object.
142       */
143      public Builder clientSecret(String value) {
144         reqnb("value", value);
145         clientSecretSupplier = () -> value;
146         return this;
147      }
148
149      /**
150       * Adds requested scopes.
151       *
152       * @param values The scopes.
153       * @return This object.
154       */
155      public Builder scope(String... values) {
156         reqnn("values", values);
157         for (var v : values) {
158            reqnb("scope", v);
159            scopes.add(v);
160         }
161         return this;
162      }
163
164      /**
165       * Requests the {@code offline_access} scope so the IdP issues a refresh token (SEP-2207).
166       *
167       * @param value <jk>true</jk> to add {@code offline_access}.
168       * @return This object.
169       */
170      public Builder offlineAccess(boolean value) {
171         offlineAccess = value;
172         return this;
173      }
174
175      /**
176       * Sets the RFC 8707 {@code resource} indicator (the canonical MCP server URI).
177       *
178       * @param value The canonical resource URI.  Must not be <jk>null</jk>.
179       * @return This object.
180       */
181      public Builder resource(URI value) {
182         resource = reqnn("value", value);
183         return this;
184      }
185
186      /**
187       * Sets the expected issuer the callback {@code iss} parameter is validated against (SEP-2468).
188       *
189       * <p>
190       * Typically the {@code issuer} returned by {@code OidcDiscoveryClient} for the discovered authorization
191       * server.
192       *
193       * @param value The expected issuer.  Must not be <jk>null</jk>.
194       * @return This object.
195       */
196      public Builder expectedIssuer(URI value) {
197         expectedIssuer = reqnn("value", value);
198         return this;
199      }
200
201      /**
202       * Explicitly opts out of the SEP-2468 {@code iss} validation.
203       *
204       * <p>
205       * {@code iss} validation is on by default; {@link #build()} requires {@link #expectedIssuer(URI)} unless this
206       * is set to <jk>true</jk>.  Only disable this against an authorization server known not to emit {@code iss}.
207       *
208       * @param value <jk>true</jk> to skip the {@code iss} check.
209       * @return This object.
210       */
211      public Builder skipIssuerValidation(boolean value) {
212         skipIssuerValidation = value;
213         return this;
214      }
215
216      /**
217       * Applies the discovered authorization-server metadata: sets the expected issuer and requires the {@code iss}
218       * response parameter when the server advertises {@code authorization_response_iss_parameter_supported}
219       * (RFC 9207).
220       *
221       * @param metadata The discovered metadata.  Must not be <jk>null</jk>.
222       * @return This object.
223       */
224      public Builder authorizationServer(OidcMetadata metadata) {
225         reqnn("metadata", metadata);
226         expectedIssuer = metadata.issuer();
227         requireIssuerResponseParameter = metadata.authorizationResponseIssParameterSupported();
228         return this;
229      }
230
231      /**
232       * Requires the authorization response to carry an {@code iss} parameter, rejecting a response that omits it.
233       *
234       * <p>
235       * Set automatically by {@link #authorizationServer(OidcMetadata)}; set explicitly when the discovered authorization-server metadata advertises
236       * {@code authorization_response_iss_parameter_supported} (RFC 9207); see
237       * {@link org.apache.juneau.rest.auth.oauth.oidc.OidcMetadata#authorizationResponseIssParameterSupported()}.
238       *
239       * @param value <jk>true</jk> to reject a response with no {@code iss} parameter.
240       * @return This object.
241       */
242      public Builder requireIssuerResponseParameter(boolean value) {
243         requireIssuerResponseParameter = value;
244         return this;
245      }
246
247      /**
248       * Sets the loopback redirect path.  Default {@code /callback}.
249       *
250       * @param value The path (must start with {@code /}).  Must not be <jk>null</jk> or blank.
251       * @return This object.
252       */
253      public Builder redirectPath(String value) {
254         redirectPath = reqnb("value", value);
255         req(redirectPath.startsWith("/"), "redirectPath must start with '/' (was '%s')", redirectPath);
256         return this;
257      }
258
259      /**
260       * Sets a fixed loopback redirect port so the receiver binds exactly that port (the "bind-first" strategy for
261       * strict exact-match authorization servers).
262       *
263       * <p>
264       * Defaults to {@code 0}, meaning an ephemeral port (the RFC 8252 &sect;7.3 port-agnostic strategy) &mdash; the
265       * simplest interoperable choice.  Set a non-zero port only when the authorization server registration used a
266       * bind-first {@link LoopbackRedirectUris#forPort(int, String) forPort} redirect; {@link McpClientRegistrations#configure}
267       * wires this automatically from such a registration.
268       *
269       * @param value The fixed loopback port in {@code 1..65535}, or {@code 0} for an ephemeral port.
270       * @return This object.
271       */
272      public Builder redirectPort(int value) {
273         req(value == 0 || (value >= 1 && value <= 65535), "redirectPort must be 0 (ephemeral) or in 1..65535 (was %s)", value);
274         redirectPort = value;
275         return this;
276      }
277
278      /**
279       * Sets the callback invoked with the authorization URL so the caller can open it in a browser (or print it).
280       *
281       * @param value The launcher.  Must not be <jk>null</jk>.
282       * @return This object.
283       */
284      public Builder browserLauncher(Consumer<URI> value) {
285         browserLauncher = reqnn("value", value);
286         return this;
287      }
288
289      /**
290       * Sets the ephemeral state/verifier store.  Defaults to a fresh {@link EphemeralStore}.
291       *
292       * @param value The store.  Must not be <jk>null</jk>.
293       * @return This object.
294       */
295      public Builder store(EphemeralStore value) {
296         store = reqnn("value", value);
297         return this;
298      }
299
300      /**
301       * Sets the connect/read timeout applied to the token-exchange request.  Default 10 seconds.
302       *
303       * @param value The timeout.  Must not be <jk>null</jk> and must be positive.
304       * @return This object.
305       */
306      public Builder httpTimeout(Duration value) {
307         reqnn("value", value);
308         req(!value.isZero() && !value.isNegative(), "httpTimeout must be positive (was %s)", value);
309         httpTimeout = value;
310         return this;
311      }
312
313      /**
314       * Sets a callback that customizes the Nimbus {@link HTTPRequest} for the token exchange.
315       *
316       * @param value The callback.  Must not be <jk>null</jk>.
317       * @return This object.
318       */
319      public Builder httpRequestConfigurator(Consumer<HTTPRequest> value) {
320         httpRequestConfigurator = reqnn("value", value);
321         return this;
322      }
323
324      /**
325       * Builds the acquirer.
326       *
327       * @return A new {@link McpAuthorizationCodeAcquirer}.
328       */
329      public McpAuthorizationCodeAcquirer build() {
330         if (authorizationEndpoint == null)
331            throw isex("McpAuthorizationCodeAcquirer requires authorizationEndpoint(...)");
332         if (tokenEndpoint == null)
333            throw isex("McpAuthorizationCodeAcquirer requires tokenEndpoint(...)");
334         if (clientId == null)
335            throw isex("McpAuthorizationCodeAcquirer requires clientId(...)");
336         if (resource == null)
337            throw isex("McpAuthorizationCodeAcquirer requires resource(...) (RFC 8707 resource indicator)");
338         if (expectedIssuer == null && ! skipIssuerValidation)
339            throw isex("McpAuthorizationCodeAcquirer requires expectedIssuer(...) (SEP-2468); call skipIssuerValidation(true) to opt out");
340         if (store == null)
341            store = EphemeralStore.create();
342         return new McpAuthorizationCodeAcquirer(this);
343      }
344   }
345
346   /** Default connect/read timeout applied to the token-exchange request when the caller sets none. */
347   static final Duration DEFAULT_HTTP_TIMEOUT = Duration.ofSeconds(10);
348
349   /**
350    * Default loopback callback path.  Not RFC 8252-mandated (only the loopback address itself is spec-mandated) and
351    * already fully caller-overridable via {@link Builder#redirectPath(String)}; this is merely the conventional
352    * default.
353    */
354   @SuppressWarnings({
355      "java:S1075" // Default value for an already caller-configurable Builder#redirectPath(String); not a hardcoded endpoint.
356   })
357   static final String DEFAULT_REDIRECT_PATH = "/callback";
358
359   /** Default HTML body served on the loopback callback so the browser tab shows a friendly confirmation. */
360   private static final String DEFAULT_CALLBACK_HTML =
361      "<html><body><h3>Authorization received</h3><p>You may close this window and return to the application.</p></body></html>";
362
363   private final URI authorizationEndpoint;
364   private final URI tokenEndpoint;
365   private final String clientId;
366   private final Supplier<String> clientSecretSupplier;
367   private final Set<String> scopes;
368   private final URI resource;
369   private final URI expectedIssuer;
370   private final boolean skipIssuerValidation;
371   private final boolean requireIssuerResponseParameter;
372   private final String redirectPath;
373   private final int redirectPort;
374   private final Consumer<URI> browserLauncher;
375   private final EphemeralStore store;
376   private final Duration httpTimeout;
377   private final Consumer<HTTPRequest> httpRequestConfigurator;
378
379   /**
380    * Constructor.
381    *
382    * @param b The builder.
383    */
384   protected McpAuthorizationCodeAcquirer(Builder b) {
385      this.authorizationEndpoint = b.authorizationEndpoint;
386      this.tokenEndpoint = b.tokenEndpoint;
387      this.clientId = b.clientId;
388      this.clientSecretSupplier = b.clientSecretSupplier;
389      var s = new LinkedHashSet<>(b.scopes);
390      if (b.offlineAccess)
391         s.add("offline_access");
392      this.scopes = u(s);
393      this.resource = b.resource;
394      this.expectedIssuer = b.expectedIssuer;
395      this.skipIssuerValidation = b.skipIssuerValidation;
396      this.requireIssuerResponseParameter = b.requireIssuerResponseParameter;
397      this.redirectPath = b.redirectPath;
398      this.redirectPort = b.redirectPort;
399      this.browserLauncher = b.browserLauncher;
400      this.store = b.store;
401      this.httpTimeout = b.httpTimeout;
402      this.httpRequestConfigurator = b.httpRequestConfigurator;
403   }
404
405   /**
406    * Default {@link Builder#browserLauncher(Consumer)}: prints the authorization URL to standard output so a headless
407    * user can open it manually (rather than silently doing nothing).
408    *
409    * @param authUrl The authorization URL.
410    */
411   @SuppressWarnings({
412      "java:S106" // Intentional user-facing console prompt for headless CLI authorization; not diagnostic logging.
413   })
414   private static void printAuthorizationUrl(URI authUrl) {
415      System.out.println("Open the following URL in a browser to authorize:\n  " + authUrl);
416   }
417
418   /**
419    * Runs the full interactive acquisition: starts the loopback listener, opens the authorization URL, waits for the
420    * redirect, validates it, and exchanges the code for a token.
421    *
422    * @param timeout The maximum time to wait for the user to complete authorization at the IdP.  Must not be
423    *    <jk>null</jk>.
424    * @return The acquired token.
425    * @throws McpAuthException If the listener cannot start, the wait times out, or the callback fails validation.
426    * @throws OAuthFlowException If the token-exchange HTTP round-trip fails or the IdP returns an error.
427    */
428   public OAuthToken acquire(Duration timeout) {
429      reqnn("timeout", timeout);
430      LoopbackRedirectReceiver receiver;
431      try {
432         receiver = new LoopbackRedirectReceiver(redirectPath, redirectPort, DEFAULT_CALLBACK_HTML);
433      } catch (IOException e) {
434         throw new McpAuthException("Failed to start the loopback redirect listener", e);
435      }
436      try (receiver) {
437         var flow = buildFlow(receiver.redirectUri());
438         var verifier = new CodeVerifier();
439         var state = new State().getValue();
440         var authUrl = buildAuthorizationUrl(flow, state, verifier);
441         store.store(state, verifier.getValue(), expectedIssuer);
442         receiver.expectState(state);
443         browserLauncher.accept(authUrl);
444         var callbackUri = receiver.awaitCallback(timeout);
445         return handleCallback(flow, callbackUri);
446      }
447   }
448
449   /**
450    * Builds the authorization URL for a given state and PKCE verifier (exposed for callers driving their own
451    * user-agent interaction).
452    *
453    * @param flow The configured flow.  Must not be <jk>null</jk>.
454    * @param state The opaque state.  Must not be <jk>null</jk> or blank.
455    * @param verifier The PKCE verifier.  Must not be <jk>null</jk>.
456    * @return The authorization URL.
457    */
458   public URI buildAuthorizationUrl(OAuthAuthorizationCodeFlow flow, String state, CodeVerifier verifier) {
459      reqnn("flow", flow);
460      reqnn("verifier", verifier);
461      var challenge = CodeChallenge.compute(CodeChallengeMethod.S256, verifier);
462      return flow.buildAuthorizationUrl(state, challenge);
463   }
464
465   /**
466    * Validates a loopback callback and exchanges the authorization code for a token.
467    *
468    * <p>
469    * Consumes the pending {@code state} entry (single-use), performs the SEP-2468 {@code iss} check against the issuer
470    * recorded when the request was started, then exchanges the code.
471    *
472    * @param flow The configured flow.  Must not be <jk>null</jk>.
473    * @param callbackUri The full loopback callback URI.  Must not be <jk>null</jk>.
474    * @return The acquired token.
475    * @throws McpAuthException If the callback is an error response, the state is unknown/replayed, or the {@code iss}
476    *    check fails.
477    */
478   public OAuthToken handleCallback(OAuthAuthorizationCodeFlow flow, URI callbackUri) {
479      reqnn("flow", flow);
480      reqnn("callbackUri", callbackUri);
481      var resp = parse(callbackUri);
482      var state = resp.getState() == null ? null : resp.getState().getValue();
483      if (state == null)
484         throw new McpAuthException("Authorization callback is missing the state parameter");
485      var pending = store.consume(state)
486         .orElseThrow(() -> new McpAuthException("Authorization callback state is unknown, expired, or replayed"));
487      var code = extractCode(resp, pending.expectedIssuer(), skipIssuerValidation, requireIssuerResponseParameter);
488      return flow.exchange(code, new CodeVerifier(pending.codeVerifier()));
489   }
490
491   /**
492    * Validates an authorization-code callback and returns the authorization code, without any token exchange or
493    * state-store interaction.
494    *
495    * <p>
496    * This is the pure SEP-2468 / CSRF validation step.  The {@code iss} comparison gates BOTH success and error
497    * responses (per the MCP spec a client MUST NOT act on an {@code error}/{@code error_description}/{@code error_uri}
498    * from a response whose {@code iss} does not match), so an error response with a mismatched issuer is reported as
499    * an issuer mismatch rather than a denial.  A missing/mismatched {@code state} is rejected as CSRF.  When
500    * {@code iss} is absent it is accepted (future-proofed for the eventual "reject if absent" MUST); use
501    * {@link #validateAuthorizationResponse(URI, String, URI, boolean)} to require it.
502    *
503    * @param callbackUri The full callback URI.  Must not be <jk>null</jk>.
504    * @param expectedState The state issued when the authorization request was built.  Must not be <jk>null</jk>.
505    * @param expectedIssuer The discovered issuer to validate {@code iss} against.  Must not be <jk>null</jk>.
506    * @return The authorization code.
507    * @throws McpAuthException If validation fails.
508    */
509   public static String validateAuthorizationResponse(URI callbackUri, String expectedState, URI expectedIssuer) {
510      return validateAuthorizationResponse(callbackUri, expectedState, expectedIssuer, false);
511   }
512
513   /**
514    * Validates an authorization-code callback and returns the authorization code, without any token exchange or
515    * state-store interaction.
516    *
517    * @param callbackUri The full callback URI.  Must not be <jk>null</jk>.
518    * @param expectedState The state issued when the authorization request was built.  Must not be <jk>null</jk>.
519    * @param expectedIssuer The discovered issuer to validate {@code iss} against.  Must not be <jk>null</jk>.
520    * @param requireIssuerParameter <jk>true</jk> to reject a response that omits the {@code iss} parameter (RFC 9207
521    *    {@code authorization_response_iss_parameter_supported}).
522    * @return The authorization code.
523    * @throws McpAuthException If validation fails.
524    */
525   public static String validateAuthorizationResponse(URI callbackUri, String expectedState, URI expectedIssuer, boolean requireIssuerParameter) {
526      reqnn("callbackUri", callbackUri);
527      reqnb("expectedState", expectedState);
528      reqnn("expectedIssuer", expectedIssuer);
529      var resp = parse(callbackUri);
530      var state = resp.getState() == null ? null : resp.getState().getValue();
531      if (neq(expectedState, state))
532         throw new McpAuthException("Authorization callback state mismatch (possible CSRF)");
533      return extractCode(resp, expectedIssuer, false, requireIssuerParameter);
534   }
535
536   private static AuthorizationResponse parse(URI callbackUri) {
537      try {
538         return AuthorizationResponse.parse(callbackUri);
539      } catch (ParseException e) {
540         throw new McpAuthException("Authorization callback could not be parsed", e);
541      }
542   }
543
544   private static String extractCode(AuthorizationResponse resp, URI expectedIssuer, boolean skipIssuerValidation, boolean requireIssuerParameter) {
545      // SEP-2468: the iss check gates BOTH the success and error paths — a client MUST NOT act on an error response
546      // whose issuer doesn't match, so this runs before the indicatesSuccess() branch.
547      if (! skipIssuerValidation) {
548         var iss = resp.getIssuer();
549         if (iss == null) {
550            if (requireIssuerParameter)
551               throw new McpAuthException("Authorization response is missing the required iss parameter (SEP-2468 / RFC 9207)");
552         } else if (expectedIssuer == null || ! iss.getValue().equals(expectedIssuer.toString())) {
553            throw new McpAuthException("Authorization response issuer mismatch (SEP-2468): expected '"
554               + expectedIssuer + "' but got '" + iss.getValue() + "'");
555         }
556      }
557      if (! resp.indicatesSuccess()) {
558         throw new McpAuthException("Authorization request was denied: " + resp.toErrorResponse().getErrorObject().getCode());
559      }
560      return resp.toSuccessResponse().getAuthorizationCode().getValue();
561   }
562
563   private OAuthAuthorizationCodeFlow buildFlow(URI redirectUri) {
564      var b = OAuthAuthorizationCodeFlow.create()
565         .authorizationEndpoint(authorizationEndpoint)
566         .tokenEndpoint(tokenEndpoint)
567         .clientId(clientId)
568         .redirectUri(redirectUri)
569         .httpTimeout(httpTimeout);
570      if (clientSecretSupplier != null)
571         b.clientSecretSupplier(clientSecretSupplier);
572      scopes.forEach(b::scope);
573      b.resource(resource);
574      if (httpRequestConfigurator != null)
575         b.httpRequestConfigurator(httpRequestConfigurator);
576      return b.build();
577   }
578
579   /**
580    * The configured fixed loopback redirect port ({@code 0} means ephemeral).  Package-private for test verification of
581    * the bind-first port carry-through.
582    *
583    * @return The redirect port.
584    */
585   int redirectPort() {
586      return redirectPort;
587   }
588}