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;
022import org.jspecify.annotations.Nullable;
023
024import javax.annotation.concurrent.NotThreadSafe;
025import java.io.IOException;
026
027import static java.util.Objects.requireNonNull;
028
029/**
030 * Thrown when a {@link RemoteJwksSource} has no usable JSON Web Key Set for a call: the fetch failed, a
031 * recent failure is still suppressing fetches, the limit of two requests per cooldown held the call back, or the
032 * call's deadline ended while it waited for another caller's fetch.
033 * <p>
034 * Its category says what went wrong, and there is no separate reason:
035 * <ul>
036 *   <li>{@link ErrorCategory#TRANSPORT}: the exchange timed out or failed with an I/O error, the call's deadline
037 *   ended while it waited, or the limit of two requests per cooldown held the call back and no request was sent (all
038 *   transient; {@link JoseObserver#didSuppressJwksFetch(java.net.URI, java.time.Duration)} reports the
039 *   last), or this thread was interrupted (not transient, with the interrupt flag set again);</li>
040 *   <li>{@link ErrorCategory#REMOTE_ERROR}: the server answered with an error status (transient for 429 and 5xx) or a
041 *   redirect, which is never followed;</li>
042 *   <li>{@link ErrorCategory#MALFORMED_INPUT}: the response or the key set document was malformed or too large;</li>
043 *   <li>{@link ErrorCategory#CONFIGURATION}: the fetch cannot run in this configuration or runtime, such as a default
044 *   HTTP client that could not be created.</li>
045 * </ul>
046 * The message is fixed for each category and never contains the URI, a header or the response body. Only the caller
047 * whose request ended in an I/O error keeps the JDK's {@link IOException} as the cause; every other instance has
048 * none. Revetsec never wraps this exception: a validator that needed the key set throws it unchanged.
049 *
050 * @author <a href="https://www.revetkn.com">Mark Allen</a>
051 * @since 1.0.0
052 */
053@NotThreadSafe
054public final class JwksUnavailableException extends RevetsecException {
055        /**
056         * The serialized form's version.
057         */
058        private static final long serialVersionUID = 1L;
059
060        private JwksUnavailableException(@NonNull ErrorCategory category,
061                                                                                                                                                                                @NonNull Boolean transientFailure,
062                                                                                                                                                                                @Nullable IOException cause) {
063                // messageFor checks the category inside the super(...) arguments, so a failed construction leaves no partial
064                // instance; RevetsecException checks the transience and the cause.
065                super(category, transientFailure, messageFor(category), cause);
066        }
067
068        /**
069         * Returns a new instance with no cause. Only Revetsec calls this.
070         *
071         * @param category         {@link ErrorCategory#TRANSPORT}, {@link ErrorCategory#REMOTE_ERROR},
072         *                         {@link ErrorCategory#MALFORMED_INPUT} or {@link ErrorCategory#CONFIGURATION}
073         * @param transientFailure whether retrying later may succeed; only a {@code TRANSPORT} or {@code REMOTE_ERROR}
074         *                         failure may be transient
075         * @return a new instance
076         * @throws IllegalArgumentException if the category is not one of the four, or a category that is never transient
077         *                                  is marked transient
078         */
079        @NonNull
080        static JwksUnavailableException fromCategory(@NonNull ErrorCategory category,
081                                                                                                                                                                                                                                @NonNull Boolean transientFailure) {
082                return new JwksUnavailableException(requireNonNull(category), requireNonNull(transientFailure), null);
083        }
084
085        /**
086         * Returns a new instance that keeps the JDK's {@link IOException} as its cause. Only Revetsec calls this, for the
087         * caller whose own request failed with that I/O error.
088         *
089         * @param category         {@link ErrorCategory#TRANSPORT}, the only category that keeps a cause
090         * @param transientFailure whether retrying later may succeed
091         * @param cause            the JDK's I/O error, or {@code null} for none
092         * @return a new instance
093         * @throws IllegalArgumentException if the category is not one of the four, a category that is never transient is
094         *                                  marked transient, or a cause is given for a category other than
095         *                                  {@code TRANSPORT}
096         */
097        @NonNull
098        static JwksUnavailableException fromCategory(@NonNull ErrorCategory category,
099                                                                                                                                                                                                                                @NonNull Boolean transientFailure,
100                                                                                                                                                                                                                                @Nullable IOException cause) {
101                return new JwksUnavailableException(requireNonNull(category), requireNonNull(transientFailure), cause);
102        }
103
104        /**
105         * The fixed message of each category a key set failure can have.
106         *
107         * @throws IllegalArgumentException for any other category
108         */
109        @NonNull
110        private static String messageFor(@NonNull ErrorCategory category) {
111                return switch (requireNonNull(category)) {
112                        case TRANSPORT -> "The JSON Web Key Set could not be fetched.";
113                        case REMOTE_ERROR -> "The JSON Web Key Set endpoint answered with an error.";
114                        case MALFORMED_INPUT -> "The JSON Web Key Set response is malformed.";
115                        case CONFIGURATION -> "The JSON Web Key Set cannot be fetched in this configuration.";
116                        default -> throw new IllegalArgumentException("A JSON Web Key Set failure is TRANSPORT, REMOTE_ERROR, "
117                                        + "MALFORMED_INPUT or CONFIGURATION.");
118                };
119        }
120}