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.*;
020
021import java.net.*;
022import java.time.*;
023import java.util.*;
024import java.util.function.*;
025
026import org.apache.juneau.http.remote.*;
027import org.apache.juneau.rest.auth.oauth.oidc.*;
028
029import com.nimbusds.oauth2.sdk.http.*;
030
031/**
032 * Orchestrates SEP-2352 registration-mechanism selection, issuer-keying, and re-registration on authorization-server
033 * migration, returning a usable {@link McpClientRegistration} for a discovered AS.
034 *
035 * <p>
036 * Given a discovered {@link OidcMetadata} (whose {@code issuer} identifies the AS and whose {@code extras} carry the
037 * RFC 7591 {@code registration_endpoint}), {@link #resolve(OidcMetadata)} selects credentials per the SEP-2352 rules:
038 * <ul>
039 *    <li><b>Pre-registered credentials</b> ({@link Builder#preRegistered(McpClientRegistration)}) are used only when
040 *       their bound {@code issuer} matches the discovered AS; a mismatch (the AS migrated) surfaces an
041 *       {@link McpAuthException} rather than silently reusing cross-AS credentials (SEP-2352 SHOULD).
042 *    <li><b>With a store</b> ({@link Builder#store(McpClientRegistrationStore)}) the issuer-keyed entry is reused without
043 *       a second DCR round-trip; on migration to a different issuer the store has no entry for the new AS, so the manager
044 *       re-registers via DCR and stores under the new issuer &mdash; the old AS's entry is never reused (SEP-2352
045 *       "MUST NOT reuse client credentials from a different authorization server").
046 *    <li><b>On-demand mode</b> (no store) performs a fresh DCR on every {@link #resolve(OidcMetadata)} call &mdash; fully
047 *       compliant (persisting a registration is optional).
048 *    <li>If the AS advertises no {@code registration_endpoint} and no matching pre-registered credentials exist, an
049 *       {@link McpAuthException} is thrown (no way to obtain a {@code client_id}; CIMD is a tracked fast-follow).
050 * </ul>
051 *
052 * @since 10.0.0
053 */
054@SuppressWarnings({
055   "java:S1192" // Duplicated literals (argument/property names) read more clearly inline than as constants
056})
057public class McpClientRegistrationManager {
058
059   /**
060    * Static creator.
061    *
062    * @return A new builder.
063    */
064   public static Builder create() {
065      return new Builder();
066   }
067
068   /**
069    * Builder.
070    */
071   public static class Builder {
072      McpClientRegistrationStore store;
073      McpClientRegistration preRegistered;
074      McpApplicationType applicationType = McpApplicationType.NATIVE;
075      Supplier<List<URI>> redirectUrisSupplier;
076      final Set<String> scopes = st();
077      boolean confidential;
078      String clientName;
079      Supplier<String> initialAccessTokenSupplier;
080      Duration httpTimeout = McpDynamicClientRegistrar.DEFAULT_HTTP_TIMEOUT;
081      Consumer<HTTPRequest> httpRequestConfigurator;
082      Function<OidcMetadata,McpClientRegistration> dcrOverride;
083      boolean allowPrivateUrls;
084
085      /** Constructor. */
086      protected Builder() {}
087
088      /**
089       * Sets the optional issuer-keyed credential store.  When omitted, the manager runs in on-demand mode and
090       * performs a fresh DCR on every {@code resolve(...)} call (compliant).
091       *
092       * @param value The store.  Must not be <jk>null</jk>.
093       * @return This object.
094       */
095      public Builder store(McpClientRegistrationStore value) {
096         store = reqnn("value", value);
097         return this;
098      }
099
100      /**
101       * Sets pre-registered (manually provisioned) credentials bound to a specific AS {@code issuer}.
102       *
103       * @param value The pre-registered credentials.  Must not be <jk>null</jk>.
104       * @return This object.
105       */
106      public Builder preRegistered(McpClientRegistration value) {
107         preRegistered = reqnn("value", value);
108         return this;
109      }
110
111      /**
112       * Sets the {@code application_type} declared when the manager performs DCR.  Default {@link McpApplicationType#NATIVE}.
113       *
114       * @param value The application type.  Must not be <jk>null</jk>.
115       * @return This object.
116       */
117      public Builder applicationType(McpApplicationType value) {
118         applicationType = reqnn("value", value);
119         return this;
120      }
121
122      /**
123       * Sets the redirect URIs to register when the manager performs DCR.
124       *
125       * @param values The redirect URIs (e.g. {@link LoopbackRedirectUris#portAgnostic(String)}).  Must not be
126       *    <jk>null</jk> or empty.
127       * @return This object.
128       */
129      public Builder redirectUris(List<URI> values) {
130         reqnn("values", values);
131         req(! values.isEmpty(), "redirectUris must not be empty");
132         var copy = u(cp(values));
133         redirectUrisSupplier = () -> copy;
134         return this;
135      }
136
137      /**
138       * Sets a supplier of redirect URIs to register when the manager performs DCR (for the bind-first strategy where
139       * the loopback port is learned per-connection).
140       *
141       * @param value The supplier.  Must not be <jk>null</jk>.
142       * @return This object.
143       */
144      public Builder redirectUrisSupplier(Supplier<List<URI>> value) {
145         redirectUrisSupplier = reqnn("value", value);
146         return this;
147      }
148
149      /**
150       * Adds scopes requested during DCR.
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       * Registers a confidential client during DCR (default public/native).
166       *
167       * @param value <jk>true</jk> to register a confidential client.
168       * @return This object.
169       */
170      public Builder confidential(boolean value) {
171         confidential = value;
172         return this;
173      }
174
175      /**
176       * Sets the human-readable client name declared during DCR.
177       *
178       * @param value The client name.
179       * @return This object.
180       */
181      public Builder clientName(String value) {
182         clientName = reqnb("value", value);
183         return this;
184      }
185
186      /**
187       * Sets the RFC 7591 &sect;3 initial access token for a protected registration endpoint.
188       *
189       * @param value The initial access token.  Must not be <jk>null</jk> or blank.
190       * @return This object.
191       */
192      public Builder initialAccessToken(String value) {
193         reqnb("value", value);
194         initialAccessTokenSupplier = () -> value;
195         return this;
196      }
197
198      /**
199       * Sets the connect/read timeout applied to DCR requests.  Default 10 seconds.
200       *
201       * @param value The timeout.  Must not be <jk>null</jk> and must be positive.
202       * @return This object.
203       */
204      public Builder httpTimeout(Duration value) {
205         reqnn("value", value);
206         req(!value.isZero() && !value.isNegative(), "httpTimeout must be positive (was %s)", value);
207         httpTimeout = value;
208         return this;
209      }
210
211      /**
212       * Sets a callback that customizes the Nimbus {@link HTTPRequest} for each DCR request.
213       *
214       * @param value The callback.  Must not be <jk>null</jk>.
215       * @return This object.
216       */
217      public Builder httpRequestConfigurator(Consumer<HTTPRequest> value) {
218         httpRequestConfigurator = reqnn("value", value);
219         return this;
220      }
221
222      /**
223       * Overrides the registration function the manager invokes to perform DCR (advanced / test seam).
224       *
225       * <p>
226       * The default builds an {@link McpDynamicClientRegistrar} from the discovered {@link OidcMetadata} and performs
227       * a live RFC 7591 round-trip; supply this to inject an alternate registration strategy or a stub.
228       *
229       * @param value The registration function mapping a discovered AS to an issued {@link McpClientRegistration}.
230       *    Must not be <jk>null</jk>.
231       * @return This object.
232       */
233      public Builder registrarFunction(Function<OidcMetadata,McpClientRegistration> value) {
234         dcrOverride = reqnn("value", value);
235         return this;
236      }
237
238      /**
239       * Allows an AS-advertised registration endpoint that points at a loopback, private, link-local or metadata host.
240       *
241       * <p>
242       * By default such endpoints are rejected (the endpoint comes from AS metadata, so a hostile document could
243       * otherwise aim the registration request at an internal service).  Intended for local development and
244       * testing; plain {@code http} is still limited to loopback hosts.
245       *
246       * @param value <jk>true</jk> to skip the host deny-list.
247       * @return This object.
248       */
249      public Builder allowPrivateUrls(boolean value) {
250         allowPrivateUrls = value;
251         return this;
252      }
253
254      /**
255       * Builds the manager.
256       *
257       * @return A new {@link McpClientRegistrationManager}.
258       */
259      public McpClientRegistrationManager build() {
260         return new McpClientRegistrationManager(this);
261      }
262   }
263
264   private final McpClientRegistrationStore store;
265   private final McpClientRegistration preRegistered;
266   private final McpApplicationType applicationType;
267   private final Supplier<List<URI>> redirectUrisSupplier;
268   private final Set<String> scopes;
269   private final boolean confidential;
270   private final String clientName;
271   private final Supplier<String> initialAccessTokenSupplier;
272   private final Duration httpTimeout;
273   private final Consumer<HTTPRequest> httpRequestConfigurator;
274   private final Function<OidcMetadata,McpClientRegistration> dcrOverride;
275   private final boolean allowPrivateUrls;
276
277   /**
278    * Constructor.
279    *
280    * @param b The builder.
281    */
282   protected McpClientRegistrationManager(Builder b) {
283      this.store = b.store;
284      this.preRegistered = b.preRegistered;
285      this.applicationType = b.applicationType;
286      this.redirectUrisSupplier = b.redirectUrisSupplier;
287      this.scopes = u(new LinkedHashSet<>(b.scopes));
288      this.confidential = b.confidential;
289      this.clientName = b.clientName;
290      this.initialAccessTokenSupplier = b.initialAccessTokenSupplier;
291      this.httpTimeout = b.httpTimeout;
292      this.httpRequestConfigurator = b.httpRequestConfigurator;
293      this.dcrOverride = b.dcrOverride;
294      this.allowPrivateUrls = b.allowPrivateUrls;
295   }
296
297   /**
298    * Resolves a usable client registration for the discovered authorization server, applying the SEP-2352 selection,
299    * issuer-keying, and migration rules (see the class javadoc).
300    *
301    * @param as The discovered authorization-server metadata.  Must not be <jk>null</jk>.
302    * @return A usable registration bound to {@code as.issuer()}.  Never <jk>null</jk>.
303    * @throws McpAuthException If credentials cannot be obtained (AS migrated away from pre-registered creds, or the AS
304    *    advertises no {@code registration_endpoint} and no matching pre-registered creds exist).
305    */
306   public McpClientRegistration resolve(OidcMetadata as) {
307      reqnn("as", as);
308      var issuer = as.issuer();
309
310      // Pre-registered credentials: use only if bound to this exact AS; a mismatch means the AS migrated (SEP-2352
311      // MUST NOT reuse cross-AS creds — SHOULD surface an error rather than silently reuse).
312      if (preRegistered != null) {
313         if (! preRegistered.issuer().equals(issuer))
314            throw new McpAuthException("Pre-registered client credentials are bound to issuer '" + preRegistered.issuer()
315               + "' but the resource now indicates a different authorization server '" + issuer
316               + "' (SEP-2352): refusing to reuse credentials across authorization servers");
317         if (store != null)
318            store.put(issuer, preRegistered);
319         return preRegistered;
320      }
321
322      // Store-hit: reuse the issuer-keyed entry without a second DCR round-trip.  On migration to a new issuer the
323      // store has no entry for it, so we fall through to DCR and store under the new issuer, never touching the old.
324      if (store != null) {
325         var hit = store.find(issuer);
326         if (hit.isPresent()) {
327            // Defensive: a buggy durable store that returns an entry keyed under the wrong issuer would otherwise
328            // cause exactly the cross-AS credential reuse SEP-2352 forbids.  Never trust the returned entry's key.
329            if (! hit.get().issuer().equals(issuer))
330               throw new McpAuthException("Client-registration store returned an entry bound to issuer '" + hit.get().issuer()
331                  + "' for a lookup of issuer '" + issuer + "' (SEP-2352): refusing to reuse credentials across authorization servers");
332            return hit.get();
333         }
334      }
335
336      var reg = register(as);
337      if (store != null)
338         store.put(issuer, reg);
339      return reg;
340   }
341
342   private McpClientRegistration register(OidcMetadata as) {
343      if (dcrOverride != null)
344         return dcrOverride.apply(as);
345      var regEndpoint = registrationEndpoint(as, allowPrivateUrls)
346         .orElseThrow(() -> new McpAuthException("Authorization server '" + as.issuer()
347            + "' advertises no registration_endpoint and no matching pre-registered credentials are configured"
348            + " (Dynamic Client Registration not possible; CIMD is out of scope)"));
349      if (redirectUrisSupplier == null)
350         throw new McpAuthException("McpClientRegistrationManager requires redirectUris(...) to perform Dynamic Client Registration");
351      var b = McpDynamicClientRegistrar.create()
352         .registrationEndpoint(regEndpoint)
353         .issuer(as.issuer())
354         .applicationType(applicationType)
355         .addRedirectUris(redirectUrisSupplier.get())
356         .confidential(confidential)
357         .httpTimeout(httpTimeout);
358      scopes.forEach(b::scope);
359      if (clientName != null)
360         b.clientName(clientName);
361      if (initialAccessTokenSupplier != null)
362         b.initialAccessToken(initialAccessTokenSupplier.get());
363      if (httpRequestConfigurator != null)
364         b.httpRequestConfigurator(httpRequestConfigurator);
365      return b.build().register();
366   }
367
368   /**
369    * Extracts the RFC 7591 {@code registration_endpoint} from the discovered AS metadata's extras, if present.
370    *
371    * <p>
372    * The value is AS-supplied, so a hostile/misconfigured AS document is defended against here: a malformed URI or a
373    * plaintext {@code http://} (non-loopback) endpoint yields the documented {@link McpAuthException} rather than a raw
374    * {@link IllegalArgumentException} (from {@code URI.create}) or a downstream {@link IllegalStateException} (from the
375    * registrar's https gate).
376    */
377   static Optional<URI> registrationEndpoint(OidcMetadata as, boolean allowPrivateUrls) {
378      var v = as.extras().get("registration_endpoint");
379      if (v == null)
380         return oe();
381      URI uri;
382      try {
383         uri = URI.create(v.toString());
384      } catch (IllegalArgumentException e) {
385         throw new McpAuthException("Authorization server advertised a malformed registration_endpoint: '" + v + "'", e);
386      }
387      try {
388         RemoteUrlPolicy.requireAllowedUrl(uri.toString(), allowPrivateUrls);
389      } catch (IllegalArgumentException e) {
390         throw new McpAuthException("Authorization server advertised a registration_endpoint that is not permitted: '" + uri + "': " + e.getMessage(), e);
391      }
392      if (! McpDynamicClientRegistrar.isSecureOrLoopback(uri))
393         throw new McpAuthException("Authorization server advertised a non-https registration_endpoint (loopback exempt): '" + uri + "'");
394      return o(uri);
395   }
396}