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.jose; 018 019import com.revetsec.ErrorCategory; 020import com.revetsec.RevetsecException; 021import org.jspecify.annotations.NonNull; 022 023import javax.annotation.concurrent.Immutable; 024import javax.annotation.concurrent.NotThreadSafe; 025 026import static java.util.Objects.requireNonNull; 027 028/** 029 * A rejected JOSE input: a token that {@link JwtValidator} refused, or a JSON Web Key Set document that 030 * {@link Jwks#fromJsonResult(String)} rejected. 031 * <p> 032 * Every instance has a {@link Reason}, which also fixes its class and {@link ErrorCategory}: 033 * <ul> 034 * <li>{@link MalformedJoseInputException}: {@link ErrorCategory#MALFORMED_INPUT}, for input that could not be 035 * parsed or exceeded a limit;</li> 036 * <li>{@link UnsupportedJoseFeatureException}: {@link ErrorCategory#UNSUPPORTED}, for a JOSE feature Revetsec does 037 * not support, such as encryption;</li> 038 * <li>{@link JwtValidationException}: {@link ErrorCategory#VALIDATION_FAILURE}, for a well-formed token that failed a 039 * check.</li> 040 * </ul> 041 * The message is the reason's fixed sentence and never contains the token, a claim, a key or a key ID. A JOSE 042 * exception has no cause and is never transient. Applications catch these exceptions; only Revetsec creates them. 043 * 044 * @author <a href="https://www.revetkn.com">Mark Allen</a> 045 * @since 1.0.0 046 */ 047@NotThreadSafe 048public abstract sealed class JoseException extends RevetsecException 049 permits MalformedJoseInputException, UnsupportedJoseFeatureException, JwtValidationException { 050 /** 051 * The serialized form's version. 052 */ 053 private static final long serialVersionUID = 1L; 054 055 /** 056 * Why the input was rejected; never {@code null}. 057 * 058 * @serial 059 */ 060 @NonNull 061 private final Reason reason; 062 063 /** 064 * Creates an exception for {@code reason}, with the reason's category and fixed message, no cause, and not 065 * transient. Only the three permitted subclasses call it, from their factories. 066 * 067 * @param reason the reason, whose category the subclass has checked 068 */ 069 JoseException(@NonNull Reason reason) { 070 // The checks run inside the super(...) arguments, so a failed construction leaves no partial instance. 071 super(requireNonNull(reason).category(), false, reason.message(), null); 072 this.reason = reason; 073 } 074 075 /** 076 * Returns a new exception of the class that {@code reason} belongs to. Only Revetsec calls this. 077 * 078 * @param reason the reason 079 * @return a new {@link MalformedJoseInputException}, {@link UnsupportedJoseFeatureException} or 080 * {@link JwtValidationException} 081 */ 082 @NonNull 083 static JoseException fromReason(@NonNull Reason reason) { 084 requireNonNull(reason); 085 086 return switch (reason.category()) { 087 case MALFORMED_INPUT -> MalformedJoseInputException.fromReason(reason); 088 case UNSUPPORTED -> UnsupportedJoseFeatureException.fromReason(reason); 089 case VALIDATION_FAILURE -> JwtValidationException.fromReason(reason); 090 default -> throw new IllegalArgumentException("A JOSE reason must be MALFORMED_INPUT, UNSUPPORTED or " 091 + "VALIDATION_FAILURE."); 092 }; 093 } 094 095 /** 096 * Returns why the input was rejected. 097 * 098 * @return the reason 099 * @since 1.0.0 100 */ 101 @NonNull 102 public final Reason getReason() { 103 return this.reason; 104 } 105 106 /** 107 * Why a JOSE input was rejected. Each reason belongs to exactly one exception class and category, and has one fixed 108 * message. 109 * <p> 110 * This enum is not switch-stable: a later release may add constants, so a {@code switch} over it needs a default 111 * branch. 112 * 113 * @author <a href="https://www.revetkn.com">Mark Allen</a> 114 * @since 1.0.0 115 */ 116 @Immutable 117 public enum Reason { 118 /** 119 * The token is longer than the validator's maximum token length. Nothing else about it was examined. 120 * {@link MalformedJoseInputException}. 121 */ 122 TOKEN_TOO_LARGE(ErrorCategory.MALFORMED_INPUT, "The token is longer than the maximum token length."), 123 /** 124 * The token is not a JWS compact serialization: a character outside the base64url alphabet and {@code .}, a 125 * number of dots other than two or four, an empty header, or a segment that is not canonical unpadded 126 * base64url (RFC 7515 sections 2 and 7.1). Four dots are {@link #ENCRYPTED_TOKEN}, and a leading left curly 127 * bracket is {@link #JSON_SERIALIZATION}. {@link MalformedJoseInputException}. 128 */ 129 TOKEN_SYNTAX(ErrorCategory.MALFORMED_INPUT, "The token is not a well-formed JWS compact serialization."), 130 /** 131 * The JOSE header is not a strict UTF-8 JSON object within the limits, has duplicate members, has no string 132 * {@code alg}, or has a {@code kid} that is not a string of 1 to 256 characters. 133 * {@link MalformedJoseInputException}. 134 */ 135 HEADER(ErrorCategory.MALFORMED_INPUT, "The token's JOSE header is malformed."), 136 /** 137 * The payload is not a strict UTF-8 JSON object within the limits, has duplicate members, is empty, or holds a 138 * registered claim of the wrong type or out of range, such as an {@code exp} that is not a number or an empty 139 * {@code aud} array (RFC 7519 section 4.1). {@link MalformedJoseInputException}. 140 */ 141 CLAIMS(ErrorCategory.MALFORMED_INPUT, "The token's claims are malformed."), 142 /** 143 * The JSON Web Key Set document is not a strict JSON object with a {@code keys} array of objects within the 144 * size and key-count limits (RFC 7517 section 5). {@link MalformedJoseInputException}. 145 */ 146 KEY_SET(ErrorCategory.MALFORMED_INPUT, "The JSON Web Key Set document is malformed."), 147 /** 148 * The token is a JWE compact serialization, with four dots (RFC 7516), which Revetsec does not decrypt. 149 * {@link UnsupportedJoseFeatureException}. 150 */ 151 ENCRYPTED_TOKEN(ErrorCategory.UNSUPPORTED, "Encrypted tokens are not supported."), 152 /** 153 * The token starts with a left curly bracket, as a JWS JSON serialization does (RFC 7515 section 7.2), which 154 * Revetsec does not accept. {@link UnsupportedJoseFeatureException}. 155 */ 156 JSON_SERIALIZATION(ErrorCategory.UNSUPPORTED, "The JWS JSON serialization is not supported."), 157 /** 158 * The header has a {@code crit} member (RFC 7515 section 4.1.11). Revetsec understands no extension, so it 159 * rejects every critical one. {@link UnsupportedJoseFeatureException}. 160 */ 161 CRITICAL_HEADER(ErrorCategory.UNSUPPORTED, "Critical header parameters are not supported."), 162 /** 163 * The header has a {@code b64} member (RFC 7797). {@link UnsupportedJoseFeatureException}. 164 */ 165 UNENCODED_PAYLOAD(ErrorCategory.UNSUPPORTED, "Unencoded payloads are not supported."), 166 /** 167 * The header has a {@code zip} member. {@link UnsupportedJoseFeatureException}. 168 */ 169 COMPRESSED_PAYLOAD(ErrorCategory.UNSUPPORTED, "Compressed payloads are not supported."), 170 /** 171 * The header has a {@code cty} member, as a nested token does (RFC 7519 section 5.2). 172 * {@link UnsupportedJoseFeatureException}. 173 */ 174 NESTED_TOKEN(ErrorCategory.UNSUPPORTED, "Nested tokens are not supported."), 175 /** 176 * The header's {@code alg} is not one of the allowed algorithms, compared exactly; {@code none} in any case 177 * lands here. {@link JwtValidationException}. 178 */ 179 ALGORITHM_NOT_ALLOWED(ErrorCategory.VALIDATION_FAILURE, "The token's algorithm is not allowed."), 180 /** 181 * The header carries its own key or a key location ({@code jwk}, {@code jku} or {@code x5u}), which Revetsec 182 * never trusts or fetches. {@link JwtValidationException}. 183 */ 184 UNTRUSTED_KEY_REFERENCE(ErrorCategory.VALIDATION_FAILURE, "The token's header refers to a key that is not " 185 + "trusted."), 186 /** 187 * The signature has the wrong length for its algorithm or key, or an ECDSA signature's r or s is outside 188 * [1, n − 1]. Decided before any cryptographic verification and, for the key-independent part, before any 189 * key is looked up. {@link JwtValidationException}. 190 */ 191 SIGNATURE_MALFORMED(ErrorCategory.VALIDATION_FAILURE, "The token's signature is malformed."), 192 /** 193 * No trusted key matches the token's {@code kid}, or, without a {@code kid}, no trusted key fits its 194 * algorithm. {@link JwtValidationException}. 195 */ 196 UNKNOWN_KEY(ErrorCategory.VALIDATION_FAILURE, "No trusted key matches the token."), 197 /** 198 * More than one trusted key fits the token: two usable keys share its {@code kid}, or, without a {@code kid}, 199 * more than one key fits its algorithm. {@link JwtValidationException}. 200 */ 201 AMBIGUOUS_KEY(ErrorCategory.VALIDATION_FAILURE, "More than one trusted key matches the token."), 202 /** 203 * Trusted keys with the token's {@code kid} exist, but none fits its algorithm: another key type or curve, 204 * another {@code alg}, or an RSA key without {@code alg} while more than one RSA algorithm is allowed. 205 * {@link JwtValidationException}. 206 */ 207 KEY_ALGORITHM_MISMATCH(ErrorCategory.VALIDATION_FAILURE, "The token's key does not fit its algorithm."), 208 /** 209 * The key's JWK {@code issuer} member does not match the token's {@code iss}. {@link JwtValidationException}. 210 */ 211 KEY_ISSUER_MISMATCH(ErrorCategory.VALIDATION_FAILURE, "The token's key is not bound to its issuer."), 212 /** 213 * The signature did not verify. {@link JwtValidationException}. 214 */ 215 SIGNATURE_MISMATCH(ErrorCategory.VALIDATION_FAILURE, "The token's signature does not verify."), 216 /** 217 * The header's {@code typ} is not one of the allowed types, or it is absent where a type is required. 218 * {@link JwtValidationException}. 219 */ 220 INVALID_TYPE(ErrorCategory.VALIDATION_FAILURE, "The token's type is not allowed."), 221 /** 222 * The token's {@code iss} is not the expected issuer, compared exactly. {@link JwtValidationException}. 223 */ 224 ISSUER_MISMATCH(ErrorCategory.VALIDATION_FAILURE, "The token's issuer is not the expected issuer."), 225 /** 226 * None of the token's audiences is an expected audience. {@link JwtValidationException}. 227 */ 228 AUDIENCE_MISMATCH(ErrorCategory.VALIDATION_FAILURE, "The token's audience is not an expected audience."), 229 /** 230 * A required claim is absent or JSON {@code null}. {@link JwtValidationException}. 231 */ 232 MISSING_CLAIM(ErrorCategory.VALIDATION_FAILURE, "A required claim is missing from the token."), 233 /** 234 * The token's {@code exp} has passed, allowing for clock skew. {@link JwtValidationException}. 235 */ 236 EXPIRED(ErrorCategory.VALIDATION_FAILURE, "The token has expired."), 237 /** 238 * The token's {@code nbf} has not yet been reached, allowing for clock skew. {@link JwtValidationException}. 239 */ 240 NOT_YET_VALID(ErrorCategory.VALIDATION_FAILURE, "The token is not yet valid."), 241 /** 242 * The token's {@code iat} is in the future, allowing for clock skew. {@link JwtValidationException}. 243 */ 244 ISSUED_IN_FUTURE(ErrorCategory.VALIDATION_FAILURE, "The token was issued in the future."), 245 /** 246 * The token has a {@code cnf} claim (RFC 7800): it is bound to a key whose possession this validator does not 247 * check, so it is never accepted as a bearer token. {@link JwtValidationException}. 248 */ 249 CONFIRMATION_NOT_VERIFIED(ErrorCategory.VALIDATION_FAILURE, "The token is bound to a key whose possession was " 250 + "not proven."); 251 252 @NonNull 253 private final ErrorCategory category; 254 @NonNull 255 private final String message; 256 257 Reason(@NonNull ErrorCategory category, 258 @NonNull String message) { 259 this.category = category; 260 this.message = message; 261 } 262 263 /** 264 * The category, which also fixes the exception class. 265 */ 266 @NonNull 267 ErrorCategory category() { 268 return this.category; 269 } 270 271 /** 272 * The fixed message. 273 */ 274 @NonNull 275 String message() { 276 return this.message; 277 } 278 } 279}