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.oauth.server;
018
019import com.google.errorprone.annotations.CheckReturnValue;
020import org.jspecify.annotations.NonNull;
021import org.jspecify.annotations.Nullable;
022import java.security.PublicKey;
023import java.time.Instant;
024import java.util.LinkedHashMap;
025import java.util.Map;
026import javax.annotation.concurrent.Immutable;
027import javax.annotation.concurrent.NotThreadSafe;
028import static java.util.Objects.requireNonNull;
029
030/**
031 * Immutable application declaration of active, published and retained public keys. The active projection is
032 * always included. Identifiers must never be reused for different material. A new generation has a strictly
033 * later publication instant; keep its published keys available for the configured public metadata HTTP cache max-age
034 * before signing. Retirement boundaries cannot precede outstanding token expiries plus skew, deadline and cache margins.
035 * Applications persist these obligations across nodes, restarts and restores; an initial snapshot is a trusted
036 * declaration, not evidence of external distribution. At most 100 keys and 128 KiB of aggregate configuration
037 * are accepted; response limits apply separately. No provider lookup or signing occurs during construction.
038 * A fresh lifecycle instance conservatively waits from this generation's publication instant before signing,
039 * even when another process remembers an earlier staging observation for the same public key.
040 * @author <a href="https://www.revetkn.com">Mark Allen</a>
041 * @since 1.0.0
042 */
043@Immutable
044public final class OAuthIssuerKeySnapshot {
045 private final @NonNull OAuthIssuerSigningKey activeKey;
046 private final @NonNull Map<@NonNull String,@NonNull PublicKey> verificationKeys;
047 private final @NonNull String generation;
048 private final @NonNull Instant publishedAt;
049 private final @NonNull Map<@NonNull String,@NonNull Instant> retirementNotBefore;
050 private OAuthIssuerKeySnapshot(@NonNull Builder builder) {
051  if(builder.generation==null || builder.publishedAt==null) throw new IllegalStateException("Issuer key lifecycle declarations are required.");
052  this.activeKey=builder.activeKey; this.generation=builder.generation;this.publishedAt=builder.publishedAt;
053  Map<String,PublicKey> keys=new LinkedHashMap<>(builder.verificationKeys);
054  PublicKey previous=keys.put(this.activeKey.getKeyId(),this.activeKey.getPublicKey());
055  if(previous!=null && !OAuthIssuerPublicKeys.material(previous).equals(OAuthIssuerPublicKeys.material(this.activeKey.getPublicKey())))
056   throw OAuthStoreFormat.invalid();
057  if(keys.size()>100 || !keys.keySet().containsAll(builder.retirementNotBefore.keySet())) throw OAuthStoreFormat.invalid();
058  int size=OAuthServerConfiguration.utf8Length(this.generation);
059  for(Map.Entry<String,PublicKey> entry:keys.entrySet()) { size=OAuthServerConfiguration.addBytes(size,entry.getKey());
060   size=OAuthServerConfiguration.addBytes(size,OAuthIssuerPublicKeys.material(entry.getValue())); }
061  for(Instant retirement:builder.retirementNotBefore.values()) if(retirement.isBefore(this.publishedAt)) throw OAuthStoreFormat.invalid();
062  this.verificationKeys=Map.copyOf(keys);this.retirementNotBefore=Map.copyOf(builder.retirementNotBefore);
063 }
064 /**
065  * Starts a builder around the required active signing key.
066  * @param activeKey required immutable signing key
067  * @return a new builder
068  * @throws NullPointerException if activeKey is null
069  * @since 1.0.0
070  */
071 @CheckReturnValue
072 public static @NonNull Builder withActiveKey(@NonNull OAuthIssuerSigningKey activeKey) { return new Builder(requireNonNull(activeKey)); }
073 /** Returns the active signing holder.
074  * @return the active signing holder
075  * @since 1.0.0
076  */
077 public @NonNull OAuthIssuerSigningKey getActiveKey() { return this.activeKey; }
078 /** Returns the published and retained public verification keys.
079  * @return unmodifiable checked public keys, including the active key
080  * @since 1.0.0
081  */
082 public @NonNull Map<@NonNull String,@NonNull PublicKey> getVerificationKeys() { return this.verificationKeys; }
083 /** Returns the application lifecycle generation declaration.
084  * @return the exact application lifecycle generation
085  * @since 1.0.0
086  */
087 public @NonNull String getGeneration() { return this.generation; }
088 /** Returns the declared publication instant for this generation.
089  * @return when this generation was published to independent resources
090  * @since 1.0.0
091  */
092 public @NonNull Instant getPublishedAt() { return this.publishedAt; }
093 /** Returns the declared earliest removal instants for retained public keys.
094  * @return unmodifiable earliest retirement instants; absence declares no planned retirement
095  * @since 1.0.0
096  */
097 public @NonNull Map<@NonNull String,@NonNull Instant> getRetirementNotBefore() { return this.retirementNotBefore; }
098 /** @return a description without identifiers or key material
099  * @since 1.0.0
100  */
101 @Override public @NonNull String toString() { return "OAuthIssuerKeySnapshot{<redacted>}"; }
102 /**
103  * Builds a checked immutable declaration without signing or provider lookup.
104  * @author <a href="https://www.revetkn.com">Mark Allen</a>
105  * @since 1.0.0
106  */
107 @NotThreadSafe
108 @CheckReturnValue
109 public static final class Builder {
110  private final @NonNull OAuthIssuerSigningKey activeKey;
111  private @NonNull Map<@NonNull String,@NonNull PublicKey> verificationKeys=Map.of();
112  private @Nullable String generation;
113  private @Nullable Instant publishedAt;
114  private @NonNull Map<@NonNull String,@NonNull Instant> retirementNotBefore=Map.of();
115  private Builder(@NonNull OAuthIssuerSigningKey activeKey) { this.activeKey=activeKey; }
116  /**
117   * Sets additional public keys; an equal active duplicate is allowed, different material for its ID is refused.
118   * @param value at most 100 checked public RSA keys, or null to reset empty
119   * @return this builder
120   * @throws IllegalArgumentException if supplied configuration is invalid
121   * @since 1.0.0
122   */
123  @CheckReturnValue
124  public @NonNull Builder verificationKeys(@Nullable Map<@NonNull String,@NonNull PublicKey> value) {
125   if(value==null) this.verificationKeys=Map.of();
126   else {
127    if(value.size()>100) throw OAuthStoreFormat.invalid();
128    Map<String,PublicKey> copy=new LinkedHashMap<>();
129    for(Map.Entry<String,PublicKey> entry:value.entrySet()) {
130     String id=OAuthServerConfiguration.text(entry.getKey(),256);
131     if(copy.put(id,OAuthIssuerPublicKeys.snapshot(entry.getValue()))!=null) throw OAuthStoreFormat.invalid();
132    }
133    this.verificationKeys=Map.copyOf(copy);
134   }
135   return this;
136  }
137  /**
138   * Sets the required generation declaration.
139   * @param value nonempty text of at most 256 characters, or null to clear required
140   * @return this builder
141   * @throws IllegalArgumentException if supplied text is invalid
142   * @since 1.0.0
143   */
144  @CheckReturnValue
145  public @NonNull Builder generation(@Nullable String value) { this.generation=value==null ? null : OAuthServerConfiguration.text(value,256); return this; }
146  /**
147   * Sets the required publication instant.
148   * Preserve the actual instant for an unchanged generation across restarts; do not backdate a new
149   * generation to avoid the publication wait. This setter does not publish keys or restore prior history.
150   * @param value an instant before the permanent storage sentinel, or null to clear required
151   * @return this builder
152   * @throws IllegalArgumentException if the supplied instant is invalid
153   * @since 1.0.0
154   */
155  @CheckReturnValue
156  public @NonNull Builder publishedAt(@Nullable Instant value) {
157   if(value!=null && !value.isBefore(OAuthStoreFormat.PERMANENT)) throw OAuthStoreFormat.invalid();
158   this.publishedAt=value;return this;
159  }
160  /**
161   * Declares the earliest removal instants for published keys; it does not retire them automatically.
162   * @param value at most 100 key IDs to finite instants, or null to reset empty
163   * @return this builder
164   * @throws IllegalArgumentException if supplied configuration is invalid
165   * @since 1.0.0
166   */
167  @CheckReturnValue
168  public @NonNull Builder retirementNotBefore(@Nullable Map<@NonNull String,@NonNull Instant> value) {
169   if(value==null) this.retirementNotBefore=Map.of();
170   else {
171    if(value.size()>100) throw OAuthStoreFormat.invalid();
172    Map<String,Instant> copy=new LinkedHashMap<>();
173    for(Map.Entry<String,Instant> entry:value.entrySet()) {
174     String id=OAuthServerConfiguration.text(entry.getKey(),256);Instant instant=requireNonNull(entry.getValue());
175     if(!instant.isBefore(OAuthStoreFormat.PERMANENT) || copy.put(id,instant)!=null) throw OAuthStoreFormat.invalid();
176    }
177    this.retirementNotBefore=Map.copyOf(copy);
178   }
179   return this;
180  }
181  /**
182   * Checks and snapshots the configuration.
183   * @return immutable lifecycle declaration
184   * @throws IllegalStateException if generation or publishedAt is missing
185   * @throws IllegalArgumentException if supplied configuration is inconsistent
186   * @since 1.0.0
187   */
188  @CheckReturnValue
189  public @NonNull OAuthIssuerKeySnapshot build() { return new OAuthIssuerKeySnapshot(this); }
190 }
191}