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.internal.Limits;
020import com.revetsec.internal.jose.JoseFailure;
021import com.revetsec.internal.jose.JwksParser;
022import com.revetsec.internal.jose.ParsedJwks;
023import com.revetsec.internal.jose.VerificationKey;
024import org.jspecify.annotations.NonNull;
025import org.jspecify.annotations.Nullable;
026import com.google.errorprone.annotations.CheckReturnValue;
027
028import javax.annotation.concurrent.Immutable;
029import java.util.ArrayList;
030import java.util.List;
031
032import static java.util.Objects.requireNonNull;
033
034/**
035 * A JSON Web Key Set (RFC 7517 section 5): the usable public verification keys of a key set document, in document
036 * order.
037 * <p>
038 * <strong>Keys that are not usable are skipped</strong>, never used in part, and never fail the set: a symmetric or
039 * private key, a key for encryption, a curve or key type Revetsec does not support, a weak or malformed key, and the
040 * rest of the cases {@link JwkSkipReason} lists. Only the document itself can fail: text that is not strict
041 * JSON, not an object, without a {@code keys} array of objects, or over the size and key-count limits.
042 * <p>
043 * The {@link #fromJsonResult(String)} operation applies the default limits of {@link RemoteJwksSource}: 256 KiB and 100 keys, every
044 * element of {@code keys} counted. So at the default limits a document is accepted the same way from a string as from
045 * the network.
046 * <p>
047 * Two key sets are equal when they hold equal keys in the same order.
048 *
049 * @author <a href="https://www.revetkn.com">Mark Allen</a>
050 * @since 1.0.0
051 */
052@Immutable
053public final class Jwks {
054        @NonNull
055        private final List<@NonNull Jwk> keys;
056        @NonNull
057        private final List<@NonNull VerificationKey> verificationKeys;
058
059        private Jwks(@NonNull List<@NonNull Jwk> keys,
060                                                                                                @NonNull List<@NonNull VerificationKey> verificationKeys) {
061                this(keys,verificationKeys,false);
062        }
063
064        private Jwks(@NonNull List<@NonNull Jwk> keys,
065                        @NonNull List<@NonNull VerificationKey> verificationKeys,boolean retainVerificationFixture) {
066                this.keys = List.copyOf(keys);
067                this.verificationKeys = retainVerificationFixture ? requireNonNull(verificationKeys) : List.copyOf(verificationKeys);
068        }
069
070        /**
071         * Parses a JSON Web Key Set document and returns the usable keys or a fixed structural rejection.
072         * Malformed or unusable individual keys are skipped; only the document structure and limits reject the set.
073         * This static facade returns usable keys only: it exposes no skipped-key count, original indices or per-key
074         * skip reasons and emits no observer events. Remote fetches have separate JoseObserver skip callbacks.
075         *
076         * @param json untrusted document, at most 256 KiB as UTF-8 and 100 elements in its keys array
077         * @return the parsing outcome; a successful key set may have no usable keys
078         * @throws NullPointerException if the document is null
079         * @since 1.0.0
080         */
081        @CheckReturnValue
082        public static @NonNull JwksParseResult fromJsonResult(@NonNull String json) {
083                requireNonNull(json);
084                try {
085                        return JwksParseResult.fromJwks(fromParsedJwks(JwksParser.parse(json,
086                                        Limits.JWKS_RESPONSE_BODY_SIZE.getDefaultIntValue(), Limits.JWKS_KEY_COUNT.getDefaultIntValue())));
087                } catch (JoseFailure failure) {
088                        return JwksParseResult.fromReason(failure.getReason());
089                }
090        }
091
092        /**
093         * Returns the public view of a parsed key set document.
094         *
095         * @param parsedJwks the parsed document
096         * @return the key set of its usable keys
097         */
098        @NonNull
099        static Jwks fromParsedJwks(@NonNull ParsedJwks parsedJwks) {
100                requireNonNull(parsedJwks);
101                List<Jwk> keys = new ArrayList<>(parsedJwks.keys().size());
102                for (VerificationKey key : parsedJwks.keys())
103                        keys.add(Jwk.fromVerificationKey(key));
104                return new Jwks(keys, parsedJwks.keys());
105        }
106
107        /**
108         * Returns the usable keys.
109         *
110         * @return an unmodifiable list, in document order; empty if every key was skipped
111         * @since 1.0.0
112         */
113        @NonNull
114        public List<@NonNull Jwk> getKeys() {
115                return this.keys;
116        }
117
118        /**
119         * The parsed keys, in the same order as {@link #getKeys()}.
120         */
121        @NonNull
122        List<@NonNull VerificationKey> verificationKeys() {
123                return this.verificationKeys;
124        }
125
126        /**
127         * Compares the keys, in order.
128         *
129         * @param object the other object
130         * @return whether {@code object} is a key set with equal keys in the same order
131         * @since 1.0.0
132         */
133        @Override
134        public boolean equals(@Nullable Object object) {
135                if (this == object)
136                        return true;
137                return object instanceof Jwks other && this.keys.equals(other.keys);
138        }
139
140        /**
141         * Returns a hash of the keys, in order.
142         *
143         * @return the hash code
144         * @since 1.0.0
145         */
146        @Override
147        public int hashCode() {
148                return this.keys.hashCode();
149        }
150
151        /**
152         * Describes the key set by its keys' public facts.
153         *
154         * @return the description
155         * @since 1.0.0
156         */
157        @Override
158        @NonNull
159        public String toString() {
160                return getClass().getSimpleName() + "{keys=" + this.keys + "}";
161        }
162}