001/* 002 * Copyright 2026 Revetware LLC. 003 * 004 * Licensed under the Apache License, Version 2.0 (the "License"); 005 * you may not use this file except in compliance with the License. 006 * You may obtain a copy of the License at 007 * 008 * http://www.apache.org/licenses/LICENSE-2.0 009 * 010 * Unless required by applicable law or agreed to in writing, software 011 * distributed under the License is distributed on an "AS IS" BASIS, 012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 013 * See the License for the specific language governing permissions and 014 * limitations under the License. 015 */ 016 017package com.revetsec.oauth; 018 019import com.google.errorprone.annotations.CheckReturnValue; 020import com.revetsec.internal.Limits; 021import com.revetsec.internal.http.MediaType; 022import com.revetsec.internal.encoding.EncodingException; 023import com.revetsec.internal.encoding.QueryParameters; 024import com.revetsec.internal.encoding.StrictUtf8; 025import org.jspecify.annotations.NonNull; 026import org.jspecify.annotations.Nullable; 027 028import javax.annotation.concurrent.Immutable; 029import java.net.URI; 030import java.nio.charset.Charset; 031import java.nio.charset.StandardCharsets; 032import java.util.ArrayList; 033import java.util.Arrays; 034import java.util.Collections; 035import java.util.LinkedHashMap; 036import java.util.List; 037import java.util.Map; 038import java.util.Optional; 039import java.util.Set; 040 041import static java.util.Objects.requireNonNull; 042 043/** 044 * A parsed browser authorization response. It preserves repeated parameters so a duplicate cannot be silently 045 * selected. Its delivery mode comes from the application route and method, never from callback data. Parsing does 046 * not authenticate the response; {@link OAuthClient} checks its pending state before trusting any error or code. 047 * 048 * @author <a href="https://www.revetkn.com">Mark Allen</a> 049 * @since 1.0.0 050 */ 051@Immutable 052public final class AuthorizationResponse { 053 private static final Set<String> SINGLETONS = Set.of("code", "state", "iss", "error", 054 "error_description", "error_uri"); 055 private final @NonNull Map<@NonNull String, @NonNull List<@NonNull String>> parameters; 056 private final AuthorizationRequestOptions.@NonNull ResponseMode responseMode; 057 private final @Nullable URI errorUri; 058 059 private AuthorizationResponse(@NonNull Map<@NonNull String, @NonNull List<@NonNull String>> values, 060 AuthorizationRequestOptions.@NonNull ResponseMode responseMode, @Nullable URI errorUri) { 061 this.parameters = values; 062 this.responseMode = responseMode; 063 this.errorUri = errorUri; 064 } 065 066 /** 067 * Parses a raw URL query, without the question mark, keeping malformed input as a rejected result. 068 * A successful parse grants no identity and does not validate the pending authorization transaction. 069 * 070 * @param rawQuery the raw query 071 * @return the unverified callback or a fixed rejection reason 072 * @throws NullPointerException if rawQuery is null 073 * @since 1.0.0 074 */ 075 @CheckReturnValue 076 public static @NonNull AuthorizationResponseParseResult fromQueryStringResult(@NonNull String rawQuery) { 077 try { 078 return AuthorizationResponseParseResult.fromResponse(fromQueryString(rawQuery)); 079 } catch (OAuthResponseException exception) { 080 return AuthorizationResponseParseResult.fromRejected(); 081 } 082 } 083 084 /** 085 * Parses a UTF-8 form-post body. Protocol members in the query reject split-channel responses; safe nonprotocol 086 * query parameters remain untrusted extras. Invalid charset, encoding, size or parameters produce rejection. 087 * 088 * @param body the form bytes 089 * @param charset the application's parsed Content-Type charset, which must be UTF-8 090 * @param rawQueryOrNull the URL's raw query, if any 091 * @return the unverified callback or a fixed rejection reason 092 * @throws NullPointerException if body or charset is null 093 * @since 1.0.0 094 */ 095 @CheckReturnValue 096 public static @NonNull AuthorizationResponseParseResult fromFormBodyResult(byte @NonNull [] body, 097 @NonNull Charset charset, @Nullable String rawQueryOrNull) { 098 try { 099 return AuthorizationResponseParseResult.fromResponse(fromFormBody(body, charset, rawQueryOrNull)); 100 } catch (OAuthResponseException exception) { 101 return AuthorizationResponseParseResult.fromRejected(); 102 } 103 } 104 105 /** 106 * Parses a form-post callback after validating every raw Content-Type occurrence. Requires exactly one form 107 * field with an absent or UTF-8 charset and no duplicate MIME parameters. The field is capped at 8,192 108 * characters before MIME parsing. Preserve materialized duplicates; a trusted edge rejects physical fields 109 * discarded by a transport. Invalid MIME, body, duplicate parameters and split channels produce rejection. 110 * 111 * @param body the raw form bytes 112 * @param contentTypeHeaderValues all materialized Content-Type values 113 * @param rawQueryOrNull the raw URL query, if any 114 * @return the unverified callback or a fixed rejection reason 115 * @throws NullPointerException if body, header list or its sole field is null 116 * @since 1.0.0 117 */ 118 @CheckReturnValue 119 public static @NonNull AuthorizationResponseParseResult fromFormBodyResult(byte @NonNull [] body, 120 @NonNull List<@NonNull String> contentTypeHeaderValues, @Nullable String rawQueryOrNull) { 121 try { 122 return AuthorizationResponseParseResult.fromResponse(fromFormBody(body, contentTypeHeaderValues, rawQueryOrNull)); 123 } catch (OAuthResponseException exception) { 124 return AuthorizationResponseParseResult.fromRejected(); 125 } 126 } 127 128 /** 129 * Accepts parameters from an application parser, retaining multiplicity and the explicit route mode. 130 * Malformed, duplicate, oversized or split-channel parameters produce rejection. Success remains unverified. 131 * 132 * @param values decoded parameters, with all values for each name 133 * @param rawQueryOrNull the URL query when the mode is form-post, if any 134 * @param responseMode mode established by trusted application routing 135 * @return the unverified callback or a fixed rejection reason 136 * @throws NullPointerException if values, a parameter name/list/value or responseMode is null 137 * @since 1.0.0 138 */ 139 @CheckReturnValue 140 public static @NonNull AuthorizationResponseParseResult fromParametersResult( 141 @NonNull Map<@NonNull String, @NonNull List<@NonNull String>> values, 142 @Nullable String rawQueryOrNull, AuthorizationRequestOptions.@NonNull ResponseMode responseMode) { 143 try { 144 return AuthorizationResponseParseResult.fromResponse(fromParameters(values, rawQueryOrNull, responseMode)); 145 } catch (OAuthResponseException exception) { 146 return AuthorizationResponseParseResult.fromRejected(); 147 } 148 } 149 150 private static @NonNull AuthorizationResponse fromQueryString(@NonNull String rawQuery) { 151 return fromEncoded(rawQuery, AuthorizationRequestOptions.ResponseMode.QUERY); 152 } 153 154 private static @NonNull AuthorizationResponse fromFormBody(byte @NonNull [] body, @NonNull Charset charset, 155 @Nullable String rawQueryOrNull) { 156 requireNonNull(body); 157 if (!StandardCharsets.UTF_8.equals(requireNonNull(charset))) 158 throw OAuthResponseException.fromReason(OAuthException.Reason.CALLBACK_MALFORMED); 159 if (body.length > Limits.AUTHORIZATION_RESPONSE_QUERY_SIZE.getDefaultIntValue()) 160 throw OAuthResponseException.fromReason(OAuthException.Reason.CALLBACK_MALFORMED); 161 try { 162 return fromParameters(QueryParameters.parse(StrictUtf8.decode(body)).getValuesByName(), rawQueryOrNull, 163 AuthorizationRequestOptions.ResponseMode.FORM_POST); 164 } catch (EncodingException exception) { 165 throw OAuthResponseException.fromReason(OAuthException.Reason.CALLBACK_MALFORMED); 166 } 167 } 168 169 private static @NonNull AuthorizationResponse fromFormBody(byte @NonNull [] body, 170 @NonNull List<@NonNull String> contentTypeHeaderValues, @Nullable String rawQueryOrNull) { 171 requireNonNull(body); 172 requireNonNull(contentTypeHeaderValues); 173 if (contentTypeHeaderValues.size() != 1) 174 throw OAuthResponseException.fromReason(OAuthException.Reason.CALLBACK_MALFORMED); 175 String field = requireNonNull(contentTypeHeaderValues.get(0)); 176 if (field.length() > Limits.AUTHORIZATION_RESPONSE_PARAMETER_SIZE.getDefaultIntValue()) 177 throw OAuthResponseException.fromReason(OAuthException.Reason.CALLBACK_MALFORMED); 178 MediaType type = MediaType.parse(field).orElseThrow(() -> 179 OAuthResponseException.fromReason(OAuthException.Reason.CALLBACK_MALFORMED)); 180 if (!type.getEssence().equals("application/x-www-form-urlencoded") || !type.hasUtf8OrNoCharset()) 181 throw OAuthResponseException.fromReason(OAuthException.Reason.CALLBACK_MALFORMED); 182 return fromFormBody(body, StandardCharsets.UTF_8, rawQueryOrNull); 183 } 184 185 private static @NonNull AuthorizationResponse fromParameters( 186 @NonNull Map<@NonNull String, @NonNull List<@NonNull String>> values, 187 @Nullable String rawQueryOrNull, AuthorizationRequestOptions.@NonNull ResponseMode responseMode) { 188 requireNonNull(values); 189 requireNonNull(responseMode); 190 Map<String, List<String>> copy = new LinkedHashMap<>(); 191 int maximumQuerySize = Limits.AUTHORIZATION_RESPONSE_QUERY_SIZE.getDefaultIntValue(); 192 int maximumParameterSize = Limits.AUTHORIZATION_RESPONSE_PARAMETER_SIZE.getDefaultIntValue(); 193 if (values.size() > maximumQuerySize) 194 throw OAuthResponseException.fromReason(OAuthException.Reason.CALLBACK_MALFORMED); 195 long aggregate = 0; 196 long parameterCount = 0; 197 for (Map.Entry<String, List<String>> entry : values.entrySet()) { 198 String name = requireNonNull(entry.getKey()); 199 List<String> supplied = requireNonNull(entry.getValue()); 200 if (supplied.size() > maximumQuerySize - parameterCount || name.length() > maximumParameterSize) 201 throw OAuthResponseException.fromReason(OAuthException.Reason.CALLBACK_MALFORMED); 202 parameterCount += supplied.size(); 203 if (SINGLETONS.contains(name) && supplied.size() > 1) 204 throw OAuthResponseException.fromReason(OAuthException.Reason.CALLBACK_MALFORMED); 205 List<String> list = new ArrayList<>(supplied.size()); 206 for (String value : supplied) { 207 requireNonNull(value); 208 if ((long) name.length() + value.length() > maximumParameterSize) 209 throw OAuthResponseException.fromReason(OAuthException.Reason.CALLBACK_MALFORMED); 210 long size = (long) utf8Length(name) + utf8Length(value); 211 if (size > maximumParameterSize || size > maximumQuerySize - aggregate) 212 throw OAuthResponseException.fromReason(OAuthException.Reason.CALLBACK_MALFORMED); 213 aggregate += size; 214 list.add(value); 215 } 216 copy.put(name, List.copyOf(list)); 217 } 218 if (rawQueryOrNull != null && responseMode == AuthorizationRequestOptions.ResponseMode.FORM_POST) { 219 Map<String, List<String>> query = parseEncoded(rawQueryOrNull); 220 for (Map.Entry<String, List<String>> entry : query.entrySet()) { 221 if (entry.getValue().size() > maximumQuerySize - parameterCount) 222 throw OAuthResponseException.fromReason(OAuthException.Reason.CALLBACK_MALFORMED); 223 parameterCount += entry.getValue().size(); 224 if (SINGLETONS.contains(entry.getKey())) 225 throw OAuthResponseException.fromReason(OAuthException.Reason.CALLBACK_MALFORMED); 226 if (copy.containsKey(entry.getKey())) 227 throw OAuthResponseException.fromReason(OAuthException.Reason.CALLBACK_MALFORMED); 228 copy.put(entry.getKey(), entry.getValue()); 229 for (String value : entry.getValue()) 230 aggregate += utf8Length(entry.getKey()) + utf8Length(value); 231 } 232 } 233 if (aggregate > Limits.AUTHORIZATION_RESPONSE_QUERY_SIZE.getDefaultIntValue() 234 || (copy.containsKey("code") && copy.containsKey("error"))) 235 throw OAuthResponseException.fromReason(OAuthException.Reason.CALLBACK_MALFORMED); 236 return new AuthorizationResponse(Collections.unmodifiableMap(copy), responseMode, parseErrorUri(copy)); 237 } 238 239 private static @NonNull AuthorizationResponse fromEncoded(@NonNull String encoded, 240 AuthorizationRequestOptions.@NonNull ResponseMode responseMode) { 241 return fromParameters(parseEncoded(encoded), null, responseMode); 242 } 243 244 private static @NonNull Map<@NonNull String, @NonNull List<@NonNull String>> parseEncoded(@NonNull String encoded) { 245 requireNonNull(encoded); 246 if (utf8Length(encoded) > Limits.AUTHORIZATION_RESPONSE_QUERY_SIZE.getDefaultIntValue()) 247 throw OAuthResponseException.fromReason(OAuthException.Reason.CALLBACK_MALFORMED); 248 try { 249 return QueryParameters.parse(encoded).getValuesByName(); 250 } catch (EncodingException exception) { 251 throw OAuthResponseException.fromReason(OAuthException.Reason.CALLBACK_MALFORMED); 252 } 253 } 254 255 private static int utf8Length(@NonNull String value) { 256 if (value.length() > Limits.AUTHORIZATION_RESPONSE_QUERY_SIZE.getDefaultIntValue()) 257 throw OAuthResponseException.fromReason(OAuthException.Reason.CALLBACK_MALFORMED); 258 try { 259 byte[] encoded = StrictUtf8.encode(value); 260 try { 261 return encoded.length; 262 } finally { 263 Arrays.fill(encoded, (byte) 0); 264 } 265 } catch (EncodingException exception) { 266 throw OAuthResponseException.fromReason(OAuthException.Reason.CALLBACK_MALFORMED); 267 } 268 } 269 270 private static @Nullable URI parseErrorUri(@NonNull Map<@NonNull String, @NonNull List<@NonNull String>> values) { 271 List<String> list = values.get("error_uri"); 272 if (list == null || list.isEmpty() || list.get(0).isEmpty()) 273 return null; 274 try { 275 URI uri = URI.create(list.get(0)); 276 if (!uri.isAbsolute()) 277 throw new IllegalArgumentException(); 278 return uri; 279 } catch (IllegalArgumentException exception) { 280 throw OAuthResponseException.fromReason(OAuthException.Reason.CALLBACK_MALFORMED); 281 } 282 } 283 284 private @NonNull Optional<@NonNull String> first(@NonNull String name) { 285 List<String> list = this.parameters.get(name); 286 return list == null || list.isEmpty() || list.get(0).isEmpty() ? Optional.empty() : Optional.of(list.get(0)); 287 } 288 289 /** 290 * Returns the code, if present and nonempty. It is untrusted until completion succeeds. 291 * 292 * @return the code 293 * @since 1.0.0 294 */ 295 public @NonNull Optional<@NonNull String> getCode() { return first("code"); } 296 297 /** 298 * Returns the state, if present and nonempty. 299 * 300 * @return the state 301 * @since 1.0.0 302 */ 303 public @NonNull Optional<@NonNull String> getState() { return first("state"); } 304 305 /** 306 * Returns the RFC 9207 issuer, if present and nonempty. 307 * 308 * @return the issuer 309 * @since 1.0.0 310 */ 311 public @NonNull Optional<@NonNull String> getIssuer() { return first("iss"); } 312 313 /** 314 * Returns an authorization error, if present and nonempty. 315 * 316 * @return the error 317 * @since 1.0.0 318 */ 319 public @NonNull Optional<@NonNull String> getError() { return first("error"); } 320 321 /** 322 * Returns untrusted error prose, if present, with non-NQSCHAR characters replaced and at most 1,024 characters. 323 * Do not log it without application redaction. The raw value remains available in {@link #getParameters()}. 324 * 325 * @return the prose 326 * @since 1.0.0 327 */ 328 public @NonNull Optional<@NonNull String> getErrorDescription() { 329 return first("error_description").map(AuthorizationResponse::safeErrorDescription); 330 } 331 332 private static @NonNull String safeErrorDescription(@NonNull String raw) { 333 StringBuilder safe = new StringBuilder(Math.min(raw.length(), 1_024)); 334 for (int index = 0; index < raw.length() && safe.length() < 1_024; index++) { 335 char value = raw.charAt(index); 336 safe.append((value == 0x20 || value == 0x21 || (value >= 0x23 && value <= 0x5B) 337 || (value >= 0x5D && value <= 0x7E)) ? value : '?'); 338 } 339 return safe.toString(); 340 } 341 342 /** 343 * Returns the absolute error URI, if present and nonempty. Parsing rejects a malformed supplied URI. 344 * This is untrusted provider data with no navigation, scheme or destination authorization. Never 345 * automatically redirect, fetch or render it as active content. Applications choosing to expose a 346 * link must apply their own exact HTTPS destination allowlist and safe HTML rendering. 347 * 348 * @return the URI 349 * @since 1.0.0 350 */ 351 public @NonNull Optional<@NonNull URI> getErrorUri() { 352 return Optional.ofNullable(this.errorUri); 353 } 354 355 /** 356 * Returns every decoded parameter, including unsigned provider extras. 357 * 358 * @return immutable parameter lists 359 * @since 1.0.0 360 */ 361 public @NonNull Map<@NonNull String, @NonNull List<@NonNull String>> getParameters() { 362 return Collections.unmodifiableMap(new LinkedHashMap<>(this.parameters)); 363 } 364 365 /** 366 * Returns the callback mode established by trusted application routing. 367 * 368 * @return the mode 369 * @since 1.0.0 370 */ 371 public AuthorizationRequestOptions.@NonNull ResponseMode getResponseMode() { return this.responseMode; } 372 373 /** 374 * Returns the optional per-flow cookie name derived from state. The suffix is a selector, not an authenticator. 375 * 376 * @return the cookie name when nonempty state is present 377 * @since 1.0.0 378 */ 379 public @NonNull Optional<@NonNull String> getPerFlowCookieName() { 380 return getState().map(OAuthCookieNames::fromState); 381 } 382 383 /** 384 * Redacts all callback parameters. 385 * 386 * @return a redacted description 387 * @since 1.0.0 388 */ 389 @Override 390 public @NonNull String toString() { return "AuthorizationResponse{parameters=<redacted>}"; } 391}