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.util.*; 023import java.util.concurrent.*; 024 025/** 026 * Client-side SEP-2350 step-up state machine: wraps an MCP call so that, on a {@code 401}/{@code 403 insufficient_scope} 027 * challenge, it computes the required-scope union ({@link McpScopeAccumulator}), drives (re-)authorization via a 028 * caller-supplied {@link Reauthorizer}, and retries the original call — bounded by a hard attempt cap with 029 * per-<code>(resource, operation)</code> attempt tracking so a misconfigured server can't drive an unbounded 030 * re-authorization loop (spec "no more than a few times"). 031 * 032 * <p> 033 * Step-up for user-delegation clients is inherently interactive (a fresh auth-code + PKCE round-trip), so this is an 034 * <b>explicit orchestration helper</b> the caller wraps around MCP calls — not a silent interceptor retry. The 035 * caller's {@link ScopedCall} performs the actual MCP request and throws {@link McpInsufficientScopeException} (carrying 036 * the parsed {@link WwwAuthenticateChallenge}) when the server responds with a step-up challenge; the 037 * {@link Reauthorizer} performs the (re-)authorization with the widened scope union (e.g. via 038 * {@link McpAuthorizationCodeAcquirer} for user clients or a client-credentials re-acquire) and installs the new token. 039 * 040 * <p> 041 * {@code client_credentials} (own-behalf) clients MAY abort immediately rather than attempt step-up 042 * ({@link Builder#attemptStepUp(boolean) attemptStepUp(false)}). 043 * 044 * <h2 class='topic'>Attempt-counter lifetime</h2> 045 * <p> 046 * Per-<code>(resource, operation)</code> attempt counts exist only to bound a single step-up burst. A counter is 047 * <b>cleared automatically</b> when {@link #execute(String, ScopedCall) execute} returns successfully for that operation, 048 * so a long-lived authorizer does not permanently refuse a later legitimate step-up for the same operation. A counter 049 * that reaches the cap without a success (a permanent failure) is <b>not</b> auto-cleared — the caller can reset it 050 * explicitly with {@link #reset(String)} (one operation) or {@link #resetAll()} (all operations) once the underlying 051 * cause is resolved. 052 * 053 * @since 10.0.0 054 */ 055@SuppressWarnings({ 056 "java:S1192" // Duplicated literals (argument/property names) read more clearly inline than as constants 057}) 058public class McpStepUpAuthorizer { 059 060 /** Default cap on the number of scopes in the accumulated step-up union. */ 061 public static final int DEFAULT_MAX_SCOPES = 32; 062 063 /** A caller-supplied MCP call that throws {@link McpInsufficientScopeException} on a step-up challenge. */ 064 @FunctionalInterface 065 public interface ScopedCall<T> { 066 /** 067 * Performs the MCP call. 068 * 069 * @return The call result. 070 * @throws McpInsufficientScopeException If the server responded with a step-up {@code insufficient_scope} challenge. 071 */ 072 T call() throws McpInsufficientScopeException; 073 } 074 075 /** Drives (re-)authorization with the computed scope union and installs the resulting token. */ 076 @FunctionalInterface 077 public interface Reauthorizer { 078 /** 079 * Performs (re-)authorization with the widened scope union. 080 * 081 * @param unionScopes The order-preserving union of previously-requested + challenge scopes. 082 */ 083 void reauthorize(Set<String> unionScopes); 084 } 085 086 /** 087 * Static creator. 088 * 089 * @return A new builder. 090 */ 091 public static Builder create() { 092 return new Builder(); 093 } 094 095 /** 096 * Builder. 097 */ 098 public static class Builder { 099 URI resource; 100 URI issuer; 101 McpScopeAccumulator accumulator; 102 Reauthorizer reauthorizer; 103 int maxAttempts = 3; 104 boolean attemptStepUp = true; 105 int maxScopes = DEFAULT_MAX_SCOPES; 106 Set<String> allowedScopes; 107 final Set<String> previouslyRequestedScopes = st(); 108 109 /** Constructor. */ 110 protected Builder() {} 111 112 /** 113 * Sets the RFC 8707 resource indicator this authorizer tracks attempts for. Required. 114 * 115 * @param value The resource URI. 116 * @return This object. 117 */ 118 public Builder resource(URI value) { 119 resource = reqnn("value", value); 120 return this; 121 } 122 123 /** 124 * Sets the authorization server issuer. Required. 125 * 126 * @param value The issuer URI. 127 * @return This object. 128 */ 129 public Builder issuer(URI value) { 130 issuer = reqnn("value", value); 131 return this; 132 } 133 134 /** 135 * Sets the scope accumulator. Defaults to a fresh {@link McpScopeAccumulator}. 136 * 137 * @param value The accumulator. Must not be <jk>null</jk>. 138 * @return This object. 139 */ 140 public Builder accumulator(McpScopeAccumulator value) { 141 accumulator = reqnn("value", value); 142 return this; 143 } 144 145 /** 146 * Sets the re-authorization callback invoked with the widened scope union. Required. 147 * 148 * @param value The reauthorizer. Must not be <jk>null</jk>. 149 * @return This object. 150 */ 151 public Builder reauthorizer(Reauthorizer value) { 152 reauthorizer = reqnn("value", value); 153 return this; 154 } 155 156 /** 157 * Sets the hard cap on re-authorization attempts per {@code (resource, operation)} before a permanent failure. 158 * Default 3. 159 * 160 * @param value The maximum attempts. Must be ≥ 1. 161 * @return This object. 162 */ 163 public Builder maxAttempts(int value) { 164 req(value >= 1, "maxAttempts must be >= 1 (was %s)", value); 165 maxAttempts = value; 166 return this; 167 } 168 169 /** 170 * Whether to attempt step-up at all. Default <jk>true</jk>; a {@code client_credentials} client MAY set 171 * <jk>false</jk> to abort immediately on the first challenge. 172 * 173 * @param value <jk>false</jk> to abort immediately rather than attempt step-up. 174 * @return This object. 175 */ 176 public Builder attemptStepUp(boolean value) { 177 attemptStepUp = value; 178 return this; 179 } 180 181 /** 182 * Restricts the scopes a server challenge may add to the step-up union. 183 * 184 * <p> 185 * When set, a challenge naming any scope outside this set (and outside the previously-requested scopes) aborts 186 * the step-up with an {@link McpAuthException} instead of re-authorizing. When unset, only the 187 * {@link #maxScopes(int) scope-count cap} applies. 188 * 189 * @param values The permitted scopes. Must not be <jk>null</jk>. 190 * @return This object. 191 */ 192 public Builder allowedScopes(String... values) { 193 reqnn("values", values); 194 var set = new LinkedHashSet<String>(); 195 for (var v : values) 196 set.add(reqnb("scope", v)); 197 allowedScopes = set; 198 return this; 199 } 200 201 /** 202 * Caps the number of scopes the accumulated step-up union may contain. 203 * 204 * @param value The cap. Must be >= 1. Defaults to {@value McpStepUpAuthorizer#DEFAULT_MAX_SCOPES}. 205 * @return This object. 206 */ 207 public Builder maxScopes(int value) { 208 req(value >= 1, "maxScopes must be >= 1 (was %s)", value); 209 maxScopes = value; 210 return this; 211 } 212 213 /** 214 * Seeds the scope accumulator with the client's previously-requested scopes so the first union preserves them. 215 * 216 * @param values The previously-requested scopes. 217 * @return This object. 218 */ 219 public Builder previouslyRequestedScopes(String... values) { 220 reqnn("values", values); 221 for (var v : values) { 222 reqnb("scope", v); 223 previouslyRequestedScopes.add(v); 224 } 225 return this; 226 } 227 228 /** 229 * Builds the authorizer. 230 * 231 * @return A new {@link McpStepUpAuthorizer}. 232 */ 233 public McpStepUpAuthorizer build() { 234 if (resource == null) 235 throw isex("McpStepUpAuthorizer requires resource(...)"); 236 if (issuer == null) 237 throw isex("McpStepUpAuthorizer requires issuer(...)"); 238 if (reauthorizer == null) 239 throw isex("McpStepUpAuthorizer requires reauthorizer(...)"); 240 if (accumulator == null) 241 accumulator = new McpScopeAccumulator(); 242 if (! previouslyRequestedScopes.isEmpty()) 243 accumulator.seed(resource, issuer, previouslyRequestedScopes); 244 return new McpStepUpAuthorizer(this); 245 } 246 } 247 248 private final URI resource; 249 private final URI issuer; 250 private final McpScopeAccumulator accumulator; 251 private final Reauthorizer reauthorizer; 252 private final int maxAttempts; 253 private final boolean attemptStepUp; 254 private final int maxScopes; 255 private final Set<String> allowedScopes; 256 private final ConcurrentMap<String,Integer> attemptsByOperation = new ConcurrentHashMap<>(); 257 258 /** 259 * Constructor. 260 * 261 * @param b The builder. 262 */ 263 protected McpStepUpAuthorizer(Builder b) { 264 this.resource = b.resource; 265 this.issuer = b.issuer; 266 this.accumulator = b.accumulator; 267 this.reauthorizer = b.reauthorizer; 268 this.maxAttempts = b.maxAttempts; 269 this.attemptStepUp = b.attemptStepUp; 270 this.maxScopes = b.maxScopes; 271 this.allowedScopes = b.allowedScopes == null ? null : Set.copyOf(b.allowedScopes); 272 } 273 274 /** 275 * Executes an MCP call, transparently handling SEP-2350 step-up: on an {@code insufficient_scope} challenge it 276 * unions the challenge scopes onto the accumulated set, re-authorizes, and retries — up to the configured 277 * attempt cap, after which it throws a permanent {@link McpAuthException}. 278 * 279 * @param <T> The call result type. 280 * @param operation The operation identifier (e.g. {@code tools/call:deploy}) used for per-operation attempt 281 * tracking. Must not be <jk>null</jk> or blank. 282 * @param call The MCP call. Must not be <jk>null</jk>. 283 * @return The successful call result. 284 * @throws McpAuthException If step-up is disabled, or the attempt cap is exceeded (permanent authorization failure). 285 */ 286 @SuppressWarnings({ 287 "java:S3776" // Branching is inherent to the step-up retry loop. 288 }) 289 public <T> T execute(String operation, ScopedCall<T> call) { 290 reqnb("operation", operation); 291 reqnn("call", call); 292 var opKey = opKey(operation); 293 while (true) { 294 try { 295 var result = call.call(); 296 // Success clears the operation's attempt burst so a later legitimate step-up starts fresh. 297 attemptsByOperation.remove(opKey); 298 return result; 299 } catch (McpInsufficientScopeException e) { 300 if (! attemptStepUp) 301 throw new McpAuthException("Step-up authorization aborted for operation '" + operation 302 + "' (attemptStepUp=false)", e); 303 var used = attemptsByOperation.merge(opKey, 1, Integer::sum); 304 if (used > maxAttempts) 305 throw new McpAuthException("Step-up authorization exhausted after " + maxAttempts 306 + " attempt(s) for resource '" + resource + "' operation '" + operation 307 + "'; treating as a permanent authorization failure", e); 308 var requested = e.challenge().scopes(); 309 if (allowedScopes != null && requested != null) { 310 var known = accumulator.current(resource, issuer); 311 for (var sc : requested) 312 if (! allowedScopes.contains(sc) && ! known.contains(sc)) 313 throw new McpAuthException("Step-up authorization refused for operation '" + operation 314 + "': the server requested a scope outside the configured allow-list", e); 315 } 316 // Check the cap before accumulating so a refused challenge leaves the stored scope set untouched. 317 if (McpScopeAccumulator.union(accumulator.current(resource, issuer), requested).size() > maxScopes) 318 throw new McpAuthException("Step-up authorization refused for operation '" + operation 319 + "': the requested scope set exceeds the maximum of " + maxScopes, e); 320 var union = accumulator.accumulate(resource, issuer, requested); 321 reauthorizer.reauthorize(union); 322 } 323 } 324 } 325 326 /** 327 * Returns the number of step-up attempts recorded for the given operation. 328 * 329 * @param operation The operation identifier. Must not be <jk>null</jk> or blank. 330 * @return The recorded attempt count. 331 */ 332 public int attempts(String operation) { 333 reqnb("operation", operation); 334 return attemptsByOperation.getOrDefault(opKey(operation), 0); 335 } 336 337 /** 338 * Clears the recorded step-up attempt count for a single operation (e.g. after the caller has resolved the cause of 339 * a prior permanent failure), so a subsequent {@link #execute(String, ScopedCall)} may step up again. 340 * 341 * @param operation The operation identifier. Must not be <jk>null</jk> or blank. 342 */ 343 public void reset(String operation) { 344 reqnb("operation", operation); 345 attemptsByOperation.remove(opKey(operation)); 346 } 347 348 /** 349 * Clears all recorded step-up attempt counts for this authorizer's resource across every operation. 350 */ 351 public void resetAll() { 352 attemptsByOperation.clear(); 353 } 354 355 /** The per-operation attempt-tracking key: {@code resource + '\n' + operation}. */ 356 private String opKey(String operation) { 357 return resource.toString() + '\n' + operation; 358 } 359}