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.CheckReturnValue;
020import com.revetsec.internal.encoding.EncodingException;
021import com.revetsec.internal.encoding.StrictUtf8;
022import com.revetsec.internal.jose.JwkParser;
023import org.jspecify.annotations.NonNull;
024import org.jspecify.annotations.Nullable;
025
026import javax.annotation.concurrent.Immutable;
027import javax.annotation.concurrent.NotThreadSafe;
028import java.util.Arrays;
029import java.util.Optional;
030
031import static java.util.Objects.requireNonNull;
032
033/**
034 * Immutable protected-header metadata for signing a JWT: its required {@link JwtType type} and optional key
035 * identifier and SHA-256 certificate thumbprint. The {@code alg} header comes from the {@link JwsSigner}; callers
036 * cannot configure a conflicting algorithm here.
037 * <p>
038 * Arrays are defensively copied. String rendering never exposes configured identifiers or certificate digests.
039 *
040 * @author <a href="https://www.revetkn.com">Mark Allen</a>
041 * @since 1.0.0
042 */
043@Immutable
044public final class JwtSigningHeader {
045        private static final int CERTIFICATE_DIGEST_LENGTH = 32;
046
047        private final @NonNull JwtType type;
048        private final @Nullable String keyId;
049        private final byte @Nullable [] certificateSha256Thumbprint;
050
051        private JwtSigningHeader(@NonNull Builder builder) {
052                this.type = builder.type;
053                this.keyId = builder.keyId;
054                this.certificateSha256Thumbprint = builder.certificateSha256Thumbprint == null
055                                ? null : builder.certificateSha256Thumbprint.clone();
056        }
057
058        /**
059         * Starts a header builder with the required token type.
060         *
061         * @param type the protected-header token type
062         * @return the builder
063         * @throws NullPointerException if {@code type} is {@code null}
064         * @since 1.0.0
065         */
066        @CheckReturnValue
067        public static @NonNull Builder withType(@NonNull JwtType type) {
068                return new Builder(type);
069        }
070
071        /**
072         * Returns a header with the required token type and no key identifier or certificate thumbprint.
073         * Equivalent to {@code withType(type).build()}.
074         *
075         * @param type the protected-header token type
076         * @return the immutable header
077         * @throws NullPointerException if {@code type} is {@code null}
078         * @since 1.0.0
079         */
080        @CheckReturnValue
081        public static @NonNull JwtSigningHeader fromType(@NonNull JwtType type) {
082                return withType(type).build();
083        }
084
085        /**
086         * Returns the required protected-header {@code typ} selection.
087         *
088         * @return the token type
089         * @since 1.0.0
090         */
091        public @NonNull JwtType getType() {
092                return this.type;
093        }
094
095        /**
096         * Returns the optional protected-header {@code kid} value.
097         *
098         * @return the key identifier when configured
099         * @since 1.0.0
100         */
101        public @NonNull Optional<@NonNull String> getKeyId() {
102                return Optional.ofNullable(this.keyId);
103        }
104
105        /**
106         * Returns a copy of the optional SHA-256 digest of a DER certificate, serialized as {@code x5t#S256} when signing.
107         *
108         * @return a copy of the certificate digest when configured
109         * @since 1.0.0
110         */
111        public @NonNull Optional<byte @NonNull []> getCertificateSha256Thumbprint() {
112                return this.certificateSha256Thumbprint == null
113                                ? Optional.empty() : Optional.of(this.certificateSha256Thumbprint.clone());
114        }
115
116        /**
117         * Returns a description without configured identifiers or certificate digests.
118         *
119         * @return the redacted description
120         * @since 1.0.0
121         */
122        @Override
123        public @NonNull String toString() {
124                return "JwtSigningHeader{header=<redacted>}";
125        }
126
127        /**
128         * Configures an immutable JWT signing header without signing or I/O. Optional setters replace their previous
129         * value, and {@code null} clears the value. Each {@link #build()} call takes an independent snapshot.
130         *
131         * @author <a href="https://www.revetkn.com">Mark Allen</a>
132         * @since 1.0.0
133         */
134        @NotThreadSafe
135        @CheckReturnValue
136        public static final class Builder {
137                private final @NonNull JwtType type;
138                private @Nullable String keyId;
139                private byte @Nullable [] certificateSha256Thumbprint;
140
141                private Builder(@NonNull JwtType type) {
142                        this.type = requireNonNull(type);
143                }
144
145                /**
146                 * Replaces the optional protected-header key identifier. Text must contain 1–256 UTF-16 code units and valid
147                 * Unicode.
148                 *
149                 * @param keyId the key identifier, or {@code null} to clear it
150                 * @return this builder
151                 * @throws IllegalArgumentException if the supplied identifier is empty, too long or invalid Unicode
152                 * @since 1.0.0
153                 */
154                public @NonNull Builder keyId(@Nullable String keyId) {
155                        if (keyId != null) {
156                                if (keyId.isEmpty() || keyId.length() > JwkParser.MAXIMUM_KEY_ID_LENGTH)
157                                        throw new IllegalArgumentException("The JWT signing key identifier is invalid.");
158                                try {
159                                        Arrays.fill(StrictUtf8.encode(keyId), (byte) 0);
160                                } catch (EncodingException invalid) {
161                                        throw new IllegalArgumentException("The JWT signing key identifier is invalid.");
162                                }
163                        }
164                        this.keyId = keyId;
165                        return this;
166                }
167
168                /**
169                 * Replaces the optional SHA-256 digest of a DER certificate with a defensive copy.
170                 *
171                 * @param certificateSha256Thumbprint exactly 32 digest bytes, or {@code null} to clear it
172                 * @return this builder
173                 * @throws IllegalArgumentException if the supplied digest does not contain exactly 32 bytes
174                 * @since 1.0.0
175                 */
176                public @NonNull Builder certificateSha256Thumbprint(byte @Nullable [] certificateSha256Thumbprint) {
177                        if (certificateSha256Thumbprint != null && certificateSha256Thumbprint.length != CERTIFICATE_DIGEST_LENGTH)
178                                throw new IllegalArgumentException("The JWT signing certificate digest must contain 32 bytes.");
179                        this.certificateSha256Thumbprint = certificateSha256Thumbprint == null
180                                        ? null : certificateSha256Thumbprint.clone();
181                        return this;
182                }
183
184                /**
185                 * Builds an immutable header snapshot without signing or I/O.
186                 *
187                 * @return the header
188                 * @since 1.0.0
189                 */
190                public @NonNull JwtSigningHeader build() {
191                        return new JwtSigningHeader(this);
192                }
193
194                /**
195                 * Returns a description without configured identifiers or certificate digests.
196                 *
197                 * @return the redacted description
198                 * @since 1.0.0
199                 */
200                @Override
201                public @NonNull String toString() {
202                        return "JwtSigningHeader.Builder{header=<redacted>}";
203                }
204        }
205}