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.revetsec.internal.ObserverDispatch;
020import java.util.concurrent.atomic.AtomicBoolean;
021import com.revetsec.BrowserBinding;
022import com.revetsec.ConfigurationDiagnostic;
023import com.revetsec.StateSealer;
024import com.revetsec.OutboundUriPolicy;
025import com.revetsec.internal.crypto.SealedStateAccess;
026import com.revetsec.internal.http.Deadline;
027import com.revetsec.internal.http.RuntimeFloor;
028import com.revetsec.internal.oauth.OidcTransactionAccess;
029import com.revetsec.jose.JwsAlgorithm;
030import com.revetsec.jose.StaticJwksSource;
031import com.revetsec.oauth.BearerToken;
032import com.revetsec.oauth.JwtAccessTokenValidator;
033import com.revetsec.oauth.VerifiedAccessToken;
034import com.revetsec.oauth.AccessTokenValidationException;
035import com.revetsec.oauth.OAuthTransportException;
036import com.google.errorprone.annotations.CheckReturnValue;
037import org.jspecify.annotations.NonNull;
038import org.jspecify.annotations.Nullable;
039import javax.annotation.concurrent.ThreadSafe;
040import javax.annotation.concurrent.NotThreadSafe;
041import java.net.URI;
042import java.time.Clock;
043import java.time.Duration;
044import java.time.Instant;
045import java.time.ZoneId;
046import java.util.List;
047import java.util.ArrayList;
048import java.util.Map;
049import java.util.Optional;
050import java.util.Set;
051import java.util.HashSet;
052import java.util.function.Function;
053import static java.util.Objects.requireNonNull;
054import static com.revetsec.oauth.server.OAuthServerException.Reason.*;
055import static com.revetsec.oauth.server.OAuthServerObserver.Endpoint.*;
056
057/**
058 * Caller-thread OAuth code issuer with authoritative online grant status. Applications supply users, consent,
059 * atomic durable storage, admitted store time, healthy worker clocks, keys and authorization policy. Register the exact configured
060 * routes; request headers never select issuer authority. Protect completion with the app's session and CSRF
061 * controls. Infrastructure faults remain exceptions; expected remote rejection is a restricted result.
062 * Construction performs no application data callbacks, network I/O, signing or thread startup; the builder documents
063 * its explicit observer notification. No positive grant-status cache.
064 * Revetsec has not been independently audited.
065 * @since 1.0.0
066 */
067@ThreadSafe
068public final class OAuthAuthorizationServer {
069 private final @NonNull String issuer;
070 private final @NonNull URI authorizationEndpoint, tokenEndpoint, jwksEndpoint;
071 private final @Nullable URI revocationEndpoint, introspectionEndpoint;
072 private final @NonNull OAuthServerSettings settings;
073 private final @NonNull OAuthServerIngressLimits limits;
074 private final @NonNull Map<@NonNull String, @NonNull Set<@NonNull String>> resources;
075 private final @NonNull OAuthServerClientRepository repository;
076 private final @NonNull OAuthGrantPolicy policy;
077 private final @NonNull OAuthServerObserver observer;
078 private final @NonNull Clock clock;
079 private final boolean nativeLoopback, localhost, localhostAnyPort, refresh;
080 private final @NonNull OAuthServerClientSelection clients;
081 private final @NonNull OAuthStoreCoordinator coordinator;
082 private final @NonNull OAuthAuthorizationLedger ledger;
083 private final @NonNull OAuthAuthorizationResponseEncoder authorizationEncoder;
084 private final @NonNull OAuthCodeRedemption codes;
085 private final @NonNull OAuthRefreshRotation rotations;
086 private final @NonNull OAuthIssuerKeyLifecycle keys;
087 private final @NonNull OAuthIssuerTokenStatus status;
088 private final @NonNull OAuthGrantRevocation revocation;
089 private final @NonNull OAuthResourceIntrospection introspection;
090 private final @NonNull OAuthIssuerMetadata metadata;
091 private OAuthAuthorizationServer(@NonNull Builder b) { this(b, Runtime.version()); }
092 private OAuthAuthorizationServer(@NonNull Builder b, Runtime.@NonNull Version runtimeVersion) {
093  // Inspection is the single construction-time configuration decision. Keep the historical
094  // exception categories while the fixed diagnostic codes remain local to the configuring caller.
095  List<ConfigurationDiagnostic> issues=b.configurationDiagnostics(runtimeVersion);
096  if(!issues.isEmpty()){
097   ConfigurationDiagnostic first=issues.get(0);
098   if(first.getReasonCode().equals("REQUIRED")) throw new IllegalStateException("Required authorization-server configuration is absent.");
099   if(first==ConfigurationDiagnostic.OAUTH_REFRESH_REQUIRES_REVOCATION_ENDPOINT)
100    throw new IllegalStateException("Refresh requires a revocation endpoint.");
101   if(first==ConfigurationDiagnostic.OAUTH_CLIENT_METADATA_RUNTIME_INCOMPATIBLE)
102    RuntimeFloor.require(runtimeVersion,b.acknowledgeUnpatchedRuntime);
103   throw OAuthStoreFormat.invalid();
104  }
105  this.issuer=b.issuer; this.authorizationEndpoint=required(b.authorizationEndpoint); this.tokenEndpoint=required(b.tokenEndpoint);
106  this.jwksEndpoint=required(b.jwksEndpoint); this.revocationEndpoint=b.revocationEndpoint; this.introspectionEndpoint=b.introspectionEndpoint;
107  this.repository=required(b.clientRepository); this.policy=required(b.grantPolicy); OAuthAuthorizationServerStore store=required(b.store);
108  OAuthIssuerKeyProvider provider=required(b.signingKeys); StateSealer sealer=required(b.stateSealer);
109  this.refresh=b.refreshTokensEnabled;
110  if (this.refresh && this.revocationEndpoint==null) throw new IllegalStateException("Refresh requires a revocation endpoint.");
111  this.settings=b.settings.build(this.refresh,SealedStateAccess.get().getMaximumSealedLength(sealer)); this.limits=this.settings.ingress();
112  this.resources=OAuthServerAuthorizationAdmission.checkedServerResources(required(b.resources),this.limits);
113  this.clock=b.clock; this.observer=b.observer; this.nativeLoopback=b.allowNativeLoopbackRedirects; this.localhost=b.allowLocalhostRedirects; this.localhostAnyPort=b.allowLocalhostAnyPortRedirects;
114  URI issuerUri=endpoint(URI.create(this.issuer),b.allowInsecureLoopback);
115  Set<String> routes=new HashSet<>();
116  for (URI route:List.of(this.authorizationEndpoint,this.tokenEndpoint,this.jwksEndpoint)) checkRoute(issuerUri,route,b.allowInsecureLoopback,routes);
117  if(this.revocationEndpoint!=null) checkRoute(issuerUri,this.revocationEndpoint,b.allowInsecureLoopback,routes);
118  if(this.introspectionEndpoint!=null) checkRoute(issuerUri,this.introspectionEndpoint,b.allowInsecureLoopback,routes);
119  OAuthClientMetadataPolicy metadataPolicy=b.clientMetadataPolicy;
120  if(metadataPolicy.getEnabled()) RuntimeFloor.require(runtimeVersion,b.acknowledgeUnpatchedRuntime);
121  OAuthClientMetadataFetcher fetcher=metadataPolicy.getEnabled() ? b.clientMetadataTransport==null
122   ? new OAuthClientMetadataFetcher(this.issuer,sealer,metadataPolicy,this.limits,this.nativeLoopback,this.localhost,this.localhostAnyPort,
123    b.outboundUriPolicy,this.clock,this.settings.requestTimeout)
124   : new OAuthClientMetadataFetcher(this.issuer,sealer,metadataPolicy,this.limits,this.nativeLoopback,this.localhost,this.localhostAnyPort,
125    b.outboundUriPolicy,this.clock,b.clientMetadataTransport) : null;
126  this.clients=new OAuthServerClientSelection(this.repository,this.limits,fetcher,true);
127  OAuthStoreRecordCodec codec=new OAuthStoreRecordCodec(this.issuer,sealer,this.settings.maximumStoreRecordBytes);
128  this.coordinator=new OAuthStoreCoordinator(store,codec,this.clock,this.settings.clockSkew,this.settings.maximumStoreCommitAttempts,this.settings.maximumSubjectLength);
129  this.ledger=new OAuthAuthorizationLedger(this.coordinator,codec,this.limits,this.settings.authorizationInteractionLifetime,
130   this.settings.authorizationCodeLifetime,this.settings.maximumStoreCommitAttempts,this.settings.maximumSubjectLength,this.refresh);
131  OAuthGrantRetention retention=new OAuthGrantRetention(this.settings.accessTokenLifetime,this.settings.clockSkew,this.settings.totalDeadline,this.settings.publicMetadataHttpCacheMaxAge);
132  this.keys=new OAuthIssuerKeyLifecycle(provider,this.clock,this.settings.publicMetadataHttpCacheMaxAge,retention,true);
133  OAuthTokenResponse.Encoder encoder=new OAuthTokenResponse.Encoder(this.issuer,this.keys,this.settings.maximumResponseBodyBytes,this.settings.maximumHeaderBytes);
134  this.codes=new OAuthCodeRedemption(this.coordinator,codec,this.limits,retention,encoder,this.settings.accessTokenLifetime,this.refresh,
135   this.settings.refreshTokenIdleLifetime,this.settings.refreshTokenAbsoluteLifetime,this.settings.maximumStoreCommitAttempts,this.settings.maximumSubjectLength);
136  this.rotations=new OAuthRefreshRotation(this.coordinator,codec,this.limits,retention,encoder,this.settings.accessTokenLifetime,this.refresh,
137   this.settings.refreshTokenIdleLifetime,this.settings.maximumStoreCommitAttempts,this.settings.maximumSubjectLength);
138  this.authorizationEncoder=new OAuthAuthorizationResponseEncoder(issuerUri,b.allowInsecureLoopback,this.settings.maximumResponseBodyBytes,this.settings.maximumHeaderBytes,this.settings.maximumStateLength);
139  this.status=new OAuthIssuerTokenStatus(this.coordinator,codec,this.limits,this.clock,this.settings.clockSkew,this.settings.maximumStoreCommitAttempts,this.settings.maximumSubjectLength,this.settings.maximumRequestBodyBytes);
140  this.revocation=new OAuthGrantRevocation(this.coordinator,codec,this.status,this.limits,this.settings.maximumStoreCommitAttempts,this.settings.maximumSubjectLength,this.settings.maximumResponseBodyBytes,this.settings.maximumHeaderBytes);
141  this.introspection=new OAuthResourceIntrospection(this.status,this.limits,this.settings.maximumResponseBodyBytes,this.settings.maximumHeaderBytes);
142  Set<String> scopes=new HashSet<>(); for(Set<String> values:this.resources.values()) scopes.addAll(values);
143  this.metadata=new OAuthIssuerMetadata(issuerUri,this.authorizationEndpoint,this.tokenEndpoint,this.jwksEndpoint,this.revocationEndpoint,this.introspectionEndpoint,
144   this.refresh,b.allowInsecureLoopback,scopes,this.settings.publicMetadataHttpCacheMaxAge,this.settings.maximumResponseBodyBytes,this.settings.maximumHeaderBytes,metadataPolicy.getEnabled());
145  if(this.localhostAnyPort) ObserverDispatch.dispatch(this.observer,OAuthServerObserver::didEnableLocalhostAnyPortRedirects);
146 }
147 /**
148  * Starts configuration with an exact issuer identity, retained for the lifetime of the builder/server.
149  * The primary argument is required and cannot be cleared. This factory checks its URI shape; numeric
150  * HTTP loopback is admitted provisionally but still requires {@link Builder#allowInsecureLoopback(Boolean)}
151  * at build. Localhost HTTP issuers are not supported. No endpoint routes are inferred or network calls made.
152  * @param issuer absolute HTTPS issuer, or a numeric HTTP loopback issuer for explicit local opt-in
153  * @return an otherwise unconfigured builder
154  * @throws NullPointerException if issuer is null
155  * @throws IllegalArgumentException if issuer is not a permitted absolute issuer URI
156  * @since 1.0.0
157  */
158 @CheckReturnValue public static @NonNull Builder withIssuer(@NonNull String issuer) { return new Builder(issuer); }
159 /** Admits a GET authorization request and creates a browser-bound interaction.
160  * @param httpMethod materialized method
161  * @param rawQuery original query or absence
162  * @param rawBody materialized body
163  * @param rawHeaderValues original header names and all occurrences
164  * @param browserBinding independent app-owned canonical random binding
165  * @return interaction or fixed local rejection
166  * @since 1.0.0
167  */
168 @CheckReturnValue public @NonNull OAuthAuthorizationResult beginAuthorizationResult(@NonNull String httpMethod,@Nullable String rawQuery,
169   byte @NonNull [] rawBody,@NonNull Map<@NonNull String,@NonNull List<@NonNull String>> rawHeaderValues,@NonNull BrowserBinding browserBinding) {
170  return beginAuthorizationResult(httpMethod,rawQuery,rawBody,rawHeaderValues,requireNonNull(browserBinding).toSecretString());
171 }
172 @CheckReturnValue @NonNull OAuthAuthorizationResult beginAuthorizationResult(@NonNull String httpMethod,@Nullable String rawQuery,
173   byte @NonNull [] rawBody,@NonNull Map<@NonNull String,@NonNull List<@NonNull String>> rawHeaderValues,@NonNull String browserBinding) {
174  inputs(httpMethod,rawBody,rawHeaderValues); requireNonNull(browserBinding);
175  return execute(AUTHORIZATION,d->{
176   OAuthServerRequest request=parse(OAuthServerRequest.Endpoint.AUTHORIZATION,httpMethod,rawQuery,rawBody,rawHeaderValues);
177   binding(browserBinding);
178   AtomicBoolean reported=new AtomicBoolean();
179   return this.ledger.beginResult(()->OAuthServerAuthorizationAdmission.admit(request,this.clients,d,this.resources,this.limits,this.nativeLoopback,this.localhost,this.localhostAnyPort,
180    ()->{if(reported.compareAndSet(false,true)) ObserverDispatch.dispatch(this.observer,OAuthServerObserver::didUseLocalhostAnyPortRedirects);}),browserBinding,d);
181  },r->OAuthAuthorizationResult.fromRejection(r,rejection(OAuthServerRequest.Endpoint.AUTHORIZATION,r,false)));
182 }
183 /** Rechecks a continuation before rendering consent; this does not authenticate a user.
184  * @param interactionValue secret continuation
185  * @param browserBinding independent app-owned binding
186  * @return checked restricted interaction or rejection
187  * @since 1.0.0
188  */
189 @CheckReturnValue public @NonNull OAuthAuthorizationResult resumeAuthorizationResult(@NonNull String interactionValue,@NonNull BrowserBinding browserBinding) {
190  return resumeAuthorizationResult(interactionValue,requireNonNull(browserBinding).toSecretString());
191 }
192 @CheckReturnValue @NonNull OAuthAuthorizationResult resumeAuthorizationResult(@NonNull String interactionValue,@NonNull String browserBinding) {
193  requireNonNull(interactionValue); requireNonNull(browserBinding);
194  return execute(AUTHORIZATION,d->{binding(interactionValue);binding(browserBinding);
195   return interaction(interactionValue,browserBinding,selected(interactionValue,browserBinding,d),d);
196  },r->OAuthAuthorizationResult.fromRejection(r,rejection(OAuthServerRequest.Endpoint.AUTHORIZATION,r,false)));
197 }
198 /** Completes app-protected consent once, with a fresh narrowing policy check before commit.
199  * @param interactionValue secret continuation
200  * @param browserBinding independent app-owned binding
201  * @param decision trusted server-side app decision
202  * @return retained committed redirect or rejection
203  * @since 1.0.0
204  */
205 @CheckReturnValue public @NonNull OAuthAuthorizationResult completeAuthorizationResult(@NonNull String interactionValue,@NonNull BrowserBinding browserBinding,@NonNull OAuthAuthorizationDecision decision) {
206  return completeAuthorizationResult(interactionValue,requireNonNull(browserBinding).toSecretString(),decision);
207 }
208 @CheckReturnValue @NonNull OAuthAuthorizationResult completeAuthorizationResult(@NonNull String interactionValue,@NonNull String browserBinding,@NonNull OAuthAuthorizationDecision decision) {
209  requireNonNull(interactionValue);requireNonNull(browserBinding);requireNonNull(decision);
210  return execute(AUTHORIZATION,d->{binding(interactionValue);binding(browserBinding);
211   return this.ledger.completeResult(interactionValue,browserBinding,()->selected(interactionValue,browserBinding,d),this.resources,decision,this.policy,this.authorizationEncoder,d);
212  },r->OAuthAuthorizationResult.fromRejection(r,rejection(OAuthServerRequest.Endpoint.AUTHORIZATION,r,false)));
213 }
214 /** Handles one bounded token form request on its configured route.
215  * @param httpMethod materialized method
216  * @param rawQuery original query or absence
217  * @param rawBody materialized body
218  * @param rawHeaderValues original names and every occurrence
219  * @return committed response or fixed local rejection
220  * @since 1.0.0
221  */
222 @CheckReturnValue public @NonNull OAuthTokenResult tokenResult(@NonNull String httpMethod,@Nullable String rawQuery,
223   byte @NonNull [] rawBody,@NonNull Map<@NonNull String,@NonNull List<@NonNull String>> rawHeaderValues) {
224  inputs(httpMethod,rawBody,rawHeaderValues);
225  boolean[] basic={false};
226  return execute(TOKEN,d->{
227   OAuthServerRequest request=parse(OAuthServerRequest.Endpoint.TOKEN,httpMethod,rawQuery,rawBody,rawHeaderValues);basic[0]=request.authorization()!=null;
228   String grant=request.required("grant_type");
229   OAuthTokenResponse response;
230   if(grant.equals("authorization_code")) response=this.codes.redeem(request,this.clients,this.resources,this.policy,d);
231   else if(grant.equals("refresh_token") && this.refresh) response=this.rotations.rotate(request,this.clients,this.resources,this.policy,d);
232   else throw OAuthServerValidationException.fromReason(UNSUPPORTED_GRANT_TYPE);
233   return OAuthTokenResult.fromSucceeded(response.response());
234  },r->OAuthTokenResult.fromRejection(r,rejection(OAuthServerRequest.Endpoint.TOKEN,r,basic[0])));
235 }
236 /** Handles one bounded revocation form request on its configured route.
237  * @param httpMethod materialized method
238  * @param rawQuery original query or absence
239  * @param rawBody materialized body
240  * @param rawHeaderValues original names and every occurrence
241  * @return committed response or fixed local rejection
242  * @since 1.0.0
243  */
244 @CheckReturnValue public @NonNull OAuthRevocationResult revokeResult(@NonNull String httpMethod,@Nullable String rawQuery,
245   byte @NonNull [] rawBody,@NonNull Map<@NonNull String,@NonNull List<@NonNull String>> rawHeaderValues) {
246  inputs(httpMethod,rawBody,rawHeaderValues);
247  if(this.revocationEndpoint==null) throw new IllegalStateException("The endpoint is disabled.");
248  boolean[] basic={false};
249  return execute(REVOCATION,d->{
250   OAuthServerRequest request=parse(OAuthServerRequest.Endpoint.REVOCATION,httpMethod,rawQuery,rawBody,rawHeaderValues);basic[0]=request.authorization()!=null;
251   return OAuthRevocationResult.fromSucceeded(this.revocation.revoke(request,this.clients,this.resources,this.keys,d).response());
252  },r->OAuthRevocationResult.fromRejection(r,rejection(OAuthServerRequest.Endpoint.REVOCATION,r,basic[0])));
253 }
254 /** Handles one bounded introspection form request on its configured route.
255  * @param httpMethod materialized method
256  * @param rawQuery original query or absence
257  * @param rawBody materialized body
258  * @param rawHeaderValues original names and every occurrence
259  * @return committed response or fixed local rejection
260  * @since 1.0.0
261  */
262 @CheckReturnValue public @NonNull OAuthIntrospectionResult introspectionResult(@NonNull String httpMethod,@Nullable String rawQuery,
263   byte @NonNull [] rawBody,@NonNull Map<@NonNull String,@NonNull List<@NonNull String>> rawHeaderValues) {
264  inputs(httpMethod,rawBody,rawHeaderValues);
265  if(this.introspectionEndpoint==null) throw new IllegalStateException("The endpoint is disabled.");
266  boolean[] basic={false};
267  return execute(INTROSPECTION,d->{
268   OAuthServerRequest request=parse(OAuthServerRequest.Endpoint.INTROSPECTION,httpMethod,rawQuery,rawBody,rawHeaderValues);basic[0]=request.authorization()!=null;
269   String resource=request.value("resource");
270   if(resource==null) { if(this.resources.size()!=1) throw OAuthServerValidationException.fromReason(INVALID_RESOURCE); resource=this.resources.keySet().iterator().next(); }
271   if(!this.resources.containsKey(resource)) throw OAuthServerValidationException.fromReason(INVALID_RESOURCE);
272   return OAuthIntrospectionResult.fromSucceeded(this.introspection.introspect(request,this.repository,resource,this.keys,d).response());
273  },r->OAuthIntrospectionResult.fromRejection(r,rejection(OAuthServerRequest.Endpoint.INTROSPECTION,r,basic[0])));
274 }
275 /**
276  * Validates local M5 signature/profile facts and uncached authoritative issuer status before releasing the
277  * checked token and its sensitive issuer-local grant management handle. The handle is constructed from the
278  * same access/grant snapshot only after the atomic status barrier commits; it is not a generic JWT claim.
279  * @param token unverified bearer credential
280  * @param resource exact configured application resource
281  * @return restricted checked proof plus grant handle, or fixed rejection
282  * @since 1.0.0
283  */
284 @CheckReturnValue public @NonNull OAuthIssuerAccessTokenResult validateAccessTokenResult(@NonNull BearerToken token,@NonNull String resource) {
285  requireNonNull(token);OAuthServerConfiguration.resource(resource);
286  if(!this.resources.containsKey(resource)) throw OAuthServerConfiguration.invalid();
287  return execute(ACCESS_TOKEN_VALIDATION,d->{
288   if(OidcTransactionAccess.get().bearerValue(token).length()>this.settings.maximumRequestBodyBytes) return OAuthIssuerAccessTokenResult.fromRejection(MALFORMED_REQUEST,null,null);
289   StaticJwksSource snapshot=this.keys.recognitionKeys(d);
290   com.revetsec.json.JsonObject claims;
291   try{claims=this.status.recognizeForProof(OidcTransactionAccess.get().bearerValue(token),resource,snapshot,d);}
292   catch(OAuthIssuerTokenStatus.RecognitionFailure rejected){return rejected.result();}
293   return this.status.validateProof(claims,resource,d,session->{
294    StaticJwksSource admittedKeys=this.keys.verificationKeys(d,session::authorityNow);
295    Clock authorityClock=Clock.fixed(session.effectiveNow(),java.time.ZoneOffset.UTC);
296    try {
297     OAuthServerClientAdmission.remaining(d);
298     JwtAccessTokenValidator validator=JwtAccessTokenValidator.withIssuer(this.issuer).jwksSource(admittedKeys).expectedAudiences(Set.of(resource))
299      .allowedAlgorithms(Set.of(JwsAlgorithm.RS256)).clock(authorityClock).clockSkew(this.settings.clockSkew)
300      .maximumTokenLength(Math.max(8192,this.settings.maximumRequestBodyBytes)).requestTimeout(Duration.ofSeconds(1)).totalDeadline(this.settings.totalDeadline).build();
301     VerifiedAccessToken proof=OidcTransactionAccess.get().validateAccessToken(validator,token,d);
302     return OAuthIssuerTokenStatus.PreparedProof.fromSucceeded(proof);
303    }catch(AccessTokenValidationException rejected){
304     OAuthServerClientAdmission.remaining(d);
305     return OAuthIssuerTokenStatus.PreparedProof.fromRejection(
306      OAuthIssuerAccessTokenResult.fromRejection(TOKEN_REVOKED,rejected.getReason(),rejected.getJoseReason().orElse(null)));
307    }
308   });
309  },r->OAuthIssuerAccessTokenResult.fromRejection(r,null,null));
310 }
311 /** Revokes a trusted grant reference monotonically.
312  * @param grantValue trusted management identity
313  * @since 1.0.0
314  */
315 public void revokeGrant(@NonNull String grantValue) { OAuthStoreFormat.nonce(grantValue);
316  execute(GRANT_REVOCATION,d->{this.revocation.revokeGrant(grantValue,d);return Boolean.TRUE;},r->{throw OAuthServerValidationException.fromReason(r);});
317 }
318 /** Advances an established subject fence; UNKNOWN requires reconciliation.
319  * @param subject trusted management identity
320  * @since 1.0.0
321  */
322 public void revokeSubject(@NonNull String subject) { OAuthServerConfiguration.text(subject,this.settings.maximumSubjectLength);
323  execute(SUBJECT_REVOCATION,d->{this.coordinator.revokeSubject(subject,d);return Boolean.TRUE;},r->{throw OAuthServerValidationException.fromReason(r);});
324 }
325 /** Advances the established issuer fence; UNKNOWN requires reconciliation.
326  * @since 1.0.0
327  */
328 public void revokeAllGrants() { 
329  execute(ISSUER_REVOCATION,d->{this.coordinator.revokeAll(d);return Boolean.TRUE;},r->{throw OAuthServerValidationException.fromReason(r);});
330 }
331 /** Explicitly registers a never-used subject; never use this to repair lost permanent fences.
332  * @param subject trusted management identity
333  * @since 1.0.0
334  */
335 public void establishNewSubject(@NonNull String subject) { OAuthServerConfiguration.text(subject,this.settings.maximumSubjectLength);
336  execute(SUBJECT_REGISTRATION,d->{this.coordinator.establishNewSubject(subject,d);return Boolean.TRUE;},r->{throw OAuthServerValidationException.fromReason(r);});
337 }
338 /** Explicitly initializes a namespace the operator knows has never been used or restored.
339  * Existing state yields CONFLICT. UNKNOWN never means ready; reconcile before traffic or retry.
340  * @return one authoritative initialization outcome
341  * @since 1.0.0
342  */
343 @CheckReturnValue public @NonNull OAuthStoreCommitReceipt initializeFreshIssuer() {
344  return execute(ISSUER_INITIALIZATION,this.coordinator::initializeFreshIssuerResult,r->{throw OAuthServerValidationException.fromReason(r);});
345 }
346 /** Attempts one authenticated reseal CAS without changing grant authority or retention.
347  * @param key privileged namespace-bound maintenance key
348  * @return the factual store outcome: COMMITTED, CONFLICT for absence/race/expired row, UNKNOWN
349  * requiring reconciliation, or another explicit refusal reported by the configured store
350  * @since 1.0.0
351  */
352 @CheckReturnValue public @NonNull OAuthStoreCommitReceipt resealStoreEntry(@NonNull OAuthStoreKey key) {
353  requireNonNull(key);
354  return execute(STORE_RESEAL,d->this.coordinator.reseal(key,d),r->{throw OAuthServerValidationException.fromReason(r);});
355 }
356 /** Prepares bounded public metadata for GET or HEAD.
357  * @param httpMethod exact method
358  * @return safe public response, including method rejection
359  * @throws OAuthServerConfigurationException if the configured representation exceeds publication capacity
360  * @since 1.0.0
361  */
362 @CheckReturnValue public @NonNull OAuthServerResponse metadataResponse(@NonNull String httpMethod) {
363  requireNonNull(httpMethod);
364  return execute(METADATA,d->this.metadata.metadata(httpMethod,d).response(),r->{throw OAuthServerValidationException.fromReason(r);});
365 }
366 /** Prepares bounded public json web key set for GET or HEAD.
367  * @param httpMethod exact method
368  * @return safe public response, including method rejection
369  * @throws OAuthServerConfigurationException if the configured representation exceeds publication capacity
370  * @since 1.0.0
371  */
372 @CheckReturnValue public @NonNull OAuthServerResponse jwksResponse(@NonNull String httpMethod) {
373  requireNonNull(httpMethod);
374  return execute(JWKS,d->this.metadata.jwks(httpMethod,this.keys,d).response(),r->{throw OAuthServerValidationException.fromReason(r);});
375 }
376 /** Translates a caught infrastructure exception to a fixed, bounded local503 response.
377  * @param failure restricted issuer failure
378  * @return safe response with no redirect or reflected descriptions
379  * @since 1.0.0
380  */
381 @CheckReturnValue public @NonNull OAuthServerResponse responseForFailure(@NonNull OAuthServerException failure) {
382  return OAuthServerFailureBoundary.failure(failure,this.settings.maximumResponseBodyBytes,this.settings.maximumHeaderBytes);
383 }
384 /** Checks configured signing keys and the established issuer fence on one shrinking caller budget.
385  * Never initializes missing state or fetches arbitrary client metadata.
386  * @since 1.0.0
387  */
388 public void warmUp() {
389  try { Deadline d=Deadline.fromNow(this.settings.totalDeadline);
390   for(int n=0;n<this.settings.maximumStoreCommitAttempts;n++){
391    OAuthStoreCoordinator.Session session=this.coordinator.begin(d);this.keys.warmUp(d,session::authorityNow);
392    if(session.barrier()==OAuthStoreCommitStatus.COMMITTED)return;
393   }
394   throw OAuthServerStoreException.fromReason(STORE_UNAVAILABLE,false);
395  } catch(OAuthStoreFailure f) {throw OAuthServerFailureBoundary.store(f);}
396  catch(OAuthServerAdmissionFailure f) {throw OAuthServerFailureBoundary.admission(f);}
397 }
398 /** Returns configured Issuer.
399  * @return exact setting or optional absence
400  * @since 1.0.0
401  */
402 @CheckReturnValue public @NonNull String getIssuer() {return this.issuer;}
403 /** Returns configured AuthorizationEndpoint.
404  * @return exact setting or optional absence
405  * @since 1.0.0
406  */
407 @CheckReturnValue public @NonNull URI getAuthorizationEndpoint() {return this.authorizationEndpoint;}
408 /** Returns configured TokenEndpoint.
409  * @return exact setting or optional absence
410  * @since 1.0.0
411  */
412 @CheckReturnValue public @NonNull URI getTokenEndpoint() {return this.tokenEndpoint;}
413 /** Returns configured JwksEndpoint.
414  * @return exact setting or optional absence
415  * @since 1.0.0
416  */
417 @CheckReturnValue public @NonNull URI getJwksEndpoint() {return this.jwksEndpoint;}
418 /** Returns configured RevocationEndpoint.
419  * @return exact setting or optional absence
420  * @since 1.0.0
421  */
422 @CheckReturnValue public @NonNull Optional<@NonNull URI> getRevocationEndpoint() {return Optional.ofNullable(this.revocationEndpoint);}
423 /** Returns configured IntrospectionEndpoint.
424  * @return exact setting or optional absence
425  * @since 1.0.0
426  */
427 @CheckReturnValue public @NonNull Optional<@NonNull URI> getIntrospectionEndpoint() {return Optional.ofNullable(this.introspectionEndpoint);}
428 /** Returns a fixed description without configuration or credentials.
429  * @return redacted description
430  * @since 1.0.0
431  */
432 @Override public @NonNull String toString() {return "OAuthAuthorizationServer{<redacted>}";}
433 private OAuthServerClientSelection.@NonNull Selected selected(@NonNull String interaction,@NonNull String browser,@NonNull Deadline d) {
434  return this.clients.authorization(this.ledger.clientId(interaction,browser,d),this.resources,d);
435 }
436 private @NonNull OAuthAuthorizationResult interaction(@NonNull String handle,@NonNull String browser,OAuthServerClientSelection.@NonNull Selected selected,@NonNull Deadline d) {
437  OAuthAuthorizationRecord record=this.ledger.resume(handle,browser,selected,d);
438  return OAuthAuthorizationResult.fromInteractionRequired(OAuthServerInteraction.fromRecord(handle,record,selected.client().getClientName().orElse(null),this.limits));
439 }
440 private static void binding(@NonNull String value) {
441  try {OAuthAuthorizationRecord.credentialDigest(value);} catch(IllegalArgumentException f) {throw OAuthServerValidationException.fromReason(MALFORMED_REQUEST);}
442 }
443 private static void inputs(@NonNull String method,byte @NonNull [] body,@NonNull Map<@NonNull String,@NonNull List<@NonNull String>> headers) {
444  requireNonNull(method);requireNonNull(body);requireNonNull(headers);
445 }
446 private @NonNull OAuthServerRequest parse(OAuthServerRequest.@NonNull Endpoint endpoint,@NonNull String method,@Nullable String query,
447   byte @NonNull [] body,@NonNull Map<@NonNull String,@NonNull List<@NonNull String>> headers) {
448  return OAuthServerRequest.parseForServer(endpoint,method,query,body,headers,this.limits);
449 }
450 private @NonNull OAuthServerResponse rejection(OAuthServerRequest.@NonNull Endpoint endpoint,OAuthServerException.@NonNull Reason reason,boolean basic) {
451  return OAuthServerFailureBoundary.rejection(endpoint,reason,basic,this.settings.maximumResponseBodyBytes,this.settings.maximumHeaderBytes);
452 }
453 private <T> @NonNull T execute(OAuthServerObserver.@NonNull Endpoint endpoint,@NonNull Function<@NonNull Deadline,@NonNull T> work,
454   @NonNull Function<OAuthServerException.@NonNull Reason,@NonNull T> reject) {
455  Deadline d=Deadline.fromNow(this.settings.totalDeadline);OAuthServerObservation observation=new OAuthServerObservation(this.observer,endpoint);
456  T result;
457  try (OAuthStoreCoordinator.Operation scope=this.coordinator.operation(d)) {
458  try {result=work.apply(d);}
459  catch(OAuthTransportException f) {rethrowEffect(scope,observation,false);OAuthServerException translated=OAuthServerStoreException.fromReason(STORE_UNAVAILABLE,true);observation.failed(translated);throw translated;}
460  catch(OAuthStoreFailure f) {rethrowEffect(scope,observation,false);OAuthServerException translated=OAuthServerFailureBoundary.store(f);observation.failed(translated);throw translated;}
461  catch(OAuthServerAdmissionFailure f) {
462   OAuthServerException translated=OAuthServerFailureBoundary.admission(f);
463   rethrowEffect(scope,observation,translated instanceof OAuthServerValidationException);
464   if(translated instanceof OAuthServerValidationException) result=rejectionResult(reject,translated.getReason(),observation);
465   else {observation.failed(translated);throw translated;}
466  }
467  catch(OAuthServerValidationException rejected) {rethrowEffect(scope,observation,true);result=rejectionResult(reject,rejected.getReason(),observation);}
468  catch(OAuthServerException f) {rethrowEffect(scope,observation,false);observation.failed(f);throw f;}
469  catch(IllegalArgumentException f) {rethrowEffect(scope,observation,true);result=rejectionResult(reject,MALFORMED_REQUEST,observation);}
470  try{scope.release();}catch(OAuthStoreFailure failure){OAuthServerException translated=OAuthServerFailureBoundary.store(failure);observation.failed(translated);throw translated;}
471  OAuthServerException.Reason rejected=reason(result);Integer statusCode=statusCode(result);
472  if(rejected==null) observation.succeeded(statusCode);else observation.rejected(rejected,statusCode);
473  try{scope.release();}catch(OAuthStoreFailure failure){throw OAuthServerFailureBoundary.store(failure);}
474  return result;
475  }
476 }
477 /** Throwing rejection adapters are non-HTTP management paths; finish before their fixed exception escapes. */
478 private static <T> @NonNull T rejectionResult(@NonNull Function<OAuthServerException.@NonNull Reason,@NonNull T> reject,
479   OAuthServerException.@NonNull Reason reason,@NonNull OAuthServerObservation observation){
480  try{return reject.apply(reason);}
481  catch(OAuthServerValidationException rejected){observation.rejected(rejected.getReason(),null);throw rejected;}
482 }
483 private static void rethrowEffect(OAuthStoreCoordinator.@NonNull Operation scope,@NonNull OAuthServerObservation observation,boolean rejection){
484  try{if(rejection)scope.rethrowRejectionEffect();else scope.rethrowEffect();}
485  catch(OAuthStoreFailure failure){OAuthServerException translated=OAuthServerFailureBoundary.store(failure);observation.failed(translated);throw translated;}
486 }
487 private static OAuthServerException.@Nullable Reason reason(@NonNull Object result) {
488  if(result instanceof OAuthAuthorizationResult.Rejected r) return r.getReason();
489  if(result instanceof OAuthAuthorizationResult.Denied) return ACCESS_DENIED;
490  if(result instanceof OAuthTokenResult.Rejected r) return r.getReason();
491  if(result instanceof OAuthRevocationResult.Rejected r) return r.getReason();
492  if(result instanceof OAuthIntrospectionResult.Rejected r) return r.getReason();
493  if(result instanceof OAuthIssuerAccessTokenResult.Rejected r) return r.getReason();
494  if(result instanceof OAuthServerResponse r && r.getStatusCode()==405) return METHOD_NOT_ALLOWED;
495  return null;
496 }
497 private static @Nullable Integer statusCode(@NonNull Object result) {
498  if(result instanceof OAuthAuthorizationResult.InteractionRequired) return 200;
499  if(result instanceof OAuthAuthorizationResult.Completed r) return r.getResponse().getStatusCode();
500  if(result instanceof OAuthAuthorizationResult.Denied r) return r.getResponse().getStatusCode();
501  if(result instanceof OAuthAuthorizationResult.Rejected r) return r.getResponse().getStatusCode();
502  if(result instanceof OAuthTokenResult.Succeeded r) return r.getResponse().getStatusCode();
503  if(result instanceof OAuthTokenResult.Rejected r) return r.getResponse().getStatusCode();
504  if(result instanceof OAuthRevocationResult.Succeeded r) return r.getResponse().getStatusCode();
505  if(result instanceof OAuthRevocationResult.Rejected r) return r.getResponse().getStatusCode();
506  if(result instanceof OAuthIntrospectionResult.Succeeded r) return r.getResponse().getStatusCode();
507  if(result instanceof OAuthIntrospectionResult.Rejected r) return r.getResponse().getStatusCode();
508  if(result instanceof OAuthServerResponse r) return r.getStatusCode();
509  return null;
510 }
511 private static <T> @NonNull T required(@Nullable T value) {
512  if(value==null) throw new IllegalStateException("Required authorization-server configuration is absent.");return value;
513 }
514 private static @NonNull URI endpoint(@NonNull URI uri,boolean insecure) {
515  OAuthServerConfiguration.text(uri.toString(),2048);
516  boolean loopback="http".equalsIgnoreCase(uri.getScheme()) && ("127.0.0.1".equals(uri.getHost()) || "[::1]".equals(uri.getHost()));
517  if(uri.isOpaque() || uri.getHost()==null || uri.getRawUserInfo()!=null || uri.getRawQuery()!=null || uri.getRawFragment()!=null
518    || uri.getPort()==0 || uri.getPort()>65535 || !("https".equalsIgnoreCase(uri.getScheme()) || (insecure && loopback))) throw OAuthServerConfiguration.invalid();
519  return uri;
520 }
521 private static void checkRoute(@NonNull URI issuer,@NonNull URI route,boolean insecure,@NonNull Set<@NonNull String> routes) {
522  endpoint(route,insecure);
523  if(!issuer.getScheme().equalsIgnoreCase(route.getScheme()) || !issuer.getRawAuthority().equals(route.getRawAuthority())
524    || !routes.add(route.toString())) throw OAuthServerConfiguration.invalid();
525 }
526 /**
527  * Mutable, non-thread-safe issuer configuration. Keep the builder on one configuring thread; each
528  * {@link #build()} snapshots its values so later setters do not change an already-built server.
529  * Application collaborators remain retained references and must satisfy their thread-safety, budget
530  * and lifetime contracts; the server does not copy or close them.
531  * <p>
532  * Required configuration has no inferred defaults: authorization, token and JWKS routes, client
533  * repository, authoritative store, signing-key provider, state sealer, grant policy and resource map.
534  * Null clears those required values. Revocation and introspection routes default absent; refresh
535  * defaults off and requires a revocation route when enabled. Collection setters replace complete
536  * values; {@link #resources(Map)} snapshots the map and its scope sets rather than merging them.
537  * <p>
538  * Numeric setters accept a nullable value and defer bounds to build. In addition to each documented
539  * inclusive interval, code lifetime must not exceed interaction lifetime; with refresh enabled,
540  * access lifetime must not exceed idle lifetime, which must not exceed absolute lifetime. Skew must
541  * not exceed half the access lifetime, request timeout must not exceed total deadline, and the sealed
542  * record cap must fit the sealer. Resource counts and scope limits are checked against the copied map.
543  * <p>
544  * Configuration and construction do not call the repository, store, signing-key provider, grant policy
545  * or address resolver, sample the worker clock, perform network I/O/signing, or start owned threads.
546  * The explicit construction-time observer exception is
547  * {@link OAuthServerObserver#didEnableLocalhostAnyPortRedirects()} when that option is enabled.
548  * Build neither initializes persistence nor opens serving/recovery admission. The application owns
549  * trusted startup time, durable store qualification, keys, user authentication, consent, sessions/CSRF
550  * and HTTP routing. Construction success does not qualify that deployment.
551  * @since 1.0.0
552  */
553 @NotThreadSafe @CheckReturnValue
554 public static final class Builder {
555  private final @NonNull String issuer;
556  private @Nullable URI authorizationEndpoint,tokenEndpoint,jwksEndpoint,revocationEndpoint,introspectionEndpoint;
557  private @Nullable OAuthServerClientRepository clientRepository;
558  private @Nullable OAuthAuthorizationServerStore store;
559  private @Nullable OAuthIssuerKeyProvider signingKeys;
560  private @Nullable StateSealer stateSealer;
561  private @Nullable OAuthGrantPolicy grantPolicy;
562  private @Nullable Map<@NonNull String,@NonNull Set<@NonNull String>> resources;
563  private @NonNull OAuthClientMetadataPolicy clientMetadataPolicy=OAuthClientMetadataPolicy.disabledInstance();
564  private OAuthClientMetadataFetcher.@Nullable Transport clientMetadataTransport;
565  private @NonNull Clock clock=Clock.systemUTC();
566  private @NonNull OutboundUriPolicy outboundUriPolicy=OutboundUriPolicy.publicAddressesOnlyInstance();
567  private @NonNull OAuthServerObserver observer=OAuthServerObserver.disabledInstance();
568  private boolean refreshTokensEnabled,allowInsecureLoopback,allowNativeLoopbackRedirects,allowLocalhostRedirects,allowLocalhostAnyPortRedirects,acknowledgeUnpatchedRuntime;
569  private final OAuthServerSettings.@NonNull Builder settings=OAuthServerSettings.builder();
570  private Builder(@NonNull String issuer) {this.issuer=endpoint(URI.create(requireNonNull(issuer)),true).toString();}
571  @CheckReturnValue @NonNull Builder clientMetadataTransport(OAuthClientMetadataFetcher.@NonNull Transport value) {
572   this.clientMetadataTransport=requireNonNull(value);return this;
573  }
574  /**
575   * Sets the required browser authorization route; there is no default.
576   * Null clears the required route, so the next build fails until it is supplied again.
577   * The route must use the issuer's scheme and exact raw authority, be distinct from every other configured
578   * route, and contain no user info, query or fragment. It is not inferred from the issuer or request headers.
579   * These checks run at {@link #build()}; the application owns HTTP routing and TLS termination.
580   * @param value the exact absolute endpoint URI, or null to clear it
581   * @return this builder
582   * @since 1.0.0
583   */
584  @CheckReturnValue public @NonNull Builder authorizationEndpoint(@Nullable URI value) {this.authorizationEndpoint=value;return this;}
585  /**
586   * Sets the required code-exchange and refresh token route; there is no default.
587   * Null clears the required route, so the next build fails until it is supplied again.
588   * The route must use the issuer's scheme and exact raw authority, be distinct from every other configured
589   * route, and contain no user info, query or fragment. It is not inferred from the issuer or request headers.
590   * These checks run at {@link #build()}; the application owns HTTP routing and TLS termination.
591   * @param value the exact absolute endpoint URI, or null to clear it
592   * @return this builder
593   * @since 1.0.0
594   */
595  @CheckReturnValue public @NonNull Builder tokenEndpoint(@Nullable URI value) {this.tokenEndpoint=value;return this;}
596  /**
597   * Sets the required public verification-key publication route; there is no default.
598   * Null clears the required route, so the next build fails until it is supplied again.
599   * The route must use the issuer's scheme and exact raw authority, be distinct from every other configured
600   * route, and contain no user info, query or fragment. It is not inferred from the issuer or request headers.
601   * These checks run at {@link #build()}; the application owns HTTP routing and TLS termination.
602   * @param value the exact absolute endpoint URI, or null to clear it
603   * @return this builder
604   * @since 1.0.0
605   */
606  @CheckReturnValue public @NonNull Builder jwksEndpoint(@Nullable URI value) {this.jwksEndpoint=value;return this;}
607  /**
608   * Sets the optional token-revocation route; the default and null mean absent.
609   * A route is required when {@link #refreshTokensEnabled(Boolean)} is true. Without it, revocation is
610   * not advertised and the public revocation operation is unavailable; null does not select another route.
611   * The route must use the issuer's scheme and exact raw authority, be distinct from every other configured
612   * route, and contain no user info, query or fragment. It is not inferred from the issuer or request headers.
613   * These checks run at {@link #build()}; the application owns HTTP routing and TLS termination.
614   * @param value the exact absolute revocation URI, or null for no route
615   * @return this builder
616   * @since 1.0.0
617   */
618  @CheckReturnValue public @NonNull Builder revocationEndpoint(@Nullable URI value) {this.revocationEndpoint=value;return this;}
619  /**
620   * Sets the optional resource-only introspection route; the default and null mean absent.
621   * Without it, introspection is not advertised and the public introspection operation is unavailable.
622   * The route must use the issuer's scheme and exact raw authority, be distinct from every other configured
623   * route, and contain no user info, query or fragment. It is not inferred from the issuer or request headers.
624   * These checks run at {@link #build()}; the application owns HTTP routing and TLS termination.
625   * @param value the exact absolute introspection URI, or null for no route
626   * @return this builder
627   * @since 1.0.0
628   */
629  @CheckReturnValue public @NonNull Builder introspectionEndpoint(@Nullable URI value) {this.introspectionEndpoint=value;return this;}
630  /**
631   * Sets the required application-owned registered-client lookup; there is no default.
632   * Null clears it and makes the next build fail. The reference is retained, not copied or called during
633   * construction. It must be thread-safe and honor each operation's remaining cooperative budget.
634   * Exact registrations are consulted before opt-in client-ID metadata; a backend failure must not be
635   * reported as an unknown client. See {@link OAuthServerClientRepository}.
636   * @param value the registered-client repository, or null to clear it
637   * @return this builder
638   * @since 1.0.0
639   */
640  @CheckReturnValue public @NonNull Builder clientRepository(@Nullable OAuthServerClientRepository value) {this.clientRepository=value;return this;}
641  /**
642   * Sets the required application-owned authoritative store; there is no default.
643   * Null clears it and makes the next build fail. The reference is retained without reading, writing or
644   * initializing a namespace during construction. The implementation must supply the coherent admitted
645   * time, atomic exact predicates, durability, recovery admission and permanent/replay retention required
646   * by {@link OAuthAuthorizationServerStore}; this setter supplies none of those deployment guarantees.
647   * @param value the authoritative issuer store, or null to clear it
648   * @return this builder
649   * @since 1.0.0
650   */
651  @CheckReturnValue public @NonNull Builder store(@Nullable OAuthAuthorizationServerStore value) {this.store=value;return this;}
652  /**
653   * Sets the required application-owned signing-key snapshot provider; there is no default.
654   * Null clears it and makes the next build fail. Construction retains the provider without invoking it,
655   * looking up keys or signing. Operations require coherent lifecycle snapshots and the issuer's RS256
656   * profile. The application owns private-key protection, publication, rollover and retirement; changing
657   * the provider reference is not a key-migration or retention procedure. See {@link OAuthIssuerKeyProvider}.
658   * @param value the signing-key provider, or null to clear it
659   * @return this builder
660   * @since 1.0.0
661   */
662  @CheckReturnValue public @NonNull Builder signingKeys(@Nullable OAuthIssuerKeyProvider value) {this.signingKeys=value;return this;}
663  /**
664   * Sets the required application-owned state sealer; there is no default.
665   * Null clears it and makes the next build fail. The immutable sealer reference is retained. At build,
666   * {@link #maximumStoreRecordBytes(Integer)} must not exceed its configured maximum sealed length.
667   * Sealing keys, old-key retention and coordinated rotation across writers remain application-owned;
668   * replacing the sealer does not migrate stored records or repair missing fences.
669   * @param value the configured state sealer, or null to clear it
670   * @return this builder
671   * @since 1.0.0
672   */
673  @CheckReturnValue public @NonNull Builder stateSealer(@Nullable StateSealer value) {this.stateSealer=value;return this;}
674  /**
675   * Sets the required application-owned continuing authorization policy; there is no default.
676   * Null clears it and makes the next build fail. Construction retains the thread-safe callback without
677   * invoking it. Approval, code exchange and refresh recheck current permissions under the remaining
678   * cooperative budget. A decision can deny or narrow authority; it cannot replace application login,
679   * session/CSRF protection or consent. See {@link OAuthGrantPolicy}.
680   * @param value the continuing grant policy, or null to clear it
681   * @return this builder
682   * @since 1.0.0
683   */
684  @CheckReturnValue public @NonNull Builder grantPolicy(@Nullable OAuthGrantPolicy value) {this.grantPolicy=value;return this;}
685  /**
686   * Replaces the required complete map of exact resource identifiers to allowed scope sets.
687   * There is no default; null clears the required map. Non-null maps and their scope sets are validated
688   * and defensively copied when set, rather than merged or retained. Resource identifiers are absolute,
689   * fragment-free URI spellings compared exactly and never fetched. The map must be nonempty; an empty
690   * scope set grants no authority. Carrier/aggregate ceilings are checked here; the selected
691   * {@link #maximumResources(Integer)}, {@link #maximumScopesPerResource(Integer)} and
692   * {@link #maximumScopeLength(Integer)} are checked at build. Per-client and grant policy can only narrow
693   * this configuration.
694   * @param value the complete resource/scope map, or null to clear it
695   * @return this builder
696   * @throws IllegalArgumentException if the non-null replacement violates resource/scope carrier limits
697   * @throws NullPointerException if a non-null map contains a null key, scope set or scope
698   * @since 1.0.0
699   */
700  @CheckReturnValue public @NonNull Builder resources(@Nullable Map<@NonNull String,@NonNull Set<@NonNull String>> value) {this.resources=value==null ? null : OAuthServerConfiguration.resources(value,1024);return this;}
701  /**
702   * Selects opt-in client-ID metadata document (CIMD) policy.
703   * The default and null are {@link OAuthClientMetadataPolicy#disabledInstance()}; null disables CIMD,
704   * not registered clients. An enabled immutable policy retains its application resolver and explicit
705   * cache selection. Construction performs no resolution, cache access or HTTP fetch. Enabled CIMD
706   * requires the runtime floor described by {@link #acknowledgeUnpatchedRuntime(Boolean)} and uses
707   * {@link #outboundUriPolicy(OutboundUriPolicy)}. Cache reuse is not authoritative credential storage
708   * or shared-deployment qualification. Exact registered clients still take precedence.
709   * @param value the complete metadata policy, or null to disable CIMD
710   * @return this builder
711   * @since 1.0.0
712   */
713  @CheckReturnValue public @NonNull Builder clientMetadataPolicy(@Nullable OAuthClientMetadataPolicy value) {this.clientMetadataPolicy=value==null ? OAuthClientMetadataPolicy.disabledInstance() : value;return this;}
714  /**
715   * Sets the worker wall clock; the default and null select {@link Clock#systemUTC()}.
716   * The reference is retained without sampling it during construction. Operations use it for worker
717   * health checks, provisional key-lifecycle preparation and optional metadata-cache freshness. Timed
718   * authoritative state transitions use admitted store time and authenticated floors, not this clock as
719   * a fallback. Changing this clock neither establishes trusted startup time nor resets durable floors.
720   * @param value the application worker clock, or null to restore the system UTC clock
721   * @return this builder
722   * @since 1.0.0
723   */
724  @CheckReturnValue public @NonNull Builder clock(@Nullable Clock value) {this.clock=value==null ? Clock.systemUTC() : value;return this;}
725  /**
726   * Selects the immutable outbound URI policy for opt-in CIMD address admission.
727   * The default and null select {@link OutboundUriPolicy#publicAddressesOnlyInstance()}. This is a
728   * restriction on approved metadata requests, not permission to fetch arbitrary client URLs. The pinned
729   * transport still enforces its address, redirect and TLS/hostname rules. This setting does not change
730   * issuer endpoint authority or any of the separate redirect/loopback options.
731   * @param value the outbound metadata URI policy, or null to restore the public-address policy
732   * @return this builder
733   * @since 1.0.0
734   */
735  @CheckReturnValue public @NonNull Builder outboundUriPolicy(@Nullable OutboundUriPolicy value) {this.outboundUriPolicy=value==null ? OutboundUriPolicy.publicAddressesOnlyInstance() : value;return this;}
736  /**
737   * Sets the application-owned synchronous issuer observer.
738   * The default and null select {@link OAuthServerObserver#disabledInstance()}. The reference is retained;
739   * hooks must be fast and thread-safe and follow the interface's failure-containment contract. Successful
740   * construction with {@link #allowLocalhostAnyPortRedirects(Boolean)} enabled calls
741   * {@link OAuthServerObserver#didEnableLocalhostAnyPortRedirects()}; construction otherwise performs no
742   * issuer observer notification. This interface has no runtime-acknowledgment hook, and operation success
743   * events are checkpoints rather than credential-delivery receipts.
744   * @param value the issuer observer, or null to restore the disabled observer
745   * @return this builder
746   * @since 1.0.0
747   */
748  @CheckReturnValue public @NonNull Builder observer(@Nullable OAuthServerObserver value) {this.observer=value==null ? OAuthServerObserver.disabledInstance() : value;return this;}
749  /**
750   * Enables server-side refresh-token issuance and rotation; the default is false.
751   * False or null disables refresh. Enabling it requires a configured {@link #revocationEndpoint(URI)}
752   * at build and per-client and current grant-policy refresh permission at operation time. It does not
753   * override either permission or extend an existing family's pinned lifetime. With refresh enabled,
754   * access lifetime must not exceed refresh idle lifetime, which must not exceed refresh absolute lifetime.
755   * @param value true to enable refresh; false or null to disable it
756   * @return this builder
757   * @since 1.0.0
758   */
759  @CheckReturnValue public @NonNull Builder refreshTokensEnabled(@Nullable Boolean value) {this.refreshTokensEnabled=Boolean.TRUE.equals(value);return this;}
760  /**
761   * Permits a numeric HTTP loopback issuer and its same-authority server routes for local development.
762   * The default is false; false or null restores HTTPS-only issuer routes. The HTTP host must be exactly
763   * {@code 127.0.0.1} or {@code [::1]}, not {@code localhost}. This option neither admits client redirects
764   * nor enables the other loopback options, and it does not weaken CIMD transport or token validation.
765   * @param value true to allow numeric HTTP loopback issuer routes; false or null to disable
766   * @return this builder
767   * @since 1.0.0
768   */
769  @CheckReturnValue public @NonNull Builder allowInsecureLoopback(@Nullable Boolean value) {this.allowInsecureLoopback=Boolean.TRUE.equals(value);return this;}
770  /**
771   * Enables HTTP IP-loopback client redirects with the native port exception; the default is false.
772   * False or null disables the exception. Literal {@code 127.0.0.1} or {@code [::1]} redirects may vary
773   * the port while retaining the other checked components; code redemption must use the actual admitted
774   * redirect. CIMD uses this explicit policy regardless of its {@code application_type} declaration.
775   * It does not enable HTTP issuer routes or localhost redirects; see
776   * {@link #allowInsecureLoopback(Boolean)}, {@link #allowLocalhostRedirects(Boolean)} and
777   * {@link #allowLocalhostAnyPortRedirects(Boolean)}.
778   * @param value true to enable the IP-loopback redirect port exception; false or null to disable
779   * @return this builder
780   * @since 1.0.0
781   */
782  @CheckReturnValue public @NonNull Builder allowNativeLoopbackRedirects(@Nullable Boolean value) {this.allowNativeLoopbackRedirects=Boolean.TRUE.equals(value);return this;}
783  /**
784   * Enables exact HTTP localhost client redirects; the default is false.
785   * False or null disables this profile. Every component, including the configured port spelling, stays
786   * exact. This does not enable numeric-loopback redirects, an HTTP issuer, or port-less any-port matching;
787   * the latter requires {@link #allowLocalhostAnyPortRedirects(Boolean)} separately.
788   * @param value true to enable exact HTTP localhost redirects; false or null to disable
789   * @return this builder
790   * @since 1.0.0
791   */
792  @CheckReturnValue public @NonNull Builder allowLocalhostRedirects(@Nullable Boolean value) {this.allowLocalhostRedirects=Boolean.TRUE.equals(value);return this;}
793  /**
794   * Enables any-port matching for port-less HTTP localhost client registrations; the default is false.
795   * False or null disables it. The registered authority must be exactly {@code localhost}; scheme, host,
796   * raw path and query stay exact. Fixed-port registrations still require
797   * {@link #allowLocalhostRedirects(Boolean)} and remain exact. No other loopback option is implied.
798   * Code redemption requires the actual admitted redirect. A successful build emits
799   * {@link OAuthServerObserver#didEnableLocalhostAnyPortRedirects()}, and an authorization operation that
800   * relies on this exception emits {@link OAuthServerObserver#didUseLocalhostAnyPortRedirects()} even if
801   * a later check rejects it. Exact matches under the separate exact-localhost profile do not use it.
802   * @param value true to enable port-less localhost any-port matching; false or null to disable
803   * @return this builder
804   * @since 1.0.0
805   */
806  @CheckReturnValue public @NonNull Builder allowLocalhostAnyPortRedirects(@Nullable Boolean value) {this.allowLocalhostAnyPortRedirects=Boolean.TRUE.equals(value);return this;}
807  /**
808   * Acknowledges the runtime TLS risk when opt-in CIMD requires network access; the default is false.
809   * False or null restores refusal on runtimes below 17.0.3 on Java 17 or 18.0.1 on Java 18. The guard is
810   * checked at build only when {@link #clientMetadataPolicy(OAuthClientMetadataPolicy)} enables CIMD;
811   * Java 19 and later pass this guard. The flag does not patch TLS or alter signature, claim, address or
812   * peer-verification policy. The issuer observer has no acknowledgment event. With CIMD disabled it has
813   * no runtime-floor effect on issuer construction.
814   * @param value true to accept the runtime risk for CIMD; false or null to restore refusal
815   * @return this builder
816   * @since 1.0.0
817   */
818  @CheckReturnValue public @NonNull Builder acknowledgeUnpatchedRuntime(@Nullable Boolean value) {this.acknowledgeUnpatchedRuntime=Boolean.TRUE.equals(value);return this;}
819  /**
820   * Sets the maximum lifetime of a browser-bound authorization interaction.
821   * Default: 15 minutes; inclusive range: 1 minute through 1 hour. Null restores the default.
822   * Bounds and combined constraints are checked by {@link #build()}, not by this setter.
823   * Authorization-code lifetime must not exceed this lifetime.
824   * @param value the setting in duration units, or null to restore the default
825   * @return this builder
826   * @since 1.0.0
827   */
828  @CheckReturnValue public @NonNull Builder authorizationInteractionLifetime(@Nullable Duration value) {this.settings.authorizationInteractionLifetime(value);return this;}
829  /**
830   * Sets the lifetime of a one-use authorization code.
831   * Default: 2 minutes; inclusive range: 30 seconds through 10 minutes. Null restores the default.
832   * Bounds and combined constraints are checked by {@link #build()}, not by this setter.
833   * Must not exceed {@link #authorizationInteractionLifetime(Duration)}; a longer code policy does not revive an expired or consumed code.
834   * @param value the setting in duration units, or null to restore the default
835   * @return this builder
836   * @since 1.0.0
837   */
838  @CheckReturnValue public @NonNull Builder authorizationCodeLifetime(@Nullable Duration value) {this.settings.authorizationCodeLifetime(value);return this;}
839  /**
840   * Sets the maximum issued access-token lifetime.
841   * Default: 5 minutes; inclusive range: 30 seconds through 15 minutes. Null restores the default.
842   * Bounds and combined constraints are checked by {@link #build()}, not by this setter.
843   * With refresh enabled, must not exceed refresh idle lifetime; clock skew must not exceed half this value. Existing families keep their pinned maximum. Raising this value beyond a family pin causes its next refresh to revoke it rather than enlarge the pin.
844   * @param value the setting in duration units, or null to restore the default
845   * @return this builder
846   * @since 1.0.0
847   */
848  @CheckReturnValue public @NonNull Builder accessTokenLifetime(@Nullable Duration value) {this.settings.accessTokenLifetime(value);return this;}
849  /**
850   * Sets the refresh-family idle lifetime used for initial issuance and rotation.
851   * Default: 24 hours; inclusive range: 5 minutes through 7 days. Null restores the default.
852   * Bounds and combined constraints are checked by {@link #build()}, not by this setter.
853   * When refresh is enabled, access lifetime must not exceed this value, which must not exceed refresh absolute lifetime. Existing families retain their original idle-lifetime pin; increasing this setting does not extend it.
854   * @param value the setting in duration units, or null to restore the default
855   * @return this builder
856   * @since 1.0.0
857   */
858  @CheckReturnValue public @NonNull Builder refreshTokenIdleLifetime(@Nullable Duration value) {this.settings.refreshTokenIdleLifetime(value);return this;}
859  /**
860   * Sets the refresh-family absolute lifetime at initial issuance.
861   * Default: 7 days; inclusive range: 1 hour through 30 days. Null restores the default.
862   * Bounds and combined constraints are checked by {@link #build()}, not by this setter.
863   * With refresh enabled, must be at least refresh idle lifetime. Rotation does not reset the original family absolute expiry, and later configuration does not extend it.
864   * @param value the setting in duration units, or null to restore the default
865   * @return this builder
866   * @since 1.0.0
867   */
868  @CheckReturnValue public @NonNull Builder refreshTokenAbsoluteLifetime(@Nullable Duration value) {this.settings.refreshTokenAbsoluteLifetime(value);return this;}
869  /**
870   * Sets issuer JWT-validation skew and its contribution to physical retention.
871   * Default: 30 seconds; inclusive range: zero through 60 seconds. Null restores the default.
872   * Bounds and combined constraints are checked by {@link #build()}, not by this setter.
873   * Must not exceed half the access-token lifetime. This does not reserve durable clock time or advance entity floors; authoritative temporal predicates use admitted store time. Together with total deadline and public metadata cache age it contributes to retained grant horizons. A combined policy beyond a stored family horizon causes its next refresh to revoke it; coordinate revocation and new authorization across nodes.
874   * @param value the setting in duration units, or null to restore the default
875   * @return this builder
876   * @since 1.0.0
877   */
878  @CheckReturnValue public @NonNull Builder clockSkew(@Nullable Duration value) {this.settings.clockSkew(value);return this;}
879  /**
880   * Sets the original monotonic budget for a public issuer operation.
881   * Default: 10 seconds; inclusive range: 1 second through 60 seconds. Null restores the default.
882   * Bounds and combined constraints are checked by {@link #build()}, not by this setter.
883   * Preparation, callbacks, contention retries, store work and final admission share this budget; retries do not restart it. Request timeout must not exceed it. Synchronous application callbacks must cooperate because the library cannot forcibly preempt them. It also contributes to the retention margin described by {@link #clockSkew(Duration)}.
884   * @param value the setting in duration units, or null to restore the default
885   * @return this builder
886   * @since 1.0.0
887   */
888  @CheckReturnValue public @NonNull Builder totalDeadline(@Nullable Duration value) {this.settings.totalDeadline(value);return this;}
889  /**
890   * Sets the per-request timeout for outbound CIMD HTTP work.
891   * Default: 5 seconds; inclusive range: 1 second through 30 seconds. Null restores the default.
892   * Bounds and combined constraints are checked by {@link #build()}, not by this setter.
893   * Must not exceed {@link #totalDeadline(Duration)}; the original remaining operation budget can shorten a request further. This does not set the host application HTTP-server timeout or preempt arbitrary application callbacks.
894   * @param value the setting in duration units, or null to restore the default
895   * @return this builder
896   * @since 1.0.0
897   */
898  @CheckReturnValue public @NonNull Builder requestTimeout(@Nullable Duration value) {this.settings.requestTimeout(value);return this;}
899  /**
900   * Sets the HTTP Cache-Control max-age for public issuer metadata and JWKS responses.
901   * Default: 60 seconds; inclusive range: zero through 5 minutes. Null restores the default.
902   * Bounds and combined constraints are checked by {@link #build()}, not by this setter.
903   * The header uses whole seconds from {@link Duration#toSeconds()}, while the full configured duration governs new-key publication wait and contributes to grant/verification-key retention. A combined policy beyond an existing family horizon causes its next refresh to revoke it; coordinate revocation and new authorization when changing this policy.
904   * @param value the setting in duration units, or null to restore the default
905   * @return this builder
906   * @since 1.0.0
907   */
908  @CheckReturnValue public @NonNull Builder publicMetadataHttpCacheMaxAge(@Nullable Duration value) {this.settings.publicMetadataHttpCacheMaxAge(value);return this;}
909  /**
910   * Sets the maximum admitted materialized endpoint request-body size in bytes.
911   * Default: 16384 bytes; inclusive range: 1024 bytes through 65536 bytes. Null restores the default.
912   * Bounds and combined constraints are checked by {@link #build()}, not by this setter.
913   * This is a library admission bound, not permission for a transport adapter or host server to allocate an unbounded body before calling the issuer. Query, header, token and result bounds still apply separately.
914   * @param value the setting in the units described above, or null to restore the default
915   * @return this builder
916   * @since 1.0.0
917   */
918  @CheckReturnValue public @NonNull Builder maximumRequestBodyBytes(@Nullable Integer value) {this.settings.maximumRequestBodyBytes(value);return this;}
919  /**
920   * Sets the maximum raw query length in UTF-16 code units before form decoding.
921   * Default: 16384 code units; inclusive range: 1024 code units through 65536 code units. Null restores the default.
922   * Bounds and combined constraints are checked by {@link #build()}, not by this setter.
923   * Encoded spelling consumes this budget separately from the decoded state/client/scope limits. The host must also bound acquisition of the original query.
924   * @param value the setting in the units described above, or null to restore the default
925   * @return this builder
926   * @since 1.0.0
927   */
928  @CheckReturnValue public @NonNull Builder maximumRawQueryLength(@Nullable Integer value) {this.settings.maximumRawQueryLength(value);return this;}
929  /**
930   * Sets the aggregate request-header and prepared response-header budget in bytes.
931   * Default: 16384 bytes; inclusive range: 1024 bytes through 65536 bytes. Null restores the default.
932   * Bounds and combined constraints are checked by {@link #build()}, not by this setter.
933   * Admitted request names, values and framing are charged together; separate header-name/occurrence caps and duplicate-security-header rules remain. This does not change the container or adapter read limits.
934   * @param value the setting in the units described above, or null to restore the default
935   * @return this builder
936   * @since 1.0.0
937   */
938  @CheckReturnValue public @NonNull Builder maximumHeaderBytes(@Nullable Integer value) {this.settings.maximumHeaderBytes(value);return this;}
939  /**
940   * Sets the maximum prepared issuer response-body size in bytes.
941   * Default: 32768 bytes; inclusive range: 4096 bytes through 131072 bytes. Null restores the default.
942   * Bounds and combined constraints are checked by {@link #build()}, not by this setter.
943   * Responses are bounded before credential-bearing output or the relevant transition is committed. Request/header/store budgets remain separate; a valid grant need not fit every smaller response policy.
944   * @param value the setting in the units described above, or null to restore the default
945   * @return this builder
946   * @since 1.0.0
947   */
948  @CheckReturnValue public @NonNull Builder maximumResponseBodyBytes(@Nullable Integer value) {this.settings.maximumResponseBodyBytes(value);return this;}
949  /**
950   * Sets the maximum ASCII sealed store-record size in bytes, not plaintext payload size.
951   * Default: 3800 bytes; inclusive range: 1024 bytes through 16384 bytes. Null restores the default.
952   * Bounds and combined constraints are checked by {@link #build()}, not by this setter.
953   * Must not exceed the configured {@link #stateSealer(StateSealer)} maximum sealed length. Envelope, authentication and encoding overhead reduce usable payload capacity. Raising another admission limit does not prove a resulting record fits; this setter neither enlarges the sealer nor migrates existing records.
954   * @param value the setting in the units described above, or null to restore the default
955   * @return this builder
956   * @since 1.0.0
957   */
958  @CheckReturnValue public @NonNull Builder maximumStoreRecordBytes(@Nullable Integer value) {this.settings.maximumStoreRecordBytes(value);return this;}
959  /**
960   * Sets the maximum attempts for bounded store-conflict retry loops.
961   * Default: 3 attempts; inclusive range: 1 attempt through 8 attempts. Null restores the default.
962   * Bounds and combined constraints are checked by {@link #build()}, not by this setter.
963   * Attempts share the original total deadline; this is not a global cap on every store callback in a composite operation. Only a definite zero-effect conflict permits retry. Unknown mutation outcomes and confirmed commitments requiring reconciliation stop automatic retry.
964   * @param value the setting in the units described above, or null to restore the default
965   * @return this builder
966   * @since 1.0.0
967   */
968  @CheckReturnValue public @NonNull Builder maximumStoreCommitAttempts(@Nullable Integer value) {this.settings.maximumStoreCommitAttempts(value);return this;}
969  /**
970   * Sets the maximum resource entries accepted by configured issuer resource maps and client admission.
971   * Default: 64 resources; inclusive range: 1 resource through 1024 resources. Null restores the default.
972   * Bounds and combined constraints are checked by {@link #build()}, not by this setter.
973   * The configured server map is checked at build; client maps are checked when selected. It is a count bound, not a collection of wildcard audiences or permission to fetch resource identifiers.
974   * @param value the setting in the units described above, or null to restore the default
975   * @return this builder
976   * @since 1.0.0
977   */
978  @CheckReturnValue public @NonNull Builder maximumResources(@Nullable Integer value) {this.settings.maximumResources(value);return this;}
979  /**
980   * Sets the maximum redirect registrations accepted from a selected client.
981   * Default: 32 redirects; inclusive range: 1 redirect through 64 redirects. Null restores the default.
982   * Bounds and combined constraints are checked by {@link #build()}, not by this setter.
983   * Selection applies this bound without changing exact redirect validation or the separately opted-in loopback profiles. Build does not fetch clients to pre-validate their registrations.
984   * @param value the setting in the units described above, or null to restore the default
985   * @return this builder
986   * @since 1.0.0
987   */
988  @CheckReturnValue public @NonNull Builder maximumRedirectUris(@Nullable Integer value) {this.settings.maximumRedirectUris(value);return this;}
989  /**
990   * Sets the maximum scope count per resource in issuer configuration and client admission.
991   * Default: 32 scopes; inclusive range: 1 scope through 128 scopes. Null restores the default.
992   * Bounds and combined constraints are checked by {@link #build()}, not by this setter.
993   * The server resource map is checked at build and selected clients at admission. This does not grant a scope absent from the client/server intersection or current grant policy.
994   * @param value the setting in the units described above, or null to restore the default
995   * @return this builder
996   * @since 1.0.0
997   */
998  @CheckReturnValue public @NonNull Builder maximumScopesPerResource(@Nullable Integer value) {this.settings.maximumScopesPerResource(value);return this;}
999  /**
1000   * Sets the maximum length of each ASCII scope token.
1001   * Default: 128 characters; inclusive range: 1 character through 128 characters. Null restores the default.
1002   * Bounds and combined constraints are checked by {@link #build()}, not by this setter.
1003   * The scope grammar remains strict; changing a length bound does not admit whitespace, quotes or backslashes or widen granted scopes.
1004   * @param value the setting in the units described above, or null to restore the default
1005   * @return this builder
1006   * @since 1.0.0
1007   */
1008  @CheckReturnValue public @NonNull Builder maximumScopeLength(@Nullable Integer value) {this.settings.maximumScopeLength(value);return this;}
1009  /**
1010   * Sets the maximum decoded authorization state length in UTF-16 code units.
1011   * Default: 1024 code units; inclusive range: 128 code units through 4096 code units. Null restores the default.
1012   * Bounds and combined constraints are checked by {@link #build()}, not by this setter.
1013   * Raw query/body and encoded redirect/response budgets still apply separately. State is reflected only after the request and registered redirect are admitted; it is not application session or CSRF authentication.
1014   * @param value the setting in the units described above, or null to restore the default
1015   * @return this builder
1016   * @since 1.0.0
1017   */
1018  @CheckReturnValue public @NonNull Builder maximumStateLength(@Nullable Integer value) {this.settings.maximumStateLength(value);return this;}
1019  /**
1020   * Sets the maximum client-identifier length in UTF-16 code units at issuer ingress.
1021   * Default: 2048 code units; inclusive range: 256 code units through 4096 code units. Null restores the default.
1022   * Bounds and combined constraints are checked by {@link #build()}, not by this setter.
1023   * Exact registered and CIMD identifiers remain subject to their profile and aggregate request limits. This bound does not normalize client identifiers or authorize metadata fetching.
1024   * @param value the setting in the units described above, or null to restore the default
1025   * @return this builder
1026   * @since 1.0.0
1027   */
1028  @CheckReturnValue public @NonNull Builder maximumClientIdLength(@Nullable Integer value) {this.settings.maximumClientIdLength(value);return this;}
1029  /**
1030   * Sets the maximum application subject length in UTF-16 code units.
1031   * Default: 255 code units; inclusive range: 16 code units through 1024 code units. Null restores the default.
1032   * Bounds and combined constraints are checked by {@link #build()}, not by this setter.
1033   * The interval bounds this maximum setting, not a minimum accepted subject length. Subjects remain exact application identifiers, separately scoped by issuer; this does not create accounts or authorize a user.
1034   * @param value the setting in the units described above, or null to restore the default
1035   * @return this builder
1036   * @since 1.0.0
1037   */
1038  @CheckReturnValue public @NonNull Builder maximumSubjectLength(@Nullable Integer value) {this.settings.maximumSubjectLength(value);return this;}
1039  /** Inspects the current configuration shape without invoking application collaborators.
1040   * The immutable result contains only fixed codes and no configured values or exception text.
1041   * An empty result establishes construction validity, not deployment or key-provider readiness.
1042   * @return every detectable missing or incompatible setting in deterministic order
1043   * @since 1.0.0
1044   */
1045  @CheckReturnValue public @NonNull List<@NonNull ConfigurationDiagnostic> configurationDiagnostics() {
1046   return configurationDiagnostics(Runtime.version());
1047  }
1048  private @NonNull List<@NonNull ConfigurationDiagnostic> configurationDiagnostics(Runtime.@NonNull Version runtimeVersion) {
1049   List<ConfigurationDiagnostic> issues=new ArrayList<>();
1050   if(this.authorizationEndpoint==null)issues.add(ConfigurationDiagnostic.OAUTH_AUTHORIZATION_ENDPOINT_REQUIRED);
1051   if(this.tokenEndpoint==null)issues.add(ConfigurationDiagnostic.OAUTH_TOKEN_ENDPOINT_REQUIRED);
1052   if(this.jwksEndpoint==null)issues.add(ConfigurationDiagnostic.OAUTH_JWKS_ENDPOINT_REQUIRED);
1053   if(this.clientRepository==null)issues.add(ConfigurationDiagnostic.OAUTH_CLIENT_REPOSITORY_REQUIRED);
1054   if(this.store==null)issues.add(ConfigurationDiagnostic.OAUTH_STORE_REQUIRED);
1055   if(this.signingKeys==null)issues.add(ConfigurationDiagnostic.OAUTH_SIGNING_KEYS_REQUIRED);
1056   if(this.stateSealer==null)issues.add(ConfigurationDiagnostic.OAUTH_STATE_SEALER_REQUIRED);
1057   if(this.grantPolicy==null)issues.add(ConfigurationDiagnostic.OAUTH_GRANT_POLICY_REQUIRED);
1058   if(this.resources==null)issues.add(ConfigurationDiagnostic.OAUTH_RESOURCES_REQUIRED);
1059   if(this.refreshTokensEnabled&&this.revocationEndpoint==null)
1060    issues.add(ConfigurationDiagnostic.OAUTH_REFRESH_REQUIRES_REVOCATION_ENDPOINT);
1061
1062   Integer sealerMaximum=this.stateSealer==null?null:SealedStateAccess.get().getMaximumSealedLength(this.stateSealer);
1063   List<ConfigurationDiagnostic> settingsIssues=this.settings.configurationDiagnostics(this.refreshTokensEnabled,sealerMaximum);
1064   issues.addAll(settingsIssues);
1065   OAuthServerIngressLimits ingress=this.settings.resourceLimitsForDiagnostics();
1066   if(ingress!=null&&this.resources!=null){
1067    try{OAuthServerAuthorizationAdmission.checkedServerResources(this.resources,ingress);}
1068    catch(IllegalArgumentException invalid){issues.add(ConfigurationDiagnostic.OAUTH_RESOURCES_INVALID);}
1069   }
1070
1071   URI issuerUri=endpoint(URI.create(this.issuer),true);
1072   try{endpoint(issuerUri,this.allowInsecureLoopback);}
1073   catch(IllegalArgumentException invalid){issues.add(ConfigurationDiagnostic.OAUTH_ISSUER_SCHEME_INCOMPATIBLE);}
1074   Set<String> routes=new HashSet<>();
1075   routeDiagnostic(issuerUri,this.authorizationEndpoint,routes,ConfigurationDiagnostic.OAUTH_AUTHORIZATION_ENDPOINT_INVALID,issues);
1076   routeDiagnostic(issuerUri,this.tokenEndpoint,routes,ConfigurationDiagnostic.OAUTH_TOKEN_ENDPOINT_INVALID,issues);
1077   routeDiagnostic(issuerUri,this.jwksEndpoint,routes,ConfigurationDiagnostic.OAUTH_JWKS_ENDPOINT_INVALID,issues);
1078   routeDiagnostic(issuerUri,this.revocationEndpoint,routes,ConfigurationDiagnostic.OAUTH_REVOCATION_ENDPOINT_INVALID,issues);
1079   routeDiagnostic(issuerUri,this.introspectionEndpoint,routes,ConfigurationDiagnostic.OAUTH_INTROSPECTION_ENDPOINT_INVALID,issues);
1080   if(this.clientMetadataPolicy.getEnabled())try{RuntimeFloor.require(runtimeVersion,this.acknowledgeUnpatchedRuntime);}
1081    catch(IllegalStateException invalid){issues.add(ConfigurationDiagnostic.OAUTH_CLIENT_METADATA_RUNTIME_INCOMPATIBLE);}
1082   return List.copyOf(issues);
1083  }
1084  private static void routeDiagnostic(@NonNull URI issuer,@Nullable URI route,@NonNull Set<@NonNull String> routes,
1085    @NonNull ConfigurationDiagnostic code,@NonNull List<@NonNull ConfigurationDiagnostic> issues){
1086   if(route==null)return;
1087   try{checkRoute(issuer,route,true,routes);}
1088   catch(IllegalArgumentException invalid){issues.add(code);}
1089  }
1090  /**
1091   * Validates the complete configuration and returns an issuer retaining the selected application collaborators.
1092   * Missing required values, refresh without revocation, unsafe/duplicate/cross-authority routes, invalid
1093   * numeric/combined limits and a CIMD runtime below the unacknowledged floor fail construction.
1094   * No client/store/key/policy/resolver callback, clock sampling, network I/O, signing or owned thread is
1095   * started. Enabling localhost any-port redirects does synchronously notify the configured observer as
1096   * described by {@link #observer(OAuthServerObserver)}; its documented failure rules apply.
1097   * This does not initialize an issuer namespace, verify deployment recovery/witness readiness or authorize
1098   * credential release. Later builder changes do not alter this server; retained application collaborators
1099   * continue to follow their own lifecycle contracts.
1100   * @return the configured server, without persistence initialization or serving admission
1101   * @throws IllegalStateException if required configuration is missing, refresh lacks revocation, or CIMD requires an unacknowledged runtime floor
1102   * @throws IllegalArgumentException if endpoint, resource, numeric or combined configuration is invalid
1103   * @since 1.0.0
1104   */
1105  @CheckReturnValue public @NonNull OAuthAuthorizationServer build() {return new OAuthAuthorizationServer(this);}
1106  /** Returns a fixed redacted description.
1107   * @return description
1108   * @since 1.0.0
1109   */
1110  @Override public @NonNull String toString() {return "OAuthAuthorizationServer.Builder{<redacted>}";}
1111 }
1112}