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 com.revetsec.internal.Limits;
021import org.jspecify.annotations.NonNull;
022import org.jspecify.annotations.Nullable;
023import javax.annotation.concurrent.Immutable;
024import javax.annotation.concurrent.NotThreadSafe;
025import java.net.URI;
026import java.time.Duration;
027import java.util.Collections;
028import java.util.LinkedHashSet;
029import java.util.Optional;
030import java.util.Set;
031import static java.util.Objects.requireNonNull;
032
033/**
034 * Immutable opt-in configuration for public client metadata documents.
035 * The default is disabled. Enabling requires a trusted bounded address resolver and an explicitly
036 * selected cache backend. Select {@link InMemoryOAuthClientMetadataCache} for bounded volatile,
037 * single-process storage, or supply an application-owned shared implementation. No build performs
038 * DNS, HTTP, signing, provider calls or thread creation. This policy is configuration, not client
039 * authorization or evidence of identity. Retrieved client names are untrusted display text.
040 * Origin restrictions can narrow public HTTPS eligibility, never permit private destinations.
041 * Actual retrieval also requires Revetsec's pinned transport and complete operation admission.
042 * @author <a href="https://www.revetkn.com">Mark Allen</a>
043 * @since 1.0.0
044 */
045@Immutable
046public final class OAuthClientMetadataPolicy {
047 private static final @NonNull OAuthClientMetadataPolicy DISABLED = new OAuthClientMetadataPolicy(null);
048 private final @Nullable OAuthClientMetadataAddressResolver addressResolver;
049 private final @Nullable OAuthClientMetadataCache cache;
050 private final @Nullable Set<@NonNull URI> allowedOrigins;
051 private final @NonNull Integer maximumDocumentBytes;
052 private final @NonNull Duration maximumFreshness;
053 private final @NonNull Integer maximumConcurrentFetches;
054 private final @NonNull Integer maximumResolvedAddresses;
055 private OAuthClientMetadataPolicy(@Nullable Builder builder) {
056  this.addressResolver = builder == null ? null : requireNonNull(builder.addressResolver);
057  this.cache = builder == null ? null : requireNonNull(builder.cache);
058  this.allowedOrigins = builder == null ? null : builder.allowedOrigins;
059  this.maximumDocumentBytes = builder == null ? Integer.valueOf(Limits.CIMD_MAXIMUM_DOCUMENT_BYTES.getDefaultIntValue()) : builder.maximumDocumentBytes;
060  this.maximumFreshness = builder == null ? Limits.CIMD_MAXIMUM_FRESHNESS.getDefaultDuration() : builder.maximumFreshness;
061  this.maximumConcurrentFetches = builder == null ? Integer.valueOf(Limits.CIMD_MAXIMUM_CONCURRENT_FETCHES.getDefaultIntValue()) : builder.maximumConcurrentFetches;
062  this.maximumResolvedAddresses = builder == null ? Integer.valueOf(Limits.CIMD_MAXIMUM_RESOLVED_ADDRESSES.getDefaultIntValue()) : builder.maximumResolvedAddresses;
063 }
064 /**
065  * Returns the disabled default configuration.
066  * @return the disabled policy
067  * @since 1.0.0
068  */
069 @CheckReturnValue public static @NonNull OAuthClientMetadataPolicy disabledInstance() { return DISABLED; }
070 /**
071  * Starts an enabled policy with its required trusted resolver. Select the cache with
072  * {@link Builder#cache(OAuthClientMetadataCache)} before building.
073  * @param addressResolver the bounded resolver
074  * @return the builder
075  * @throws NullPointerException if addressResolver is null
076  * @since 1.0.0
077  */
078 @CheckReturnValue public static @NonNull Builder withAddressResolver(@NonNull OAuthClientMetadataAddressResolver addressResolver) {
079  return new Builder(requireNonNull(addressResolver));
080 }
081 /**
082  * Builds an enabled policy with an explicit resolver and cache, without callbacks or I/O.
083  * @param addressResolver the bounded resolver
084  * @param cache the explicitly selected storage backend
085  * @return the enabled policy
086  * @throws NullPointerException if either required argument is null
087  * @since 1.0.0
088  */
089 @CheckReturnValue public static @NonNull OAuthClientMetadataPolicy fromAddressResolverAndCache(
090   @NonNull OAuthClientMetadataAddressResolver addressResolver, @NonNull OAuthClientMetadataCache cache) {
091  return withAddressResolver(addressResolver).cache(requireNonNull(cache)).build();
092 }
093 /**
094  * Returns whether metadata retrieval is configured.
095  * @return the enabled flag, not a transport availability or authorization proof
096  * @since 1.0.0
097  */
098 public @NonNull Boolean getEnabled() { return this.addressResolver != null; }
099 /**
100  * Returns the required resolver when enabled.
101  * @return empty only for the disabled policy
102  * @since 1.0.0
103  */
104 public @NonNull Optional<@NonNull OAuthClientMetadataAddressResolver> getAddressResolver() { return Optional.ofNullable(this.addressResolver); }
105 /**
106  * Returns the explicitly selected storage. Reusing this policy reuses that same backend;
107  * a process-local backend remains local even when multiple engines share it. The backend owns
108  * capacity and eviction policy; no engine substitutes an implicit in-memory implementation.
109  * @return the configured storage, or empty only for the disabled policy
110  * @since 1.0.0
111  */
112 public @NonNull Optional<@NonNull OAuthClientMetadataCache> getCache() { return Optional.ofNullable(this.cache); }
113 @NonNull OAuthClientMetadataCache cacheForEngine() {
114  if(!getEnabled())throw new IllegalStateException("Client metadata retrieval is disabled.");
115  return requireNonNull(this.cache);
116 }
117 /**
118  * Returns the exact origin restriction snapshot.
119  * @return empty for all eligible public HTTPS origins; a present empty set denies every origin
120  * @since 1.0.0
121  */
122 public @NonNull Optional<@NonNull Set<@NonNull URI>> getAllowedOrigins() { return Optional.ofNullable(this.allowedOrigins); }
123 /**
124  * Returns the configured bytes bound for maximumDocumentBytes.
125  * @return the configured limit
126  * @since 1.0.0
127  */
128 public @NonNull Integer getMaximumDocumentBytes() { return this.maximumDocumentBytes; }
129 /**
130  * Returns the configured time bound for maximumFreshness.
131  * @return the configured limit
132  * @since 1.0.0
133  */
134 public @NonNull Duration getMaximumFreshness() { return this.maximumFreshness; }
135 /**
136  * Returns the configured bound on active metadata fetches. Callers wait interruptibly within the
137  * original operation deadline. When the bound is at least two, authorization requests cannot occupy
138  * the final slot reserved for locally eligible credential transitions. Applications bound incoming concurrency.
139  * @return the configured limit
140  * @since 1.0.0
141  */
142 public @NonNull Integer getMaximumConcurrentFetches() { return this.maximumConcurrentFetches; }
143 /**
144  * Returns the configured addresses bound for maximumResolvedAddresses.
145  * @return the configured limit
146  * @since 1.0.0
147  */
148 public @NonNull Integer getMaximumResolvedAddresses() { return this.maximumResolvedAddresses; }
149 @Override public @NonNull String toString() { return "OAuthClientMetadataPolicy{enabled=" + getEnabled() + ", configuration=redacted}"; }
150 /**
151  * Builds an enabled policy; null property values reset defaults, except resolver and cache null
152  * clear required properties. There is no implicit storage backend.
153  * @author <a href="https://www.revetkn.com">Mark Allen</a>
154  * @since 1.0.0
155  */
156 @NotThreadSafe @CheckReturnValue
157 public static final class Builder {
158  private @Nullable OAuthClientMetadataAddressResolver addressResolver;
159  private @Nullable OAuthClientMetadataCache cache;
160  private @Nullable Set<@NonNull URI> allowedOrigins;
161  private @NonNull Integer maximumDocumentBytes = Limits.CIMD_MAXIMUM_DOCUMENT_BYTES.getDefaultIntValue();
162  private @NonNull Duration maximumFreshness = Limits.CIMD_MAXIMUM_FRESHNESS.getDefaultDuration();
163  private @NonNull Integer maximumConcurrentFetches = Limits.CIMD_MAXIMUM_CONCURRENT_FETCHES.getDefaultIntValue();
164  private @NonNull Integer maximumResolvedAddresses = Limits.CIMD_MAXIMUM_RESOLVED_ADDRESSES.getDefaultIntValue();
165  private Builder(@NonNull OAuthClientMetadataAddressResolver resolver) { this.addressResolver = resolver; }
166  /**
167   * Sets the trusted resolver; null clears it and makes build fail.
168   * @param value the resolver, or null to clear
169   * @return this builder
170   * @since 1.0.0
171   */
172  @CheckReturnValue public @NonNull Builder addressResolver(@Nullable OAuthClientMetadataAddressResolver value) { this.addressResolver = value; return this; }
173  /**
174   * Selects application storage. Null clears this required dependency and makes build fail;
175   * build invokes no provider method. Select an in-memory backend explicitly through
176   * {@link InMemoryOAuthClientMetadataCache#fromMaximumEntries(Integer)} when local storage is intended.
177   * Shared providers must honor atomic comparison, namespaces, record bounds and remaining budgets.
178   * @param value the selected storage, or null to clear
179   * @return this builder
180   * @since 1.0.0
181   */
182  @CheckReturnValue public @NonNull Builder cache(@Nullable OAuthClientMetadataCache value) { this.cache=value;return this; }
183  /**
184   * Sets a complete exact origin restriction snapshot. Null resets all eligible public HTTPS origins;
185   * an empty set denies every origin. Origins have HTTPS scheme, host and optional port only, without path,
186   * query, fragment or userinfo. At most 4096 origins and 128 KiB aggregate text are accepted.
187   * @param value the restriction, or null to reset
188   * @return this builder
189   * @throws IllegalArgumentException if a supplied origin or aggregate is invalid
190   * @throws NullPointerException if a set element is null
191   * @since 1.0.0
192   */
193  @CheckReturnValue public @NonNull Builder allowedOrigins(@Nullable Set<@NonNull URI> value) {
194   if (value == null) { this.allowedOrigins = null; return this; }
195   if (value.size() > 4096) throw OAuthServerConfiguration.invalid();
196   Set<URI> copy = new LinkedHashSet<>(); int used = 0;
197   for (URI origin : value) {
198    requireNonNull(origin); OAuthClientMetadataUri.origin(origin);
199    used = OAuthServerConfiguration.addBytes(used, origin.toString());
200    copy.add(origin); if (copy.size() > 4096) throw OAuthServerConfiguration.invalid();
201   }
202   this.allowedOrigins = Collections.unmodifiableSet(copy); return this;
203  }
204  /**
205   * Sets maximumDocumentBytes, bounded from {@code 1024} through {@code 5120}, inclusive.
206   * @param value the limit, or null to reset to {@code 5120}
207   * @return this builder
208   * @throws IllegalArgumentException if outside the allowed interval
209   * @since 1.0.0
210   */
211  @CheckReturnValue public @NonNull Builder maximumDocumentBytes(@Nullable Integer value) {
212   this.maximumDocumentBytes = value == null ? Limits.CIMD_MAXIMUM_DOCUMENT_BYTES.getDefaultIntValue() : Limits.CIMD_MAXIMUM_DOCUMENT_BYTES.require(value); return this;
213  }
214  /**
215   * Sets maximumFreshness, bounded from {@code Duration.ZERO} through {@code Duration.ofHours(1)}, inclusive.
216   * @param value the limit, or null to reset to {@code Duration.ofSeconds(300)}
217   * @return this builder
218   * @throws IllegalArgumentException if outside the allowed interval
219   * @since 1.0.0
220   */
221  @CheckReturnValue public @NonNull Builder maximumFreshness(@Nullable Duration value) {
222   this.maximumFreshness = value == null ? Limits.CIMD_MAXIMUM_FRESHNESS.getDefaultDuration() : Limits.CIMD_MAXIMUM_FRESHNESS.require(value); return this;
223  }
224  /**
225   * Sets maximumConcurrentFetches, bounded from {@code 1} through {@code 64}, inclusive.
226   * The limit bounds active fetches; waiting uses the original operation deadline without creating workers.
227   * At least two slots are needed to reserve one from authorization requests for credential transitions.
228   * @param value the limit, or null to reset to {@code 8}
229   * @return this builder
230   * @throws IllegalArgumentException if outside the allowed interval
231   * @since 1.0.0
232   */
233  @CheckReturnValue public @NonNull Builder maximumConcurrentFetches(@Nullable Integer value) {
234   this.maximumConcurrentFetches = value == null ? Limits.CIMD_MAXIMUM_CONCURRENT_FETCHES.getDefaultIntValue() : Limits.CIMD_MAXIMUM_CONCURRENT_FETCHES.require(value); return this;
235  }
236  /**
237   * Sets maximumResolvedAddresses, bounded from {@code 1} through {@code 64}, inclusive.
238   * @param value the limit, or null to reset to {@code 16}
239   * @return this builder
240   * @throws IllegalArgumentException if outside the allowed interval
241   * @since 1.0.0
242   */
243  @CheckReturnValue public @NonNull Builder maximumResolvedAddresses(@Nullable Integer value) {
244   this.maximumResolvedAddresses = value == null ? Limits.CIMD_MAXIMUM_RESOLVED_ADDRESSES.getDefaultIntValue() : Limits.CIMD_MAXIMUM_RESOLVED_ADDRESSES.require(value); return this;
245  }
246  /**
247   * Builds a complete immutable enabled configuration without invoking the resolver.
248   * @return the configured policy
249   * @throws IllegalStateException if the required resolver or cache is missing
250   * @since 1.0.0
251   */
252  @CheckReturnValue public @NonNull OAuthClientMetadataPolicy build() {
253   if (this.addressResolver == null) throw new IllegalStateException("Client metadata requires an address resolver.");
254   if (this.cache == null) throw new IllegalStateException("Client metadata requires an explicit cache backend.");
255   return new OAuthClientMetadataPolicy(this);
256  }
257 }
258}