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.google.errorprone.annotations.CanIgnoreReturnValue;
020import com.google.errorprone.annotations.CheckReturnValue;
021import com.revetsec.internal.crypto.EcCurve;
022import com.revetsec.internal.crypto.EcPublicKeys;
023import com.revetsec.internal.crypto.Ed25519PublicKeys;
024import com.revetsec.internal.crypto.KeyRejectedException;
025import com.revetsec.internal.crypto.RsaPublicKeys;
026import com.revetsec.internal.encoding.EncodingException;
027import com.revetsec.internal.encoding.StrictUtf8;
028import com.revetsec.internal.jose.JwkParser;
029import com.revetsec.internal.pem.Pem;
030import com.revetsec.internal.pem.PemException;
031import com.revetsec.json.JsonArray;
032import com.revetsec.json.JsonObject;
033import com.revetsec.json.JsonString;
034import com.revetsec.json.JsonValue;
035import org.jspecify.annotations.NonNull;
036import org.jspecify.annotations.Nullable;
037
038import javax.annotation.concurrent.Immutable;
039import javax.annotation.concurrent.NotThreadSafe;
040import java.math.BigInteger;
041import java.security.GeneralSecurityException;
042import java.security.MessageDigest;
043import java.security.PublicKey;
044import java.security.cert.X509Certificate;
045import java.security.interfaces.ECPublicKey;
046import java.security.interfaces.EdECPublicKey;
047import java.security.interfaces.RSAPublicKey;
048import java.security.spec.ECPoint;
049import java.security.spec.EdECPoint;
050import java.security.spec.NamedParameterSpec;
051import java.util.ArrayList;
052import java.util.Arrays;
053import java.util.Base64;
054import java.util.HashSet;
055import java.util.LinkedHashMap;
056import java.util.List;
057import java.util.Map;
058import java.util.Optional;
059import java.util.Set;
060
061import static java.util.Objects.requireNonNull;
062
063/**
064 * An immutable public signing key for publication in a JSON Web Key Set (RFC 7517). RSA, EC on P-256, P-384 or
065 * P-521, and Ed25519 public keys are supported; shared secrets and private keys cannot be published here.
066 * <p>
067 * RSA publication requires generic RSA key material with algorithm RSA and no key-level PSS parameters.
068 * RSASSA-PSS containers/restricted keys are outside this publication profile, even when a selected PSS signer
069 * can use them. Publication does not erase or reinterpret key restrictions.
070 * <p>
071 * Only the public key is required. The key identifier, algorithm and certificate chain are optional. No algorithm
072 * is inferred when it is absent. Every key advertises {@code use=sig}.
073 * <p>
074 * Public parameters are copied when the builder starts, and certificate DER is copied and checked when its setter
075 * is called. Neither the builder nor the built key retains caller-owned key or certificate objects. A certificate
076 * chain supplies {@code x5c}, {@code x5t} and {@code x5t#S256}; certificate trust and validity periods are the
077 * application's responsibility.
078 *
079 * @author <a href="https://www.revetkn.com">Mark Allen</a>
080 * @since 1.0.0
081 */
082@Immutable
083public final class PublishedJwk {
084        private static final int MAXIMUM_CERTIFICATES = 16;
085        private static final int MAXIMUM_CERTIFICATE_BYTES = 65_536;
086        private static final int MAXIMUM_CHAIN_BYTES = 131_072;
087        private final @Nullable String keyId;
088        private final @Nullable JwsAlgorithm algorithm;
089        private final @NonNull JsonObject json;
090
091        private PublishedJwk(@NonNull Builder builder) {
092                this.keyId = builder.keyId;
093                this.algorithm = builder.algorithm;
094                Map<String, JsonValue> members = new LinkedHashMap<>(builder.material.getMembers());
095                members.put("use", JsonString.fromValue("sig"));
096                if (this.keyId != null)
097                        members.put("kid", JsonString.fromValue(this.keyId));
098                if (this.algorithm != null)
099                        members.put("alg", JsonString.fromValue(this.algorithm.getWireValue()));
100                members.putAll(builder.certificates.getMembers());
101                this.json = JsonObject.fromMembers(members);
102        }
103
104        /**
105         * Starts a builder with a checked snapshot of a public key.
106         *
107         * @param publicKey the public signing key
108         * @return the builder
109         * @throws NullPointerException if {@code publicKey} is {@code null}
110         * @throws IllegalArgumentException if the key is unsupported, malformed or refused by Revetsec's key policy
111         * @since 1.0.0
112         */
113        @CheckReturnValue
114        public static @NonNull Builder withPublicKey(@NonNull PublicKey publicKey) {
115                return new Builder(publicKey);
116        }
117
118        /**
119         * Returns a public signing key without optional metadata; equivalent to {@code withPublicKey(publicKey).build()}.
120         *
121         * @param publicKey the public signing key
122         * @return the immutable published key
123         * @throws NullPointerException if {@code publicKey} is {@code null}
124         * @throws IllegalArgumentException if the key is unsupported, malformed or refused by Revetsec's key policy
125         * @since 1.0.0
126         */
127        @CheckReturnValue
128        public static @NonNull PublishedJwk fromPublicKey(@NonNull PublicKey publicKey) {
129                return withPublicKey(publicKey).build();
130        }
131
132        /**
133         * Returns the optional JWK {@code kid} value.
134         *
135         * @return the configured key identifier, or empty
136         * @since 1.0.0
137         */
138        public @NonNull Optional<@NonNull String> getKeyId() {
139                return Optional.ofNullable(this.keyId);
140        }
141
142        /**
143         * Returns the optional JWK {@code alg} value. No algorithm is inferred from the public key.
144         *
145         * @return the configured algorithm, or empty
146         * @since 1.0.0
147         */
148        public @NonNull Optional<@NonNull JwsAlgorithm> getAlgorithm() {
149                return Optional.ofNullable(this.algorithm);
150        }
151
152        /**
153         * Serializes this key's public JWK representation, including optional certificate metadata, to JSON text.
154         *
155         * @return the JWK JSON text; no private or symmetric key parameters are included
156         * @since 1.0.0
157         */
158        public @NonNull String toJson() {
159                return this.json.toJson();
160        }
161
162        /**
163         * Returns this key's immutable public JWK representation, including optional certificate metadata.
164         *
165         * @return the JWK; no private or symmetric key parameters are included
166         * @since 1.0.0
167         */
168        public @NonNull JsonObject toJsonObject() {
169                return this.json;
170        }
171
172        /**
173         * Describes this object without configured key identifiers, key parameters or certificate material.
174         *
175         * @return the description
176         * @since 1.0.0
177         */
178        @Override
179        public @NonNull String toString() {
180                return "PublishedJwk{publicKey=<redacted>}";
181        }
182
183        private static @NonNull IllegalArgumentException invalidKey() {
184                return new IllegalArgumentException("The published public key is unsupported, malformed or weak.");
185        }
186
187        /** Reads only public components, then validates independent, bounded copies of those components. */
188        private static @NonNull JsonObject snapshot(@NonNull PublicKey key) {
189                try {
190                        if (key instanceof RSAPublicKey rsa) {
191                                if (!"RSA".equalsIgnoreCase(rsa.getAlgorithm()) || rsa.getParams() != null)
192                                        throw invalidKey();
193                                byte[] modulus = unsigned(rsa.getModulus(), RsaPublicKeys.MAXIMUM_MODULUS_BITS / Byte.SIZE);
194                                byte[] exponent = unsigned(rsa.getPublicExponent(), 4);
195                                RsaPublicKeys.fromComponents(modulus, exponent);
196                                return JsonObject.builder().put("kty", "RSA").put("n", base64Url(modulus))
197                                                .put("e", base64Url(exponent)).build();
198                        }
199                        if (key instanceof ECPublicKey ec) {
200                                EcCurve curve = EcCurve.findByParameterSpec(requireNonNull(ec.getParams())).orElseThrow(
201                                                PublishedJwk::invalidKey);
202                                ECPoint point = requireNonNull(ec.getW());
203                                byte[] x = coordinate(point.getAffineX(), curve.getCoordinateLength());
204                                byte[] y = coordinate(point.getAffineY(), curve.getCoordinateLength());
205                                EcPublicKeys.fromCoordinates(curve, x, y);
206                                return JsonObject.builder().put("kty", "EC").put("crv", curve.getName())
207                                                .put("x", base64Url(x)).put("y", base64Url(y)).build();
208                        }
209                        if (key instanceof EdECPublicKey ed) {
210                                if (!NamedParameterSpec.ED25519.getName().equals(ed.getParams().getName()))
211                                        throw invalidKey();
212                                EdECPoint point = requireNonNull(ed.getPoint());
213                                byte[] bigEndian = coordinate(point.getY(), Ed25519PublicKeys.KEY_LENGTH);
214                                byte[] encoded = new byte[Ed25519PublicKeys.KEY_LENGTH];
215                                for (int index = 0; index < encoded.length; index++)
216                                        encoded[index] = bigEndian[encoded.length - index - 1];
217                                // The high bit belongs to x's sign, so y must fit in the remaining 255 bits.
218                                if ((encoded[encoded.length - 1] & 0x80) != 0)
219                                        throw invalidKey();
220                                if (point.isXOdd())
221                                        encoded[encoded.length - 1] |= (byte) 0x80;
222                                Ed25519PublicKeys.fromEncoded(encoded);
223                                return JsonObject.builder().put("kty", "OKP").put("crv", "Ed25519")
224                                                .put("x", base64Url(encoded)).build();
225                        }
226                        throw invalidKey();
227                } catch (KeyRejectedException | RuntimeException invalid) {
228                        throw invalidKey();
229                }
230        }
231
232        private static byte @NonNull [] unsigned(@NonNull BigInteger value, int maximumBytes) {
233                if (value.signum() < 0 || value.bitLength() > maximumBytes * Byte.SIZE)
234                        throw invalidKey();
235                byte[] bytes = value.toByteArray();
236                if (bytes.length == 0 || bytes.length > maximumBytes + 1)
237                        throw invalidKey();
238                byte[] result = bytes.length > 1 && bytes[0] == 0 ? Arrays.copyOfRange(bytes, 1, bytes.length) : bytes.clone();
239                if (result.length > maximumBytes || new BigInteger(1, result).compareTo(value) != 0)
240                        throw invalidKey();
241                return result;
242        }
243
244        private static byte @NonNull [] coordinate(@NonNull BigInteger value, int length) {
245                byte[] minimal = unsigned(value, length);
246                byte[] padded = new byte[length];
247                System.arraycopy(minimal, 0, padded, length - minimal.length, minimal.length);
248                return padded;
249        }
250
251        private static @NonNull String base64Url(byte @NonNull [] bytes) {
252                return Base64.getUrlEncoder().withoutPadding().encodeToString(bytes);
253        }
254
255        private static @NonNull String string(@NonNull JsonObject json, @NonNull String member) {
256                return ((JsonString) requireNonNull(json.getMembers().get(member))).getValue();
257        }
258
259        private static void checkAlgorithm(@NonNull JsonObject material, @Nullable JwsAlgorithm algorithm) {
260                if (algorithm == null)
261                        return;
262                boolean compatible = switch (algorithm) {
263                        case RS256, RS384, RS512, PS256, PS384, PS512 -> string(material, "kty").equals("RSA");
264                        case ES256 -> "P-256".equals(material.getMembers().containsKey("crv") ? string(material, "crv") : null);
265                        case ES384 -> "P-384".equals(material.getMembers().containsKey("crv") ? string(material, "crv") : null);
266                        case ES512 -> "P-521".equals(material.getMembers().containsKey("crv") ? string(material, "crv") : null);
267                        case ED25519, EDDSA -> string(material, "kty").equals("OKP");
268                        default -> false;
269                };
270                if (!compatible)
271                        throw new IllegalArgumentException("The published algorithm is incompatible with the public key.");
272        }
273
274        private static @NonNull JsonObject snapshotCertificates(@NonNull JsonObject material,
275                        @Nullable List<@NonNull X509Certificate> chain) {
276                if (chain == null || chain.isEmpty())
277                        return JsonObject.emptyInstance();
278                if (chain.size() > MAXIMUM_CERTIFICATES)
279                        throw new IllegalArgumentException("The published certificate chain is too large.");
280                List<X509Certificate> parsed = new ArrayList<>();
281                List<JsonValue> encoded = new ArrayList<>();
282                Set<String> unique = new HashSet<>();
283                byte[] leaf = new byte[0];
284                int total = 0;
285                try {
286                        for (X509Certificate certificate : List.copyOf(chain)) {
287                                byte[] supplied = requireNonNull(certificate.getEncoded());
288                                if (supplied.length == 0 || supplied.length > MAXIMUM_CERTIFICATE_BYTES || supplied.length > MAXIMUM_CHAIN_BYTES - total)
289                                        throw new IllegalArgumentException("The published certificate chain is too large.");
290                                byte[] der = supplied.clone();
291                                total += der.length;
292                                String text = Base64.getEncoder().encodeToString(der);
293                                if (!unique.add(text))
294                                        throw new IllegalArgumentException("The published certificate chain contains a duplicate certificate.");
295                                parsed.add(Pem.parseCertificateDer(der));
296                                encoded.add(JsonString.fromValue(text));
297                                if (parsed.size() == 1)
298                                        leaf = der;
299                        }
300                        X509Certificate first = parsed.get(0);
301                        if (!material.equals(snapshot(requireNonNull(first.getPublicKey()))))
302                                throw new IllegalArgumentException("The leaf certificate does not match the published public key.");
303                        boolean[] leafUsage = first.getKeyUsage();
304                        if (leafUsage != null && (leafUsage.length == 0 || !leafUsage[0]))
305                                throw new IllegalArgumentException("The leaf certificate does not permit digital signatures.");
306                        for (int index = 1; index < parsed.size(); index++) {
307                                X509Certificate child = parsed.get(index - 1);
308                                X509Certificate issuer = parsed.get(index);
309                                boolean[] usage = issuer.getKeyUsage();
310                                if (!child.getIssuerX500Principal().equals(issuer.getSubjectX500Principal())
311                                                || issuer.getBasicConstraints() < 0 || (usage != null && (usage.length <= 5 || !usage[5])))
312                                        throw new IllegalArgumentException("The published certificate chain is not in issuer order.");
313                                child.verify(issuer.getPublicKey());
314                        }
315                        return JsonObject.builder().put("x5c", JsonArray.fromElements(encoded))
316                                        .put("x5t", base64Url(MessageDigest.getInstance("SHA-1").digest(leaf)))
317                                        .put("x5t#S256", base64Url(MessageDigest.getInstance("SHA-256").digest(leaf))).build();
318                } catch (GeneralSecurityException | PemException | RuntimeException invalid) {
319                        throw new IllegalArgumentException("The published certificate chain is malformed or inconsistent.");
320                }
321        }
322
323        /**
324         * Configures an immutable published public key. Optional setters replace prior values; {@code null} clears them.
325         * Key parameters and certificate encodings are snapshotted before assignment.
326         *
327         * @author <a href="https://www.revetkn.com">Mark Allen</a>
328         * @since 1.0.0
329         */
330        @NotThreadSafe
331        @CheckReturnValue
332        public static final class Builder {
333                private final @NonNull JsonObject material;
334                private @Nullable String keyId;
335                private @Nullable JwsAlgorithm algorithm;
336                private @NonNull JsonObject certificates = JsonObject.emptyInstance();
337
338                private Builder(@NonNull PublicKey publicKey) {
339                        this.material = snapshot(requireNonNull(publicKey));
340                }
341
342                /**
343                 * Replaces the optional key identifier. It must contain 1–256 UTF-16 code units and valid Unicode.
344                 *
345                 * @param keyId the JWK {@code kid}, or {@code null} to clear it
346                 * @return this builder
347                 * @throws IllegalArgumentException if the identifier is empty, too long or invalid Unicode
348                 * @since 1.0.0
349                 */
350                @CanIgnoreReturnValue
351                public @NonNull Builder keyId(@Nullable String keyId) {
352                        if (keyId != null) {
353                                if (keyId.isEmpty() || keyId.length() > JwkParser.MAXIMUM_KEY_ID_LENGTH)
354                                        throw new IllegalArgumentException("The published key identifier is invalid.");
355                                try {
356                                        Arrays.fill(StrictUtf8.encode(keyId), (byte) 0);
357                                } catch (EncodingException invalid) {
358                                        throw new IllegalArgumentException("The published key identifier is invalid.");
359                                }
360                        }
361                        this.keyId = keyId;
362                        return this;
363                }
364
365                /**
366                 * Replaces the optional algorithm restriction. RSA supports RS256/384/512 and PS256/384/512; EC supports
367                 * ES256, ES384 or ES512 on its corresponding curve; Ed25519 supports ED25519 and the legacy EDDSA name.
368                 *
369                 * @param algorithm the JWK {@code alg}, or {@code null} to omit it
370                 * @return this builder
371                 * @throws IllegalArgumentException if the algorithm does not match the key, including every HMAC algorithm
372                 * @since 1.0.0
373                 */
374                @CanIgnoreReturnValue
375                public @NonNull Builder algorithm(@Nullable JwsAlgorithm algorithm) {
376                        checkAlgorithm(this.material, algorithm);
377                        this.algorithm = algorithm;
378                        return this;
379                }
380
381                /**
382                 * Replaces the certificate chain with a checked snapshot, leaf first. The leaf must match the public key and
383                 * permit digital signatures when key usage is present. Each following certificate must be its predecessor's
384                 * signing CA, with a matching issuer name and valid certificate signature. Duplicate certificates are refused.
385                 * The chain need not end at a root; trust, validity periods and revocation are not evaluated.
386                 * <p>
387                 * At most 16 certificates, 64 KiB per DER certificate and 128 KiB of total DER are accepted. The leaf's SHA-1
388                 * and SHA-256 thumbprints are derived for {@code x5t} and {@code x5t#S256}; SHA-1 is only a certificate identifier.
389                 *
390                 * @param certificateChain the leaf-first chain, or {@code null} or an empty list to clear certificate metadata
391                 * @return this builder
392                 * @throws IllegalArgumentException if the chain is oversized, malformed, inconsistent or mismatched
393                 * @since 1.0.0
394                 */
395                @CanIgnoreReturnValue
396                public @NonNull Builder certificateChain(@Nullable List<@NonNull X509Certificate> certificateChain) {
397                        this.certificates = snapshotCertificates(this.material, certificateChain);
398                        return this;
399                }
400
401                /**
402                 * Returns a published key with the builder's current public parameters and metadata.
403                 *
404                 * @return the immutable public signing key
405                 * @since 1.0.0
406                 */
407                public @NonNull PublishedJwk build() {
408                        return new PublishedJwk(this);
409                }
410        }
411}