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.oidc;
018
019import com.revetsec.jose.JoseException;
020import org.jspecify.annotations.NonNull;
021import org.jspecify.annotations.Nullable;
022
023import javax.annotation.concurrent.Immutable;
024import javax.annotation.concurrent.NotThreadSafe;
025import java.util.Optional;
026
027import static java.util.Objects.requireNonNull;
028
029/**
030 * An ID token, UserInfo response or refresh continuity check failed. The exception retains only fixed reasons;
031 * it never retains the rejected token, a claim, a lower-layer exception or any access or refresh token.
032 *
033 * @author <a href="https://www.revetkn.com">Mark Allen</a>
034 * @since 1.0.0
035 */
036@NotThreadSafe
037public final class OidcValidationException extends OidcException {
038        private static final long serialVersionUID = 1L;
039        /** The failed OIDC check. */
040        private final @NonNull Reason reason;
041        /** The lower-layer reason, without the lower-layer exception. */
042        private final JoseException.@Nullable Reason joseReason;
043
044        private OidcValidationException(@NonNull Reason reason, JoseException.@Nullable Reason joseReason) {
045                super(requireNonNull(reason).message);
046                this.reason = reason;
047                this.joseReason = joseReason;
048        }
049
050        static @NonNull OidcValidationException fromReason(@NonNull Reason reason) {
051                return new OidcValidationException(reason, null);
052        }
053
054        static @NonNull OidcValidationException fromJoseReason(JoseException.@NonNull Reason reason) {
055                requireNonNull(reason);
056                Reason oidcReason = switch (reason) {
057                        case ISSUER_MISMATCH, KEY_ISSUER_MISMATCH -> Reason.ISSUER_MISMATCH;
058                        case AUDIENCE_MISMATCH -> Reason.AUDIENCE_MISMATCH;
059                        case EXPIRED -> Reason.EXPIRED;
060                        case NOT_YET_VALID -> Reason.NOT_YET_VALID;
061                        case ISSUED_IN_FUTURE -> Reason.ISSUED_IN_FUTURE;
062                        case INVALID_TYPE -> Reason.INVALID_TYPE;
063                        case MISSING_CLAIM -> Reason.MISSING_CLAIM;
064                        case ALGORITHM_NOT_ALLOWED -> Reason.ALGORITHM_NOT_ALLOWED;
065                        case TOKEN_TOO_LARGE, TOKEN_SYNTAX, HEADER, CLAIMS, KEY_SET -> Reason.ID_TOKEN_MALFORMED;
066                        case ENCRYPTED_TOKEN, JSON_SERIALIZATION, CRITICAL_HEADER, UNENCODED_PAYLOAD, COMPRESSED_PAYLOAD,
067                                        NESTED_TOKEN, CONFIRMATION_NOT_VERIFIED -> Reason.ID_TOKEN_UNSUPPORTED;
068                        default -> Reason.ID_TOKEN_SIGNATURE_INVALID;
069                };
070                return new OidcValidationException(oidcReason, reason);
071        }
072
073        static @NonNull OidcValidationException fromUserInfoJoseReason(JoseException.@NonNull Reason reason) {
074                OidcValidationException mapped = fromJoseReason(reason);
075                Reason profile = switch (mapped.getReason()) {
076                        case ID_TOKEN_MALFORMED -> Reason.USERINFO_MALFORMED;
077                        case ID_TOKEN_UNSUPPORTED -> Reason.USERINFO_UNSUPPORTED;
078                        case ID_TOKEN_SIGNATURE_INVALID -> Reason.USERINFO_SIGNATURE_INVALID;
079                        default -> mapped.getReason();
080                };
081                return new OidcValidationException(profile, reason);
082        }
083
084        /**
085         * Returns the fixed OIDC failure reason.
086         *
087         * @return the reason
088         * @since 1.0.0
089         */
090        public @NonNull Reason getReason() {
091                return this.reason;
092        }
093
094        /**
095         * Returns the JOSE reason when the underlying signature, header or JWT checks failed.
096         *
097         * @return the lower-layer reason, if applicable
098         * @since 1.0.0
099         */
100        public @NonNull Optional<JoseException.@NonNull Reason> getJoseReason() {
101                return Optional.ofNullable(this.joseReason);
102        }
103
104        /**
105         * Fixed OIDC validation reasons. A later release may add constants; switches should have a default branch.
106         *
107         * @author <a href="https://www.revetkn.com">Mark Allen</a>
108         * @since 1.0.0
109         */
110        @Immutable
111        public enum Reason {
112                /** The ID token is absent from a successful code-flow token response. */
113                ID_TOKEN_MISSING("The token response has no ID token."),
114                /** The compact token, header or claims are malformed. */
115                ID_TOKEN_MALFORMED("The ID token is malformed."),
116                /** The signature did not verify with a trusted key. */
117                ID_TOKEN_SIGNATURE_INVALID("The ID token signature is invalid."),
118                /** The ID token uses an unsupported JOSE feature. */
119                ID_TOKEN_UNSUPPORTED("The ID token uses an unsupported feature."),
120                /** The ID-token or signed-UserInfo algorithm is outside its effective allowlist. */
121                ALGORITHM_NOT_ALLOWED("The OIDC token algorithm is not allowed."),
122                /** The issuer or key-issuer binding does not match. */
123                ISSUER_MISMATCH("The OIDC issuer does not match."),
124                /** The verified Entra tenant is denied by the application. */
125                TENANT_NOT_ALLOWED("The OIDC tenant is not allowed."),
126                /** The audience does not include the configured client. */
127                AUDIENCE_MISMATCH("The OIDC audience does not match."),
128                /** Another audience is not explicitly trusted. */
129                UNTRUSTED_AUDIENCE("The OIDC response includes an untrusted audience."),
130                /** The authorized party is not the client or an explicitly trusted party. */
131                AUTHORIZED_PARTY_MISMATCH("The ID token authorized party does not match."),
132                /** A required JWT claim is missing. */
133                MISSING_CLAIM("A required OIDC claim is missing."),
134                /** The expiry time, allowing for skew, has been reached. */
135                EXPIRED("The OIDC token has expired."),
136                /** The token's not-before time has not been reached. */
137                NOT_YET_VALID("The OIDC token is not yet valid."),
138                /** The issued-at time is in the future beyond skew. */
139                ISSUED_IN_FUTURE("The OIDC token was issued in the future."),
140                /** The issued-at age exceeds the configured maximum plus skew. */
141                TOO_OLD("The ID token is too old."),
142                /** The subject is absent, empty, non-ASCII or longer than 255 characters. */
143                INVALID_SUBJECT("The ID token subject is invalid."),
144                /** The header marks a different JWT profile. */
145                INVALID_TYPE("The OIDC token type is not allowed."),
146                /** The required nonce is absent. */
147                NONCE_MISSING("The ID token nonce is missing."),
148                /** The nonce differs from the authenticated pending request. */
149                NONCE_MISMATCH("The ID token nonce does not match."),
150                /** Authentication time is absent after requesting maximum authentication age. */
151                AUTH_TIME_MISSING("The ID token authentication time is missing."),
152                /** The authentication time is too old or in the future beyond skew. */
153                AUTHENTICATION_TOO_OLD("The ID token authentication time is not acceptable."),
154                /** The authentication context does not meet the configured requirement. */
155                INSUFFICIENT_ACR("The ID token authentication context is insufficient."),
156                /** The present access-token hash does not match the returned access token. */
157                ACCESS_TOKEN_HASH_MISMATCH("The ID token access-token hash does not match."),
158                /** The present code hash does not match the exchanged authorization code. */
159                CODE_HASH_MISMATCH("The ID token code hash does not match."),
160                /** The token response does not use the Bearer token type. */
161                TOKEN_TYPE_UNSUPPORTED("The token response type is not supported."),
162                /** UserInfo is not a strict JSON object or has malformed claims. */
163                USERINFO_MALFORMED("The UserInfo response is malformed."),
164                /** Signed UserInfo did not verify with a trusted key. */
165                USERINFO_SIGNATURE_INVALID("The UserInfo signature is invalid."),
166                /** Signed UserInfo uses an unsupported JOSE feature. */
167                USERINFO_UNSUPPORTED("The UserInfo response uses an unsupported feature."),
168                /** The response format differs from the client's registered signed/JSON policy. */
169                USERINFO_FORMAT_MISMATCH("The UserInfo response format does not match the configured policy."),
170                /** No UserInfo endpoint is configured or advertised. */
171                USERINFO_ENDPOINT_UNAVAILABLE("The provider has no UserInfo endpoint."),
172                /** The supplied authentication was validated for a different issuer or client. */
173                USERINFO_AUTHENTICATION_MISMATCH("The authentication does not belong to this OIDC client."),
174                /** An endpoint access token cannot safely be sent as a Bearer header. */
175                USERINFO_ACCESS_TOKEN_INVALID("The access token cannot be sent to UserInfo."),
176                /** The supplied access token's known lifetime has ended. */
177                USERINFO_ACCESS_TOKEN_EXPIRED("The UserInfo access token has expired."),
178                /** UserInfo names a different subject from the validated ID token. */
179                USERINFO_SUBJECT_MISMATCH("The UserInfo subject does not match."),
180                /** The per-request HMAC client secret is missing, malformed or too short. */
181                HMAC_SECRET_INVALID("The OIDC client secret cannot verify an ID token."),
182                /** A MAC ID token has more than one audience entry. */
183                HMAC_MULTIPLE_AUDIENCES("An HMAC ID token must have exactly one audience."),
184                /** A serialized continuity reference has invalid structure. */
185                SESSION_REFERENCE_INVALID("The OIDC session reference is invalid."),
186                /** A refreshed ID token differs from the original session's continuity claims. */
187                REFRESHED_ID_TOKEN_MISMATCH("The refreshed ID token does not match the original session.");
188
189                private final @NonNull String message;
190
191                Reason(@NonNull String message) {
192                        this.message = message;
193                }
194        }
195}