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.json.JsonCodec; 022import com.revetsec.json.JsonArray; 023import com.revetsec.json.JsonObject; 024import com.revetsec.json.JsonValue; 025import org.jspecify.annotations.NonNull; 026import org.jspecify.annotations.Nullable; 027 028import javax.annotation.concurrent.Immutable; 029import javax.annotation.concurrent.NotThreadSafe; 030import java.security.MessageDigest; 031import java.security.NoSuchAlgorithmException; 032import java.time.Duration; 033import java.time.temporal.ChronoUnit; 034import java.util.ArrayList; 035import java.util.HashSet; 036import java.util.HexFormat; 037import java.util.LinkedHashMap; 038import java.util.List; 039import java.util.Map; 040import java.util.Set; 041 042import static java.util.Objects.requireNonNull; 043 044/** 045 * Publishes an immutable snapshot of public verification keys without an OAuth authorization server, signing, 046 * storage, network access or background threads. Applications register the endpoint and supply its key snapshot. 047 * Replace the publisher to rotate keys, retaining old verification keys until outstanding signatures and cached 048 * key sets have expired. Publication does not advertise the endpoint through discovery automatically. 049 * <p> 050 * A set has at most 100 keys and 256 KiB of UTF-8 JSON. Nonempty key IDs must be unique; keys without IDs are allowed. 051 * GET and HEAD support entity tags and bounded If-None-Match input. Outgoing HTTP Cache-Control max-age defaults to 052 * 60 seconds and can be configured from zero through 24 hours, in whole seconds. This policy controls downstream 053 * response caching; it does not expire or reload the key snapshot and is independent of OAuth issuer policy. 054 * 055 * @since 1.0.0 056 */ 057@Immutable 058public final class JwksPublisher { 059 060 private static final int MAXIMUM_KEYS = 100; 061 private static final int MAXIMUM_BODY_BYTES = 262_144; 062 private static final int MAXIMUM_CONDITIONAL_HEADER_LENGTH = 8192; 063 private static final @NonNull Duration DEFAULT_HTTP_CACHE_MAX_AGE = Duration.ofSeconds(60); 064 private static final @NonNull Duration MAXIMUM_HTTP_CACHE_MAX_AGE = Duration.ofHours(24); 065 private final @NonNull List<@NonNull PublishedJwk> keys; 066 private final @NonNull Duration httpCacheMaxAge; 067 private final @NonNull JsonObject json; 068 private final byte @NonNull [] body; 069 private final @NonNull String entityTag; 070 071 private JwksPublisher(@NonNull Builder builder) { 072 this.keys = builder.keys; 073 this.httpCacheMaxAge = builder.httpCacheMaxAge; 074 List<JsonValue> values = new ArrayList<>(); 075 Set<String> identifiers = new HashSet<>(); 076 int size = 0; 077 for (PublishedJwk key : this.keys) { 078 String identifier = key.getKeyId().orElse(null); 079 if (identifier != null && !identifiers.add(identifier)) 080 throw new IllegalArgumentException("Published key identifiers must be unique."); 081 JsonObject value = key.toJsonObject(); 082 size += JsonCodec.toUtf8Bytes(value).length; 083 if (size > MAXIMUM_BODY_BYTES) 084 throw new IllegalArgumentException("The published key set exceeds 256 KiB."); 085 values.add(value); 086 } 087 this.json = JsonObject.builder().put("keys", JsonArray.fromElements(values)).build(); 088 this.body = JsonCodec.toUtf8Bytes(this.json); 089 if (this.body.length > MAXIMUM_BODY_BYTES) 090 throw new IllegalArgumentException("The published key set exceeds 256 KiB."); 091 try { 092 this.entityTag = "\"" + HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(this.body)) + "\""; 093 } catch (NoSuchAlgorithmException unavailable) { 094 throw new IllegalStateException("SHA-256 is unavailable.", unavailable); 095 } 096 } 097 098 /** 099 * Starts a publisher builder with a snapshot of the complete ordered key list. An empty list publishes an empty set. 100 * @param keys at most 100 public keys, in publication order 101 * @return the builder 102 * @throws NullPointerException if the list or an element is null 103 * @throws IllegalArgumentException if there are too many keys 104 * @since 1.0.0 105 */ 106 @CheckReturnValue 107 public static @NonNull Builder withKeys(@NonNull List<@NonNull PublishedJwk> keys) { 108 return new Builder(keys); 109 } 110 111 /** 112 * Returns a publisher with the default HTTP cache max-age. Equivalent to {@code withKeys(keys).build()}. 113 * @param keys at most 100 public keys, in publication order 114 * @return the immutable publisher 115 * @throws NullPointerException if the list or an element is null 116 * @throws IllegalArgumentException if the key count, identifiers or document size is invalid 117 * @since 1.0.0 118 */ 119 @CheckReturnValue 120 public static @NonNull JwksPublisher fromKeys(@NonNull List<@NonNull PublishedJwk> keys) { 121 return withKeys(keys).build(); 122 } 123 124 /** 125 * Returns the immutable ordered public key snapshot. 126 * @return the published keys 127 * @since 1.0.0 128 */ 129 public @NonNull List<@NonNull PublishedJwk> getKeys() { 130 return this.keys; 131 } 132 133 /** 134 * Returns the max-age advertised in outgoing HTTP Cache-Control headers. It does not control key loading. 135 * @return the HTTP cache max-age in whole seconds 136 * @since 1.0.0 137 */ 138 public @NonNull Duration getHttpCacheMaxAge() { 139 return this.httpCacheMaxAge; 140 } 141 142 /** 143 * Serializes the public JWKS document to JSON text, in the supplied key order. The HTTP cache max-age does not 144 * affect the document. 145 * @return the JSON text, matching the UTF-8 document served by GET 146 * @since 1.0.0 147 */ 148 public @NonNull String toJson() { 149 return this.json.toJson(); 150 } 151 152 /** 153 * Returns the immutable public JWKS document, in the supplied key order. 154 * @return the JSON document 155 * @since 1.0.0 156 */ 157 public @NonNull JsonObject toJsonObject() { 158 return this.json; 159 } 160 161 /** 162 * Prepares a GET or HEAD response without a conditional header. Other methods receive 405. 163 * @param httpMethod the exact, case-sensitive HTTP method 164 * @return the prepared response 165 * @throws NullPointerException if the method is null 166 * @since 1.0.0 167 */ 168 @CheckReturnValue 169 public @NonNull JwksResponse responseFor(@NonNull String httpMethod) { 170 return responseFor(httpMethod, null); 171 } 172 173 /** 174 * Prepares a public response. GET/HEAD use weak If-None-Match comparison, including lists and the wildcard, to 175 * return 304 when appropriate. Malformed conditional syntax is ignored; input longer than 8192 characters receives 176 * a bodyless, non-cacheable 400. Combine repeated header occurrences with commas before calling this method. 177 * @param httpMethod the exact, case-sensitive HTTP method 178 * @param ifNoneMatch the complete If-None-Match field value, or null if absent 179 * @return the prepared response, including method or header rejection 180 * @throws NullPointerException if the method is null 181 * @since 1.0.0 182 */ 183 @CheckReturnValue 184 public @NonNull JwksResponse responseFor(@NonNull String httpMethod, @Nullable String ifNoneMatch) { 185 requireNonNull(httpMethod); 186 if (!httpMethod.equals("GET") && !httpMethod.equals("HEAD")) 187 return rejection(405); 188 if (ifNoneMatch != null && ifNoneMatch.length() > MAXIMUM_CONDITIONAL_HEADER_LENGTH) 189 return rejection(400); 190 boolean unchanged = ifNoneMatch != null && matches(ifNoneMatch); 191 Map<String, List<String>> headers = new LinkedHashMap<>(); 192 headers.put("Content-Type", List.of("application/jwk-set+json")); 193 headers.put("Cache-Control", List.of("public, max-age=" + this.httpCacheMaxAge.toSeconds() + ", must-revalidate")); 194 headers.put("ETag", List.of(this.entityTag)); 195 headers.put("Referrer-Policy", List.of("no-referrer")); 196 if (!unchanged) 197 headers.put("Content-Length", List.of(Integer.toString(this.body.length))); 198 boolean hasBody = !unchanged && httpMethod.equals("GET"); 199 return new JwksResponse(unchanged ? 304 : 200, headers, 200 hasBody ? this.body : new byte[0], hasBody ? this.json : null); 201 } 202 203 private static @NonNull JwksResponse rejection(int status) { 204 Map<String, List<String>> headers = new LinkedHashMap<>(); 205 headers.put("Cache-Control", List.of("no-store")); 206 headers.put("Content-Length", List.of("0")); 207 headers.put("Referrer-Policy", List.of("no-referrer")); 208 if (status == 405) 209 headers.put("Allow", List.of("GET, HEAD")); 210 return new JwksResponse(status, headers, new byte[0], null); 211 } 212 213 private boolean matches(@NonNull String field) { 214 int position = skipWhitespace(field, 0); 215 if (position < field.length() && field.charAt(position) == '*') 216 return skipWhitespace(field, position + 1) == field.length(); 217 boolean matched = false; 218 while (position < field.length()) { 219 // HTTP list recipients ignore empty members, including those between repeated field lines. 220 if (field.charAt(position) == ',') { 221 position = skipWhitespace(field, position + 1); 222 continue; 223 } 224 if (field.startsWith("W/", position)) 225 position += 2; 226 if (position >= field.length() || field.charAt(position) != '"') 227 return false; 228 int start = position++; 229 while (position < field.length() && field.charAt(position) != '"') { 230 char character = field.charAt(position++); 231 if (character < 0x21 || character == 0x7f || character > 0xff) 232 return false; 233 } 234 if (position >= field.length()) 235 return false; 236 matched |= this.entityTag.equals(field.substring(start, ++position)); 237 position = skipWhitespace(field, position); 238 if (position == field.length()) 239 return matched; 240 if (field.charAt(position++) != ',') 241 return false; 242 position = skipWhitespace(field, position); 243 } 244 return matched; 245 } 246 247 private static int skipWhitespace(@NonNull String value, int position) { 248 int end = position; 249 while (end < value.length() && (value.charAt(end) == ' ' || value.charAt(end) == '\t')) 250 ++end; 251 return end; 252 } 253 254 /** 255 * Returns a diagnostic without keys, key identifiers or certificate contents. 256 * @return the diagnostic description 257 * @since 1.0.0 258 */ 259 @Override 260 public @NonNull String toString() { 261 return "JwksPublisher{keys=<redacted>}"; 262 } 263 264 /** 265 * Configures an immutable public key snapshot. Optional setters replace previous values; null restores defaults. 266 * @since 1.0.0 267 */ 268 @NotThreadSafe 269 @CheckReturnValue 270 public static final class Builder { 271 private final @NonNull List<@NonNull PublishedJwk> keys; 272 private @NonNull Duration httpCacheMaxAge = DEFAULT_HTTP_CACHE_MAX_AGE; 273 274 private Builder(@NonNull List<@NonNull PublishedJwk> keys) { 275 requireNonNull(keys); 276 if (keys.size() > MAXIMUM_KEYS) 277 throw new IllegalArgumentException("A published key set may contain at most 100 keys."); 278 this.keys = List.copyOf(keys); 279 } 280 281 /** 282 * Replaces the max-age advertised in outgoing HTTP Cache-Control headers. It must be zero through 24 hours 283 * inclusive, expressed in whole seconds. This setting does not expire or reload the immutable key snapshot, 284 * and does not affect {@link JwksPublisher#toJson()} or {@link JwksPublisher#toJsonObject()}. 285 * @param httpCacheMaxAge the HTTP cache max-age, or null to restore 60 seconds 286 * @return this builder 287 * @throws IllegalArgumentException if the max-age is negative, fractional or over 24 hours 288 * @since 1.0.0 289 */ 290 @CanIgnoreReturnValue 291 public @NonNull Builder httpCacheMaxAge(@Nullable Duration httpCacheMaxAge) { 292 Duration value = httpCacheMaxAge == null ? DEFAULT_HTTP_CACHE_MAX_AGE : httpCacheMaxAge; 293 if (value.isNegative() || !value.equals(value.truncatedTo(ChronoUnit.SECONDS)) 294 || value.compareTo(MAXIMUM_HTTP_CACHE_MAX_AGE) > 0) 295 throw new IllegalArgumentException("The JWKS HTTP cache max-age must be whole seconds from zero through 24 hours."); 296 this.httpCacheMaxAge = value; 297 return this; 298 } 299 300 /** 301 * Builds an immutable snapshot and its bounded JSON representation and entity tag. 302 * @return the publisher 303 * @throws IllegalArgumentException if identifiers repeat or the document exceeds 256 KiB 304 * @since 1.0.0 305 */ 306 public @NonNull JwksPublisher build() { 307 return new JwksPublisher(this); 308 } 309 310 /** 311 * Returns a description without public key metadata. 312 * @return the diagnostic description 313 * @since 1.0.0 314 */ 315 @Override 316 public @NonNull String toString() { 317 return "JwksPublisher.Builder{keys=<redacted>}"; 318 } 319 } 320}