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 019 020import java.io.*; 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.*; 030import com.nimbusds.oauth2.sdk.http.*; 031import com.nimbusds.oauth2.sdk.util.*; 032 033import net.minidev.json.*; 034import static org.apache.juneau.commons.utils.Shorts.*; 035 036/** 037 * Fetches and parses an RFC 9728 Protected Resource Metadata (PRM) document, and resolves the authorization server a 038 * protected MCP resource delegates to. 039 * 040 * <p> 041 * This is the client half of the OAuth 2.1 baseline PRM discovery required by the MCP {@code 2026-07-28} revision: on a 042 * {@code 401 WWW-Authenticate} challenge the client recovers the {@code resource_metadata} pointer 043 * ({@link WwwAuthenticateChallenge#resourceMetadata()}), fetches the PRM document here, selects an authorization server 044 * ({@link McpProtectedResourceMetadata#firstAuthorizationServer()}), and validates that server's issuer identity via 045 * {@link OidcDiscoveryClient} (RFC 8414 / OIDC Discovery). 046 * 047 * <p> 048 * When an expected resource identifier is supplied ({@link Builder#expectedResource(URI)} or the {@code expectedResource} 049 * argument of {@link #fetch(URI, URI)} / {@link #parse(String, URI, URI)}), the PRM document's {@code resource} field is 050 * validated against it per RFC 9728 §3.3 (exact string match, mirroring the issuer-identity posture) and a mismatch 051 * is rejected — this defends against a malicious server pointing the client at a PRM document minted for a 052 * different resource. An expected resource is required unless {@link Builder#skipResourceValidation(boolean)} is set. 053 * 054 * <p> 055 * By default the PRM URL and any discovered authorization-server URI must use {@code https} and must not point at a 056 * loopback, private, link-local or metadata host; {@link Builder#allowPrivateUrls(boolean)} lifts the host restriction 057 * (and permits plain {@code http} for loopback hosts), and {@link Builder#allowInsecureHttp(boolean)} disables the 058 * scheme check. 059 * 060 * @since 10.0.0 061 */ 062@SuppressWarnings({ 063 "java:S1192" // Duplicated literals (argument/property names) read more clearly inline than as constants 064}) 065public class McpProtectedResourceMetadataClient { 066 067 /** Default connect/read timeout applied to a PRM fetch / AS discovery when the caller sets none. */ 068 static final Duration DEFAULT_HTTP_TIMEOUT = Duration.ofSeconds(10); 069 070 /** 071 * Static creator. 072 * 073 * @return A new builder. 074 */ 075 public static Builder create() { 076 return new Builder(); 077 } 078 079 /** 080 * Builder. 081 */ 082 public static class Builder { 083 private URI expectedResource; 084 private Duration httpTimeout = DEFAULT_HTTP_TIMEOUT; 085 private boolean allowInsecureHttp; 086 private boolean allowPrivateUrls; 087 private boolean skipResourceValidation; 088 private Consumer<HTTPRequest> httpRequestConfigurator; 089 090 /** Constructor. */ 091 protected Builder() {} 092 093 /** 094 * Sets the expected {@code resource} identifier the PRM document's {@code resource} field is validated against 095 * (RFC 9728 §3.3). 096 * 097 * <p> 098 * This is the canonical URI of the MCP server the client was actually talking to. A per-call value passed to 099 * {@link #fetch(URI, URI)} / {@link #parse(String, URI, URI)} overrides this. 100 * 101 * @param value The expected resource identifier. Must not be <jk>null</jk>. 102 * @return This object. 103 */ 104 public Builder expectedResource(URI value) { 105 expectedResource = reqnn("value", value); 106 return this; 107 } 108 109 /** 110 * Sets the connect/read timeout applied to the PRM fetch and AS discovery. Default 10 seconds. 111 * 112 * @param value The timeout. Must not be <jk>null</jk> and must be positive. 113 * @return This object. 114 */ 115 public Builder httpTimeout(Duration value) { 116 reqnn("value", value); 117 req(!value.isZero() && !value.isNegative(), "httpTimeout must be positive (was %s)", value); 118 httpTimeout = value; 119 return this; 120 } 121 122 /** 123 * Allows PRM / authorization-server URLs that point at loopback, private, link-local or metadata hosts. 124 * 125 * <p> 126 * Intended for local development and testing. Also permits plain {@code http} for loopback hosts. 127 * 128 * @param value <jk>true</jk> to skip the host deny-list. 129 * @return This object. 130 */ 131 public Builder allowPrivateUrls(boolean value) { 132 allowPrivateUrls = value; 133 return this; 134 } 135 136 /** 137 * Skips the check of the PRM {@code resource} field against an expected resource identifier. 138 * 139 * <p> 140 * By default an expected resource is required. 141 * 142 * @param value <jk>true</jk> to skip the resource identity check. 143 * @return This object. 144 */ 145 public Builder skipResourceValidation(boolean value) { 146 skipResourceValidation = value; 147 return this; 148 } 149 150 /** 151 * Allows plain {@code http} PRM / authorization-server URLs for non-loopback hosts. 152 * 153 * @param value <jk>true</jk> to skip the {@code https} scheme check. 154 * @return This object. 155 */ 156 public Builder allowInsecureHttp(boolean value) { 157 allowInsecureHttp = value; 158 return this; 159 } 160 161 /** 162 * Sets a callback that customizes the Nimbus {@link HTTPRequest} used for the PRM fetch and AS discovery. 163 * 164 * @param value The callback. Must not be <jk>null</jk>. 165 * @return This object. 166 */ 167 public Builder httpRequestConfigurator(Consumer<HTTPRequest> value) { 168 httpRequestConfigurator = reqnn("value", value); 169 return this; 170 } 171 172 /** 173 * Builds the client. 174 * 175 * @return A new {@link McpProtectedResourceMetadataClient}. 176 */ 177 public McpProtectedResourceMetadataClient build() { 178 return new McpProtectedResourceMetadataClient(this); 179 } 180 } 181 182 private final URI expectedResource; 183 private final Duration httpTimeout; 184 private final boolean allowInsecureHttp; 185 private final boolean allowPrivateUrls; 186 private final boolean skipResourceValidation; 187 private final Consumer<HTTPRequest> httpRequestConfigurator; 188 189 /** 190 * Constructor. 191 * 192 * @param b The builder. 193 */ 194 protected McpProtectedResourceMetadataClient(Builder b) { 195 this.expectedResource = b.expectedResource; 196 this.httpTimeout = b.httpTimeout; 197 this.allowInsecureHttp = b.allowInsecureHttp; 198 this.allowPrivateUrls = b.allowPrivateUrls; 199 this.skipResourceValidation = b.skipResourceValidation; 200 this.httpRequestConfigurator = b.httpRequestConfigurator; 201 } 202 203 /** 204 * Fetches and parses the PRM document at the supplied URL, validating its {@code resource} field against the 205 * builder-configured {@link Builder#expectedResource(URI)} (if any). 206 * 207 * @param prmUrl The PRM document URL (typically the {@code resource_metadata} pointer from a {@code 401} 208 * challenge, or the well-known URL for the resource). Must not be <jk>null</jk>. 209 * @return The parsed metadata. 210 * @throws McpAuthException If the fetch fails, the document cannot be parsed, or the resource identity check fails. 211 */ 212 public McpProtectedResourceMetadata fetch(URI prmUrl) { 213 return fetch(prmUrl, expectedResource); 214 } 215 216 /** 217 * Fetches and parses the PRM document at the supplied URL, validating its {@code resource} field against the 218 * supplied expected resource identifier (RFC 9728 §3.3). 219 * 220 * @param prmUrl The PRM document URL. Must not be <jk>null</jk>. 221 * @param expectedResource The resource identifier the client was actually talking to. May be <jk>null</jk> only 222 * when {@link Builder#skipResourceValidation(boolean)} is set. 223 * @return The parsed metadata. 224 * @throws McpAuthException If the fetch fails, the document cannot be parsed, or the resource identity check fails. 225 */ 226 public McpProtectedResourceMetadata fetch(URI prmUrl, URI expectedResource) { 227 reqnn("prmUrl", prmUrl); 228 requireSecure(prmUrl, "Protected-resource-metadata URL"); 229 HTTPResponse resp; 230 try { 231 var req = new HTTPRequest(HTTPRequest.Method.GET, prmUrl.toURL()); 232 req.setConnectTimeout((int) httpTimeout.toMillis()); 233 req.setReadTimeout((int) httpTimeout.toMillis()); 234 req.setFollowRedirects(false); 235 req.setAccept("application/json"); 236 if (httpRequestConfigurator != null) 237 httpRequestConfigurator.accept(req); 238 resp = req.send(); 239 } catch (IOException e) { 240 throw new McpAuthException("Protected-resource-metadata fetch failed for " + prmUrl, e); 241 } 242 if (!resp.indicatesSuccess()) 243 throw new McpAuthException("Protected-resource-metadata fetch returned HTTP " + resp.getStatusCode() + " for " + prmUrl); 244 return parse(resp.getBody(), prmUrl, expectedResource); 245 } 246 247 /** 248 * Parses a PRM JSON document body, validating its {@code resource} field against the builder-configured 249 * {@link Builder#expectedResource(URI)} (if any). 250 * 251 * @param json The JSON document body. Must not be <jk>null</jk>. 252 * @param source The source URI, used only for error messages. May be <jk>null</jk>. 253 * @return The parsed metadata. 254 * @throws McpAuthException If the document cannot be parsed, is missing the required {@code resource} field, or 255 * fails the resource identity check. 256 */ 257 public McpProtectedResourceMetadata parse(String json, URI source) { 258 return parse(json, source, expectedResource); 259 } 260 261 /** 262 * Parses a PRM JSON document body, validating its {@code resource} field against the supplied expected resource 263 * identifier (RFC 9728 §3.3). 264 * 265 * @param json The JSON document body. Must not be <jk>null</jk>. 266 * @param source The source URI, used only for error messages. May be <jk>null</jk>. 267 * @param expectedResource The resource identifier the client was actually talking to. May be <jk>null</jk> only 268 * when {@link Builder#skipResourceValidation(boolean)} is set. 269 * @return The parsed metadata. 270 * @throws McpAuthException If the document cannot be parsed, is missing the required {@code resource} field, or 271 * fails the resource identity check. 272 */ 273 public McpProtectedResourceMetadata parse(String json, URI source, URI expectedResource) { 274 reqnn("json", json); 275 JSONObject o; 276 try { 277 o = JSONObjectUtils.parse(json); 278 } catch (ParseException e) { 279 throw new McpAuthException("Protected-resource-metadata document could not be parsed for " + source, e); 280 } 281 McpProtectedResourceMetadata prm; 282 try { 283 var resource = JSONObjectUtils.getURI(o, "resource"); 284 var authServers = new ArrayList<URI>(); 285 if (o.containsKey("authorization_servers")) 286 for (var v : JSONObjectUtils.getStringList(o, "authorization_servers")) 287 authServers.add(URI.create(v)); 288 var scopes = new LinkedHashSet<String>(); 289 if (o.containsKey("scopes_supported")) 290 scopes.addAll(JSONObjectUtils.getStringList(o, "scopes_supported")); 291 var extras = new LinkedHashMap<String,Object>(); 292 for (var e : o.entrySet()) 293 if (!STANDARD_FIELDS.contains(e.getKey())) 294 extras.put(e.getKey(), e.getValue()); 295 prm = new McpProtectedResourceMetadata(resource, authServers, scopes, extras); 296 } catch (ParseException | IllegalArgumentException e) { 297 throw new McpAuthException("Protected-resource-metadata document was malformed for " + source, e); 298 } 299 validateResourceIdentity(prm, expectedResource); 300 return prm; 301 } 302 303 /** 304 * Selects the first authorization server from the PRM document and validates its issuer identity via RFC 8414 / 305 * OIDC discovery. 306 * 307 * @param prm The parsed PRM document. Must not be <jk>null</jk>. 308 * @return The discovered authorization-server metadata (issuer validated). 309 * @throws McpAuthException If no authorization server is advertised or discovery/issuer validation fails. 310 */ 311 public OidcMetadata discoverAuthorizationServer(McpProtectedResourceMetadata prm) { 312 reqnn("prm", prm); 313 var as = prm.firstAuthorizationServer() 314 .orElseThrow(() -> new McpAuthException("Protected-resource-metadata for " + prm.resource() + " advertised no authorization_servers")); 315 requireSecure(as, "Authorization-server URL"); 316 try { 317 var md = OidcDiscoveryClient.create() 318 .issuer(as) 319 .httpTimeout(httpTimeout) 320 .httpRequestConfigurator(httpRequestConfigurator == null ? h -> {} : httpRequestConfigurator) 321 .build() 322 .discover(); 323 requireSecure(md.tokenEndpoint(), "Token endpoint"); 324 requireSecure(md.authorizationEndpoint(), "Authorization endpoint"); 325 var reg = md.extras().get("registration_endpoint"); 326 if (reg != null) 327 requireSecure(URI.create(reg.toString()), "Registration endpoint"); 328 return md; 329 } catch (IOException | OidcDiscoveryException e) { 330 throw new McpAuthException("Authorization-server discovery/issuer validation failed for " + as, e); 331 } 332 } 333 334 /** 335 * Validates the PRM {@code resource} field against the expected resource identifier (RFC 9728 §3.3), using a 336 * normalization-free exact string comparison to match the issuer-identity posture. 337 */ 338 private void validateResourceIdentity(McpProtectedResourceMetadata prm, URI expectedResource) { 339 if (expectedResource == null) { 340 if (skipResourceValidation) 341 return; 342 throw new McpAuthException("Protected-resource-metadata validation requires an expected resource identifier (RFC 9728 3.3); call expectedResource(...)"); 343 } 344 if (!expectedResource.toString().equals(prm.resource().toString())) 345 throw new McpAuthException("Protected-resource-metadata resource identity mismatch (RFC 9728 3.3): expected '" 346 + expectedResource + "' but document declared '" + prm.resource() + "'"); 347 } 348 349 private void requireSecure(URI uri, String what) { 350 if (uri == null) 351 return; 352 try { 353 RemoteUrlPolicy.requireAllowedUrl(uri.toString(), allowPrivateUrls); 354 } catch (IllegalArgumentException e) { 355 throw new McpAuthException(what + " is not permitted (was '" + uri + "'): " + e.getMessage(), e); 356 } 357 if (allowInsecureHttp || eqic("https", uri.getScheme()) || (allowPrivateUrls && isLoopback(uri))) 358 return; 359 throw new McpAuthException(what + " must use https (was '" + uri + "'); enable allowInsecureHttp for non-loopback http"); 360 } 361 362 private static boolean isLoopback(URI uri) { 363 var host = uri.getHost(); 364 if (host == null) 365 return false; 366 return eqic("localhost", host) || eqa(host, "127.0.0.1", "[::1]", "::1"); 367 } 368 369 private static final Set<String> STANDARD_FIELDS = Set.of( 370 "resource", "authorization_servers", "scopes_supported" 371 ); 372}