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.json.JsonArray; 022import com.revetsec.json.JsonBoolean; 023import com.revetsec.json.JsonNull; 024import com.revetsec.json.JsonNumber; 025import com.revetsec.json.JsonObject; 026import com.revetsec.json.JsonString; 027import com.revetsec.json.JsonValue; 028import org.jspecify.annotations.NonNull; 029import org.jspecify.annotations.Nullable; 030 031import javax.annotation.concurrent.Immutable; 032import javax.annotation.concurrent.NotThreadSafe; 033import java.math.BigDecimal; 034import java.time.Instant; 035import java.util.List; 036import java.util.Optional; 037import java.util.Set; 038 039import static java.util.Objects.requireNonNull; 040 041/** 042 * An immutable JWT claims set for signing (RFC 7519 section 4), with typed registered claims and JSON custom claims. 043 * This is application-supplied content; {@link JwtClaims} instead represents claims that passed validation. 044 * <p> 045 * Every registered claim is optional. No clock, expiration, audience or token-profile policy is supplied implicitly, 046 * and no ordering is required between the time claims. Applications choose those values for their token's purpose. 047 * NumericDates preserve the supplied {@link Instant}'s nanoseconds and use the same years -9999 through 9999 range 048 * that Revetsec accepts when reading JWTs. Audiences are serialized as a non-empty JSON array, even for one audience. 049 * <p> 050 * Registered setters replace earlier values, and {@code null} clears them. Custom claims add one name per call and 051 * reject duplicates and registered names. Every {@link Builder#build()} returns an independent snapshot, so the 052 * builder can be reused. No serialization is performed while building; the signer's output limits apply when signing. 053 * <p> 054 * Claims can carry personal data, so {@link #toString()} shows none of them. Instances compare by reference. 055 * 056 * @author <a href="https://www.revetkn.com">Mark Allen</a> 057 * @since 1.0.0 058 */ 059@Immutable 060public final class JwtClaimsSet { 061 @NonNull 062 private static final Instant EARLIEST_NUMERIC_DATE = Instant.ofEpochSecond(-377_705_116_800L); 063 @NonNull 064 private static final Instant END_NUMERIC_DATE = Instant.ofEpochSecond(253_402_300_800L); 065 @NonNull 066 private static final Set<@NonNull String> REGISTERED_NAMES = Set.of("iss", "sub", "aud", "exp", "nbf", "iat", "jti"); 067 068 @Nullable 069 private final String issuer; 070 @Nullable 071 private final String subject; 072 @NonNull 073 private final List<@NonNull String> audiences; 074 @Nullable 075 private final Instant expiresAt; 076 @Nullable 077 private final Instant issuedAt; 078 @Nullable 079 private final Instant notBefore; 080 @Nullable 081 private final String jwtId; 082 @NonNull 083 private final JsonObject claims; 084 085 /** 086 * Returns a builder with no claims. 087 * 088 * @return a new builder 089 * @since 1.0.0 090 */ 091 @NonNull 092 public static Builder builder() { 093 return new Builder(); 094 } 095 096 private JwtClaimsSet(@NonNull Builder builder) { 097 this.issuer = builder.issuer; 098 this.subject = builder.subject; 099 this.audiences = builder.audiences; 100 this.expiresAt = builder.expiresAt; 101 this.issuedAt = builder.issuedAt; 102 this.notBefore = builder.notBefore; 103 this.jwtId = builder.jwtId; 104 105 JsonObject.Builder claims = JsonObject.builder(); 106 if (this.issuer != null) 107 claims.put("iss", this.issuer); 108 if (this.subject != null) 109 claims.put("sub", this.subject); 110 if (!this.audiences.isEmpty()) 111 claims.put("aud", JsonArray.fromElements(this.audiences.stream().map(JsonString::fromValue).toList())); 112 if (this.expiresAt != null) 113 claims.put("exp", numericDate(this.expiresAt)); 114 if (this.issuedAt != null) 115 claims.put("iat", numericDate(this.issuedAt)); 116 if (this.notBefore != null) 117 claims.put("nbf", numericDate(this.notBefore)); 118 if (this.jwtId != null) 119 claims.put("jti", this.jwtId); 120 builder.customClaims.build().getMembers().forEach(claims::put); 121 this.claims = claims.build(); 122 } 123 124 /** 125 * Returns the issuer ({@code iss}). 126 * 127 * @return the issuer, or empty if absent 128 * @since 1.0.0 129 */ 130 @NonNull 131 public Optional<@NonNull String> getIssuer() { 132 return Optional.ofNullable(this.issuer); 133 } 134 135 /** 136 * Returns the subject ({@code sub}). 137 * 138 * @return the subject, or empty if absent 139 * @since 1.0.0 140 */ 141 @NonNull 142 public Optional<@NonNull String> getSubject() { 143 return Optional.ofNullable(this.subject); 144 } 145 146 /** 147 * Returns the audiences ({@code aud}). 148 * 149 * @return the unmodifiable audiences in order, or an empty list if absent 150 * @since 1.0.0 151 */ 152 @NonNull 153 public List<@NonNull String> getAudiences() { 154 return this.audiences; 155 } 156 157 /** 158 * Returns the expiration time ({@code exp}). 159 * 160 * @return the instant, or empty if absent 161 * @since 1.0.0 162 */ 163 @NonNull 164 public Optional<@NonNull Instant> getExpiresAt() { 165 return Optional.ofNullable(this.expiresAt); 166 } 167 168 /** 169 * Returns the issue time ({@code iat}). 170 * 171 * @return the instant, or empty if absent 172 * @since 1.0.0 173 */ 174 @NonNull 175 public Optional<@NonNull Instant> getIssuedAt() { 176 return Optional.ofNullable(this.issuedAt); 177 } 178 179 /** 180 * Returns the time before which the token is not valid ({@code nbf}). 181 * 182 * @return the instant, or empty if absent 183 * @since 1.0.0 184 */ 185 @NonNull 186 public Optional<@NonNull Instant> getNotBefore() { 187 return Optional.ofNullable(this.notBefore); 188 } 189 190 /** 191 * Returns the JWT ID ({@code jti}). 192 * 193 * @return the JWT ID, or empty if absent 194 * @since 1.0.0 195 */ 196 @NonNull 197 public Optional<@NonNull String> getJwtId() { 198 return Optional.ofNullable(this.jwtId); 199 } 200 201 /** 202 * Returns a claim's JSON value, registered or not. 203 * 204 * @param name the claim name, compared exactly 205 * @return the value, which may be JSON {@code null}, or empty if absent 206 * @throws NullPointerException if {@code name} is {@code null} 207 * @since 1.0.0 208 */ 209 @NonNull 210 public Optional<@NonNull JsonValue> getClaim(@NonNull String name) { 211 return this.claims.find(requireNonNull(name)); 212 } 213 214 /** 215 * Returns every claim's name, registered claims first and then custom claims in insertion order. 216 * 217 * @return the unmodifiable claim names 218 * @since 1.0.0 219 */ 220 @NonNull 221 public Set<@NonNull String> getClaimNames() { 222 return this.claims.getMembers().keySet(); 223 } 224 225 /** 226 * Returns every claim as a JSON object, which can carry personal data. 227 * 228 * @return the immutable claims set 229 * @since 1.0.0 230 */ 231 @NonNull 232 public JsonObject toJsonObject() { 233 return this.claims; 234 } 235 236 /** 237 * Describes this claims set without any claim. 238 * 239 * @return a fully redacted description 240 * @since 1.0.0 241 */ 242 @Override 243 @NonNull 244 public String toString() { 245 return getClass().getSimpleName() + "{<redacted>}"; 246 } 247 248 @NonNull 249 private static JsonNumber numericDate(@NonNull Instant instant) { 250 if (instant.getNano() == 0) 251 return JsonNumber.fromValue(instant.getEpochSecond()); 252 return JsonNumber.fromValue(BigDecimal.valueOf(instant.getEpochSecond()) 253 .add(BigDecimal.valueOf(instant.getNano(), 9)).stripTrailingZeros()); 254 } 255 256 @Nullable 257 private static Instant requireNumericDate(@Nullable Instant instant) { 258 if (instant != null && (instant.isBefore(EARLIEST_NUMERIC_DATE) || !instant.isBefore(END_NUMERIC_DATE))) 259 throw new IllegalArgumentException("A NumericDate must lie within years -9999 through 9999."); 260 return instant; 261 } 262 263 @Nullable 264 private static String requireJsonString(@Nullable String value) { 265 return value == null ? null : JsonString.fromValue(value).getValue(); 266 } 267 268 /** 269 * Builds an outbound claims set. Registered setters replace values, and {@code null} clears them. Custom claim 270 * methods add one name per call and reject repeated or registered names, even when their value is JSON {@code null}. 271 * All content checks run in the setters. No token-profile or time-ordering policy is applied by {@link #build()}. 272 * 273 * @author <a href="https://www.revetkn.com">Mark Allen</a> 274 * @since 1.0.0 275 */ 276 @NotThreadSafe 277 @CheckReturnValue 278 public static final class Builder { 279 @Nullable 280 private String issuer; 281 @Nullable 282 private String subject; 283 @NonNull 284 private List<@NonNull String> audiences; 285 @Nullable 286 private Instant expiresAt; 287 @Nullable 288 private Instant issuedAt; 289 @Nullable 290 private Instant notBefore; 291 @Nullable 292 private String jwtId; 293 private final JsonObject.@NonNull Builder customClaims; 294 295 private Builder() { 296 this.audiences = List.of(); 297 this.customClaims = JsonObject.builder(); 298 } 299 300 /** 301 * Sets the issuer ({@code iss}). 302 * 303 * @param issuer the issuer, or {@code null} to clear it 304 * @return this builder 305 * @throws IllegalArgumentException if the string contains an unpaired surrogate 306 * @since 1.0.0 307 */ 308 @NonNull 309 @CanIgnoreReturnValue 310 public Builder issuer(@Nullable String issuer) { 311 this.issuer = requireJsonString(issuer); 312 return this; 313 } 314 315 /** 316 * Sets the subject ({@code sub}). 317 * 318 * @param subject the subject, or {@code null} to clear it 319 * @return this builder 320 * @throws IllegalArgumentException if the string contains an unpaired surrogate 321 * @since 1.0.0 322 */ 323 @NonNull 324 @CanIgnoreReturnValue 325 public Builder subject(@Nullable String subject) { 326 this.subject = requireJsonString(subject); 327 return this; 328 } 329 330 /** 331 * Replaces the audiences ({@code aud}), serialized as an array even when there is one audience. 332 * 333 * @param audiences a non-empty list, copied before assignment; {@code null} clears it 334 * @return this builder 335 * @throws NullPointerException if an element is {@code null} 336 * @throws IllegalArgumentException if the list is empty or an audience contains an unpaired surrogate 337 * @since 1.0.0 338 */ 339 @NonNull 340 @CanIgnoreReturnValue 341 public Builder audiences(@Nullable List<@NonNull String> audiences) { 342 if (audiences == null) { 343 this.audiences = List.of(); 344 return this; 345 } 346 List<@NonNull String> snapshot = List.copyOf(audiences); 347 if (snapshot.isEmpty()) 348 throw new IllegalArgumentException("The audiences must not be empty."); 349 for (String audience : snapshot) 350 JsonString.fromValue(audience); 351 this.audiences = snapshot; 352 return this; 353 } 354 355 /** 356 * Sets the expiration time ({@code exp}) as a NumericDate, preserving nanoseconds. 357 * 358 * @param expiresAt the instant, or {@code null} to clear it 359 * @return this builder 360 * @throws IllegalArgumentException if the instant is outside years -9999 through 9999 361 * @since 1.0.0 362 */ 363 @NonNull 364 @CanIgnoreReturnValue 365 public Builder expiresAt(@Nullable Instant expiresAt) { 366 this.expiresAt = requireNumericDate(expiresAt); 367 return this; 368 } 369 370 /** 371 * Sets the issue time ({@code iat}) as a NumericDate, preserving nanoseconds. 372 * 373 * @param issuedAt the instant, or {@code null} to clear it 374 * @return this builder 375 * @throws IllegalArgumentException if the instant is outside years -9999 through 9999 376 * @since 1.0.0 377 */ 378 @NonNull 379 @CanIgnoreReturnValue 380 public Builder issuedAt(@Nullable Instant issuedAt) { 381 this.issuedAt = requireNumericDate(issuedAt); 382 return this; 383 } 384 385 /** 386 * Sets the time before which the token is not valid ({@code nbf}) as a NumericDate, preserving nanoseconds. 387 * 388 * @param notBefore the instant, or {@code null} to clear it 389 * @return this builder 390 * @throws IllegalArgumentException if the instant is outside years -9999 through 9999 391 * @since 1.0.0 392 */ 393 @NonNull 394 @CanIgnoreReturnValue 395 public Builder notBefore(@Nullable Instant notBefore) { 396 this.notBefore = requireNumericDate(notBefore); 397 return this; 398 } 399 400 /** 401 * Sets the JWT ID ({@code jti}). 402 * 403 * @param jwtId the JWT ID, or {@code null} to clear it 404 * @return this builder 405 * @throws IllegalArgumentException if the string contains an unpaired surrogate 406 * @since 1.0.0 407 */ 408 @NonNull 409 @CanIgnoreReturnValue 410 public Builder jwtId(@Nullable String jwtId) { 411 this.jwtId = requireJsonString(jwtId); 412 return this; 413 } 414 415 /** 416 * Adds a custom claim. Use the typed setters for registered claim names. 417 * 418 * @param name the claim name, compared exactly 419 * @param value the JSON value, including {@link JsonNull} for JSON {@code null} 420 * @return this builder 421 * @throws NullPointerException if an argument is {@code null} 422 * @throws IllegalArgumentException if the name is registered, already present or contains an unpaired 423 * surrogate, or the claims object would nest more than 64 deep 424 * @since 1.0.0 425 */ 426 @NonNull 427 @CanIgnoreReturnValue 428 public Builder claim(@NonNull String name, @NonNull JsonValue value) { 429 requireNonNull(name); 430 requireNonNull(value); 431 if (REGISTERED_NAMES.contains(name)) 432 throw new IllegalArgumentException("Use the typed setter for a registered claim."); 433 this.customClaims.put(name, value); 434 return this; 435 } 436 437 /** 438 * Adds a custom string claim. 439 * 440 * @param name the claim name, compared exactly 441 * @param value the string 442 * @return this builder 443 * @throws NullPointerException if an argument is {@code null} 444 * @throws IllegalArgumentException if the name is registered or already present, or the name or value 445 * contains an unpaired surrogate 446 * @since 1.0.0 447 */ 448 @NonNull 449 @CanIgnoreReturnValue 450 public Builder claim(@NonNull String name, @NonNull String value) { 451 return claim(name, JsonString.fromValue(value)); 452 } 453 454 /** 455 * Adds a custom integral number claim. 456 * 457 * @param name the claim name, compared exactly 458 * @param value the number 459 * @return this builder 460 * @throws NullPointerException if an argument is {@code null} 461 * @throws IllegalArgumentException if the name is registered, already present or contains an unpaired surrogate 462 * @since 1.0.0 463 */ 464 @NonNull 465 @CanIgnoreReturnValue 466 public Builder claim(@NonNull String name, @NonNull Long value) { 467 return claim(name, JsonNumber.fromValue(value)); 468 } 469 470 /** 471 * Adds a custom number claim held exactly as a JSON number. 472 * 473 * @param name the claim name, compared exactly 474 * @param value the number 475 * @return this builder 476 * @throws NullPointerException if an argument is {@code null} 477 * @throws IllegalArgumentException if the name is registered, already present or contains an unpaired 478 * surrogate, or the value exceeds the limits of {@link JsonNumber#fromValue(BigDecimal)} 479 * @since 1.0.0 480 */ 481 @NonNull 482 @CanIgnoreReturnValue 483 public Builder claim(@NonNull String name, @NonNull BigDecimal value) { 484 return claim(name, JsonNumber.fromValue(value)); 485 } 486 487 /** 488 * Adds a custom boolean claim. 489 * 490 * @param name the claim name, compared exactly 491 * @param value the boolean 492 * @return this builder 493 * @throws NullPointerException if an argument is {@code null} 494 * @throws IllegalArgumentException if the name is registered, already present or contains an unpaired surrogate 495 * @since 1.0.0 496 */ 497 @NonNull 498 @CanIgnoreReturnValue 499 public Builder claim(@NonNull String name, @NonNull Boolean value) { 500 return claim(name, JsonBoolean.fromValue(value)); 501 } 502 503 /** 504 * Adds a custom claim whose value is JSON {@code null}. 505 * 506 * @param name the claim name, compared exactly 507 * @return this builder 508 * @throws NullPointerException if the name is {@code null} 509 * @throws IllegalArgumentException if the name is registered, already present or contains an unpaired surrogate 510 * @since 1.0.0 511 */ 512 @NonNull 513 @CanIgnoreReturnValue 514 public Builder claimNull(@NonNull String name) { 515 return claim(name, JsonNull.defaultInstance()); 516 } 517 518 /** 519 * Returns an immutable snapshot of this builder's claims, without signing or applying a token profile. 520 * 521 * @return the outbound claims set 522 * @since 1.0.0 523 */ 524 @NonNull 525 public JwtClaimsSet build() { 526 return new JwtClaimsSet(this); 527 } 528 529 /** 530 * Describes this builder without any claim. 531 * 532 * @return a fully redacted description 533 * @since 1.0.0 534 */ 535 @Override 536 @NonNull 537 public String toString() { 538 return "JwtClaimsSet.Builder{<redacted>}"; 539 } 540 } 541}