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.io.*;
022import java.net.*;
023import java.util.*;
024import java.util.stream.*;
025
026/**
027 * A parsed {@code WWW-Authenticate: Bearer ...} challenge as returned by an OAuth 2.1 / MCP resource server on a
028 * {@code 401}/{@code 403} response (RFC 6750 §3, RFC 9728 §5.1).
029 *
030 * <p>
031 * The MCP client uses this to recover the {@code resource_metadata} pointer to the RFC 9728 PRM document, the
032 * per-operation {@code scope} on a step-up challenge, and the {@code error} code.  Auth-param values are matched
033 * case-insensitively on the key per RFC 7235.
034 *
035 * <p>
036 * {@link Serializable} (it is just a scheme string plus an immutable string map) so it can ride along a serialized
037 * {@link McpInsufficientScopeException} without being dropped.
038 *
039 * @since 10.0.0
040 */
041public class WwwAuthenticateChallenge implements Serializable {
042
043   private static final long serialVersionUID = 1L;
044
045   /** Longest header value that will be parsed; longer values are treated as not a challenge. */
046   static final int MAX_HEADER_LENGTH = 8192;
047
048   /** Most parameters read from one challenge; the rest are ignored. */
049   static final int MAX_PARAMETERS = 32;
050
051   private final String scheme;
052   private final Map<String,String> parameters;
053
054   /**
055    * Constructor.
056    *
057    * @param scheme The auth scheme (e.g. {@code "Bearer"}).  Must not be <jk>null</jk> or blank.
058    * @param parameters The auth-params (lower-cased keys).  Must not be <jk>null</jk>.
059    */
060   protected WwwAuthenticateChallenge(String scheme, Map<String,String> parameters) {
061      this.scheme = reqnb("scheme", scheme);
062      this.parameters = u(cp(reqnn("parameters", parameters)));
063   }
064
065   /**
066    * Parses a single {@code WWW-Authenticate} header value.
067    *
068    * <p>
069    * Recognizes a single challenge of the form {@code <scheme> <key>=<value>, <key>="<value>", ...}.  Both quoted
070    * and bare token values are accepted; commas inside quoted values are preserved.
071    *
072    * @param headerValue The raw header value.  May be <jk>null</jk> or blank.
073    * @return The parsed challenge, or {@link Optional#empty()} if the value is null/blank or has no scheme token.
074    */
075   public static Optional<WwwAuthenticateChallenge> parse(String headerValue) {
076      if (headerValue == null)
077         return oe();
078      var s = headerValue.strip();
079      if (s.isEmpty() || s.length() > MAX_HEADER_LENGTH)
080         return oe();
081      var sp = s.indexOf(' ');
082      if (sp < 0)
083         return o(new WwwAuthenticateChallenge(s, Map.of()));
084      var scheme = s.substring(0, sp);
085      var rest = s.substring(sp + 1).strip();
086      return o(new WwwAuthenticateChallenge(scheme, parseParams(rest)));
087   }
088
089   private static Map<String,String> parseParams(String s) {
090      var out = new LinkedHashMap<String,String>();
091      var n = s.length();
092      var i = 0;
093      while ((i = skipSeparators(s, i, n)) < n) {
094         var param = parseParam(s, i, n);
095         i = param.nextIndex();
096         if (out.size() >= MAX_PARAMETERS)
097            break;
098         if (param.key() != null && !param.key().isEmpty())
099            out.putIfAbsent(param.key(), param.value());
100      }
101      return out;
102   }
103
104   /** Advances past whitespace and separator commas, returning the index of the next non-separator char (or {@code n}). */
105   private static int skipSeparators(String s, int i, int n) {
106      while (i < n && (Character.isWhitespace(s.charAt(i)) || s.charAt(i) == ','))
107         i++;
108      return i;
109   }
110
111   /**
112    * Parses a single {@code key=value} auth-param starting at {@code i} (which must not point at a separator).
113    *
114    * <p>
115    * Returns a {@code null} key when {@code i} points at a bare token with no {@code =value} (e.g. {@code token68});
116    * the caller skips such a param.  {@code nextIndex()} always advances past the scanned key (and value, if any),
117    * so the outer loop makes forward progress without a {@code break}/{@code continue}.
118    */
119   private static ParsedParam parseParam(String s, int i, int n) {
120      var keyStart = i;
121      while (i < n && s.charAt(i) != '=' && s.charAt(i) != ',')
122         i++;
123      if (i >= n || s.charAt(i) == ',')
124         return new ParsedParam(null, null, i);
125      var key = s.substring(keyStart, i).strip().toLowerCase(Locale.ROOT);
126      i++; // consume '='
127      var value = parseValue(s, i, n);
128      return new ParsedParam(key, value.value(), value.nextIndex());
129   }
130
131   /** Parses a quoted-string or bare-token auth-param value starting at {@code i}. */
132   private static ParsedValue parseValue(String s, int i, int n) {
133      if (i < n && s.charAt(i) == '"')
134         return parseQuotedValue(s, i, n);
135      var valStart = i;
136      while (i < n && s.charAt(i) != ',')
137         i++;
138      return new ParsedValue(s.substring(valStart, i).strip(), i);
139   }
140
141   /** Parses a quoted-string value starting at the opening-quote index {@code i}, honoring {@code \}-escaped chars. */
142   private static ParsedValue parseQuotedValue(String s, int i, int n) {
143      i++; // consume opening quote
144      var sb = new StringBuilder();
145      while (i < n && s.charAt(i) != '"') {
146         if (s.charAt(i) == '\\' && i + 1 < n) // handle escaped chars inside quoted-string
147            i++;
148         sb.append(s.charAt(i));
149         i++;
150      }
151      if (i < n)
152         i++; // consume closing quote
153      return new ParsedValue(sb.toString(), i);
154   }
155
156   /** A parsed auth-param; {@code key} is {@code null} for a skipped bare token with no value. */
157   private record ParsedParam(String key, String value, int nextIndex) {}
158
159   /** A parsed auth-param value and the index immediately following it. */
160   private record ParsedValue(String value, int nextIndex) {}
161
162   /**
163    * Returns the auth scheme.
164    *
165    * @return The scheme (e.g. {@code "Bearer"}).  Never {@code null}.
166    */
167   public String scheme() {
168      return scheme;
169   }
170
171   /**
172    * Returns whether the scheme is {@code Bearer} (case-insensitive).
173    *
174    * @return <jk>true</jk> if this is a Bearer challenge.
175    */
176   public boolean isBearer() {
177      return eqic("bearer", scheme);
178   }
179
180   /**
181    * Returns the parsed auth-params (lower-cased keys).
182    *
183    * @return An unmodifiable map.  Never {@code null}.
184    */
185   public Map<String,String> parameters() {
186      return parameters;
187   }
188
189   /**
190    * Returns the raw value of an auth-param.
191    *
192    * @param name The param name (matched case-insensitively).  Must not be <jk>null</jk>.
193    * @return The value, or {@link Optional#empty()} if absent.
194    */
195   public Optional<String> parameter(String name) {
196      reqnn("name", name);
197      return o(parameters.get(name.toLowerCase(Locale.ROOT)));
198   }
199
200   /**
201    * Returns the {@code resource_metadata} pointer (RFC 9728 &sect;5.1) to the PRM document.
202    *
203    * @return The PRM document URI, or {@link Optional#empty()} if absent or unparseable as a URI.
204    */
205   public Optional<URI> resourceMetadata() {
206      var v = parameters.get("resource_metadata");
207      if (ib(v))
208         return oe();
209      try {
210         return o(URI.create(v));
211      } catch (IllegalArgumentException e) {
212         return oe();
213      }
214   }
215
216   /**
217    * Returns the {@code error} code (e.g. {@code "insufficient_scope"}), if present.
218    *
219    * @return The error code, or {@link Optional#empty()}.
220    */
221   public Optional<String> error() {
222      var v = parameters.get("error");
223      return o(v != null && KNOWN_ERRORS.contains(v) ? v : null);
224   }
225
226   private static final Set<String> KNOWN_ERRORS = Set.of(
227      "invalid_request", "invalid_token", "insufficient_scope");
228
229   /**
230    * Returns the space-delimited {@code scope} param as an order-preserving set.
231    *
232    * @return The challenged scopes (empty if the param is absent or blank).  Never {@code null}.
233    */
234   public Set<String> scopes() {
235      var v = parameters.get("scope");
236      if (ib(v))
237         return Set.of();
238      var out = Arrays.stream(v.strip().split("\\s+"))
239         .collect(Collectors.toCollection(LinkedHashSet<String>::new));
240      return u(out);
241   }
242}