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;
018
019import com.revetsec.internal.Limits;
020import com.revetsec.internal.http.Deadline;
021import org.jspecify.annotations.NonNull;
022import org.jspecify.annotations.Nullable;
023
024import com.google.errorprone.annotations.CheckReturnValue;
025import javax.annotation.concurrent.NotThreadSafe;
026import javax.annotation.concurrent.ThreadSafe;
027import java.net.URI;
028import java.time.Clock;
029import java.time.Duration;
030import java.time.Instant;
031import java.util.List;
032import java.util.Map;
033import java.util.Set;
034import java.util.concurrent.CompletableFuture;
035import java.util.concurrent.ExecutionException;
036import java.util.concurrent.TimeUnit;
037import java.util.concurrent.TimeoutException;
038import java.util.concurrent.locks.ReentrantLock;
039
040import static java.util.Objects.requireNonNull;
041
042/**
043 * A bounded caller-thread cache for confidential client-credentials access tokens. One caller renews; callers may continue
044 * using a valid cached token during early renewal, while callers without one share the renewal result.
045 * A rejected cached token is cleared only when {@link #invalidate(AccessToken)} receives that exact instance.
046 * No expired or rejected token is returned.
047 *
048 * @author <a href="https://www.revetkn.com">Mark Allen</a>
049 * @since 1.0.0
050 */
051@ThreadSafe
052public final class ClientCredentialsTokenSource {
053        private final @NonNull OAuthClient client;
054        private final @NonNull TokenRequestOptions options;
055        private final @NonNull Duration fallbackCacheDuration;
056        private final @NonNull Duration maximumCacheDuration;
057        private final @NonNull Duration renewBefore;
058        private final @NonNull Clock clock;
059        private final ReentrantLock lock = new ReentrantLock();
060        private @Nullable Cached cached;
061        private @Nullable CompletableFuture<@NonNull AccessTokenAcquisitionResult> flight;
062        private @Nullable OAuthException lastFailure;
063        private AccessTokenAcquisitionResult.@Nullable Rejected lastRejection;
064        private long lastFailureNanos;
065        private int failureCount;
066        private @Nullable Instant lastClock;
067
068        private ClientCredentialsTokenSource(@NonNull Builder builder) {
069                this.client = builder.client;
070                TokenRequestOptions.Builder optionsBuilder = TokenRequestOptions.builder().scopes(builder.scopes);
071                if (builder.resourcesOverridden) optionsBuilder = optionsBuilder.resources(builder.resources);
072                optionsBuilder = optionsBuilder.additionalParameters(builder.additionalParameters);
073                this.options = optionsBuilder.build();
074                this.fallbackCacheDuration = builder.fallbackCacheDuration;
075                this.maximumCacheDuration = builder.maximumCacheDuration;
076                this.renewBefore = builder.renewBefore;
077                this.clock = builder.client.clock();
078        }
079
080        /**
081         * Starts a source using the client's configured token endpoint and deadline.
082         *
083         * @param client a confidential OAuth client
084         * @return the builder
085         * @since 1.0.0
086         */
087        public static @NonNull Builder withClient(@NonNull OAuthClient client) {
088                return new Builder(requireNonNull(client));
089        }
090
091        /**
092         * Gets a valid access token or a fixed endpoint client rejection, renewing in the calling thread when needed.
093         * An early renewal rejection or failure may serve the still-valid previous token, except after invalidation.
094         * Without a usable token, non-transient endpoint client rejections remain result values through shared renewal
095         * and backoff. Infrastructure failures remain exceptions.
096         *
097         * @return the acquisition outcome
098         * @since 1.0.0
099         */
100        @CheckReturnValue
101        public @NonNull AccessTokenAcquisitionResult getAccessTokenResult() {
102                Deadline callDeadline = Deadline.fromNow(this.client.totalDeadline());
103                for (;;) {
104                        AccessTokenAcquisitionResult result = getAccessTokenOnce(callDeadline);
105                        if (result != null) return result;
106                }
107        }
108
109        // Only the caller that installed this exact future may publish or clear its flight.
110        @SuppressWarnings("ReferenceEquality")
111        private @Nullable AccessTokenAcquisitionResult getAccessTokenOnce(@NonNull Deadline callDeadline) {
112                requireActive(callDeadline);
113                CompletableFuture<AccessTokenAcquisitionResult> mine = null;
114                CompletableFuture<AccessTokenAcquisitionResult> waitFor = null;
115                Cached old;
116                this.lock.lock();
117                try {
118                        requireActive(callDeadline);
119                        Instant now = this.clock.instant();
120                        old = currentCached(now);
121                        if (old != null && now.isBefore(old.renewAt) && now.isBefore(old.expiresAt))
122                                return AccessTokenAcquisitionResult.fromAccessToken(old.token);
123                        if (this.flight != null) {
124                                if (old != null && now.isBefore(old.expiresAt)) return AccessTokenAcquisitionResult.fromAccessToken(old.token);
125                                waitFor = this.flight;
126                        } else {
127                                long base = Duration.ofSeconds(30).toNanos();
128                                long backoff = Math.min(base << Math.min(4, Math.max(0, this.failureCount - 1)),
129                                                Duration.ofMinutes(5).toNanos());
130                                if ((this.lastFailure != null || this.lastRejection != null)
131                                                && System.nanoTime() - this.lastFailureNanos < backoff) {
132                                        if (old != null && now.isBefore(old.expiresAt)) return AccessTokenAcquisitionResult.fromAccessToken(old.token);
133                                        if (this.lastRejection != null) return this.lastRejection;
134                                        throw OAuthHttpErrors.copyForCaller(requireNonNull(this.lastFailure));
135                                }
136                                mine = new CompletableFuture<>();
137                                this.flight = mine;
138                        }
139                } finally {
140                        this.lock.unlock();
141                }
142                if (waitFor != null) {
143                        AccessTokenAcquisitionResult shared = await(waitFor, callDeadline);
144                        if (shared instanceof AccessTokenAcquisitionResult.Rejected) return shared;
145                        AccessToken token = ((AccessTokenAcquisitionResult.Succeeded) shared).getAccessToken();
146                        this.lock.lock();
147                        try {
148                                Instant now = this.clock.instant();
149                                Cached current = currentCached(now);
150                                if (current != null && current.token == token
151                                                && now.isBefore(current.expiresAt)) return shared;
152                        } finally {
153                                this.lock.unlock();
154                        }
155                        return null;
156                }
157                CompletableFuture<AccessTokenAcquisitionResult> leader = requireNonNull(mine);
158                try {
159                        OAuthTokenRequestResult requested = this.client.requestClientCredentialsResult(this.options);
160                        if (requested instanceof OAuthTokenRequestResult.Rejected rejected)
161                                return retainRejection(leader, rejected);
162                        TokenResponse response = ((OAuthTokenRequestResult.Succeeded) requested).getTokens();
163                        Instant now = this.clock.instant();
164                        Instant explicit = response.getExpiresAt().orElse(null);
165                        Duration lifetime = explicit == null ? this.fallbackCacheDuration
166                                        : Duration.between(now, explicit);
167                        if (lifetime.isNegative() || lifetime.isZero())
168                                throw OAuthValidationException.fromReason(OAuthException.Reason.TOKEN_EXPIRED);
169                        if (lifetime.compareTo(this.maximumCacheDuration) > 0) lifetime = this.maximumCacheDuration;
170                        Duration lead = Limits.clientCredentialsRenewalLeadTime(this.renewBefore, lifetime);
171                        AccessToken token = response.getAccessToken();
172                        Cached fresh = new Cached(token, now, now.plus(lifetime), now.plus(lifetime).minus(lead));
173                        this.lock.lock();
174                        try {
175                                if (this.flight == leader) {
176                                        this.cached = fresh;
177                                        this.flight = null;
178                                        this.lastFailure = null;
179                                        this.lastRejection = null;
180                                        this.failureCount = 0;
181                                }
182                        } finally {
183                                this.lock.unlock();
184                        }
185                        AccessTokenAcquisitionResult result = AccessTokenAcquisitionResult.fromAccessToken(token);
186                        leader.complete(result);
187                        return result;
188                } catch (OAuthException failure) {
189                        boolean interrupted = failure.getReason() == OAuthException.Reason.INTERRUPTED
190                                        || Thread.currentThread().isInterrupted();
191                        boolean callerLocal = interrupted || callDeadline.isExpired();
192                        if (interrupted) Thread.currentThread().interrupt();
193                        AccessToken fallback = null;
194                        this.lock.lock();
195                        try {
196                                if (this.flight == leader) {
197                                        this.flight = null;
198                                        if (!callerLocal) {
199                                                this.lastFailure = OAuthHttpErrors.copyForCaller(failure);
200                                                this.lastRejection = null;
201                                                this.lastFailureNanos = System.nanoTime();
202                                                this.failureCount = Math.min(5, this.failureCount + 1);
203                                        }
204                                        Instant now = this.clock.instant();
205                                        Cached current = currentCached(now);
206                                        if (current != null && now.isBefore(current.expiresAt))
207                                                fallback = current.token;
208                                }
209                        } finally {
210                                this.lock.unlock();
211                        }
212                        if (fallback != null) {
213                                AccessTokenAcquisitionResult result = AccessTokenAcquisitionResult.fromAccessToken(fallback);
214                                leader.complete(result);
215                                return result;
216                        }
217                        leader.completeExceptionally(callerLocal
218                                        ? OAuthTransportException.fromReason(OAuthException.Reason.NETWORK_FAILURE, null)
219                                        : OAuthHttpErrors.copyForCaller(failure));
220                        if (interrupted) throw OAuthTransportException.fromReason(OAuthException.Reason.INTERRUPTED, null);
221                        throw failure;
222                } catch (RuntimeException failure) {
223                        boolean interrupted = Thread.currentThread().isInterrupted();
224                        boolean callerLocal = interrupted || callDeadline.isExpired();
225                        OAuthException safe = OAuthTransportException.fromReason(
226                                        interrupted ? OAuthException.Reason.INTERRUPTED : OAuthException.Reason.NETWORK_FAILURE, null);
227                        this.lock.lock();
228                        try {
229                                if (this.flight == leader) {
230                                        this.flight = null;
231                                        if (!callerLocal) {
232                                                this.lastFailure = OAuthHttpErrors.copyForCaller(safe);
233                                                this.lastRejection = null;
234                                                this.lastFailureNanos = System.nanoTime();
235                                                this.failureCount = Math.min(5, this.failureCount + 1);
236                                        }
237                                }
238                        } finally {
239                                this.lock.unlock();
240                        }
241                        leader.completeExceptionally(OAuthTransportException.fromReason(OAuthException.Reason.NETWORK_FAILURE, null));
242                        throw safe;
243                } finally {
244                        // An Error from an injected clock, credential supplier or transport must not strand every later caller.
245                        this.lock.lock();
246                        try {
247                                if (this.flight == leader) this.flight = null;
248                        } finally {
249                                this.lock.unlock();
250                        }
251                        if (!leader.isDone())
252                                leader.completeExceptionally(OAuthTransportException.fromReason(OAuthException.Reason.NETWORK_FAILURE, null));
253                }
254        }
255
256        // A checked endpoint rejection follows the same single-flight/backoff and valid-token fallback policy as a
257        // failed renewal, while remaining an explicit value for callers that have no usable cached token.
258        @SuppressWarnings("ReferenceEquality")
259        private @NonNull AccessTokenAcquisitionResult retainRejection(
260                        @NonNull CompletableFuture<@NonNull AccessTokenAcquisitionResult> leader,
261                        OAuthTokenRequestResult.@NonNull Rejected rejection) {
262                AccessTokenAcquisitionResult.Rejected rejected = AccessTokenAcquisitionResult.fromRejection(rejection);
263                AccessTokenAcquisitionResult result = rejected;
264                this.lock.lock();
265                try {
266                        if (this.flight == leader) {
267                                Instant now = this.clock.instant();
268                                Cached current = currentCached(now);
269                                this.flight = null;
270                                this.lastFailure = null;
271                                this.lastRejection = rejected;
272                                this.lastFailureNanos = System.nanoTime();
273                                this.failureCount = Math.min(5, this.failureCount + 1);
274                                if (current != null && now.isBefore(current.expiresAt))
275                                        result = AccessTokenAcquisitionResult.fromAccessToken(current.token);
276                        }
277                } finally {
278                        this.lock.unlock();
279                }
280                leader.complete(result);
281                return result;
282        }
283
284        // Called only under lock. A backward clock step must not make an earlier token usable again.
285        private @Nullable Cached currentCached(@NonNull Instant now) {
286                boolean rollback = this.lastClock != null && now.isBefore(this.lastClock);
287                this.lastClock = now;
288                Cached current = this.cached;
289                if (current != null && (rollback || now.isBefore(current.fetchedAt))) {
290                        this.cached = null;
291                        return null;
292                }
293                return current;
294        }
295
296        /**
297         * Clears a rejected cached instance. An old 401 cannot evict a replacement token.
298         *
299         * @param rejectedToken the exact instance rejected by a resource server
300         * @since 1.0.0
301         */
302        public void invalidate(@NonNull AccessToken rejectedToken) {
303                requireNonNull(rejectedToken);
304                this.lock.lock();
305                try {
306                        if (this.cached != null && this.cached.token == rejectedToken) {
307                                this.cached = null;
308                                this.lastFailure = null;
309                                this.lastRejection = null;
310                                this.failureCount = 0;
311                        }
312        } finally {
313                        this.lock.unlock();
314                }
315        }
316
317        private static @NonNull AccessTokenAcquisitionResult await(@NonNull CompletableFuture<@NonNull AccessTokenAcquisitionResult> future,
318                        @NonNull Deadline deadline) {
319                try {
320                        long remaining = deadline.remainingNanos();
321                        if (remaining <= 0) throw OAuthTransportException.fromReason(OAuthException.Reason.NETWORK_FAILURE, null);
322                        return future.get(remaining, TimeUnit.NANOSECONDS);
323                } catch (InterruptedException interrupted) {
324                        Thread.currentThread().interrupt();
325                        throw OAuthTransportException.fromReason(OAuthException.Reason.INTERRUPTED, null);
326                } catch (TimeoutException timeout) {
327                        throw OAuthTransportException.fromReason(OAuthException.Reason.NETWORK_FAILURE, null);
328                } catch (ExecutionException failure) {
329                        if (failure.getCause() instanceof OAuthException oauth) throw OAuthHttpErrors.copyForCaller(oauth);
330                        throw OAuthTransportException.fromReason(OAuthException.Reason.NETWORK_FAILURE, null);
331                }
332        }
333
334        private static void requireActive(@NonNull Deadline deadline) {
335                if (Thread.currentThread().isInterrupted())
336                        throw OAuthTransportException.fromReason(OAuthException.Reason.INTERRUPTED, null);
337                if (deadline.isExpired())
338                        throw OAuthTransportException.fromReason(OAuthException.Reason.NETWORK_FAILURE, null);
339        }
340
341        private record Cached(@NonNull AccessToken token, @NonNull Instant fetchedAt, @NonNull Instant expiresAt,
342                        @NonNull Instant renewAt) { }
343
344        /**
345         * Configures a source without network I/O.
346         *
347         * @author <a href="https://www.revetkn.com">Mark Allen</a>
348         * @since 1.0.0
349         */
350        @NotThreadSafe
351        @CheckReturnValue
352        public static final class Builder {
353                private final @NonNull OAuthClient client;
354                private @Nullable Set<@NonNull String> scopes;
355                private @NonNull List<@NonNull URI> resources = List.of();
356                private @NonNull Map<@NonNull String, @NonNull String> additionalParameters = Map.of();
357                private boolean resourcesOverridden;
358                private @NonNull Duration fallbackCacheDuration = Limits.CLIENT_CREDENTIALS_FALLBACK_CACHE_DURATION.getDefaultDuration();
359                private @NonNull Duration maximumCacheDuration = Limits.CLIENT_CREDENTIALS_MAXIMUM_CACHE_DURATION.getDefaultDuration();
360                private @NonNull Duration renewBefore = Limits.CLIENT_CREDENTIALS_RENEW_BEFORE.getDefaultDuration();
361
362                private Builder(@NonNull OAuthClient client) { this.client = client; }
363
364                /**
365                 * Replaces the complete scope set; null uses the client's default.
366                 *
367                 * @param value scopes or null
368                 * @return this builder
369                 * @since 1.0.0
370                 */
371                public @NonNull Builder scopes(@Nullable Set<@NonNull String> value) {
372                        this.scopes = value == null ? null : TokenRequestOptions.builder().scopes(value).build().getScopes().orElseThrow();
373                        return this;
374                }
375
376                /**
377                 * Replaces the complete resource list.
378                 *
379                 * @param value resources, or null which restores inheritance
380                 * @return this builder
381                 * @since 1.0.0
382                 */
383                public @NonNull Builder resources(@Nullable List<@NonNull URI> value) {
384                        this.resources = TokenRequestOptions.builder().resources(value).build().getResources();
385                        this.resourcesOverridden = value != null;
386                        return this;
387                }
388
389                /**
390                 * Replaces provider-specific nonreserved token form parameters.
391                 *
392                 * @param value parameters, or null to clear them
393                 * @return this builder
394                 * @since 1.0.0
395                 */
396                public @NonNull Builder additionalParameters(@Nullable Map<@NonNull String, @NonNull String> value) {
397                        this.additionalParameters = TokenRequestOptions.builder().additionalParameters(value).build().getAdditionalParameters();
398                        return this;
399                }
400
401                /**
402                 * Sets the fallback cache lifetime when expires_in is absent.
403                 *
404                 * @param value fallback duration, or null which restores the default
405                 * @return this builder
406                 * @since 1.0.0
407                 */
408                public @NonNull Builder fallbackCacheDuration(@Nullable Duration value) {
409                        this.fallbackCacheDuration = value == null ? Limits.CLIENT_CREDENTIALS_FALLBACK_CACHE_DURATION.getDefaultDuration() : Limits.CLIENT_CREDENTIALS_FALLBACK_CACHE_DURATION.require(value);
410                        return this;
411                }
412
413                /**
414                 * Sets the maximum cache lifetime.
415                 *
416                 * @param value maximum duration, or null which restores the default
417                 * @return this builder
418                 * @since 1.0.0
419                 */
420                public @NonNull Builder maximumCacheDuration(@Nullable Duration value) {
421                        this.maximumCacheDuration = value == null ? Limits.CLIENT_CREDENTIALS_MAXIMUM_CACHE_DURATION.getDefaultDuration() : Limits.CLIENT_CREDENTIALS_MAXIMUM_CACHE_DURATION.require(value);
422                        return this;
423                }
424
425                /**
426                 * Sets the renewal lead time, clipped to half the actual lifetime.
427                 *
428                 * @param value lead time, or null which restores the default
429                 * @return this builder
430                 * @since 1.0.0
431                 */
432                public @NonNull Builder renewBefore(@Nullable Duration value) {
433                        this.renewBefore = value == null ? Limits.CLIENT_CREDENTIALS_RENEW_BEFORE.getDefaultDuration() : Limits.CLIENT_CREDENTIALS_RENEW_BEFORE.require(value);
434                        return this;
435                }
436
437                /**
438                 * Builds the source without I/O, secret/key-provider callbacks or a worker thread.
439                 * Rejects public-client authentication locally; provider capability and endpoint checks occur when requesting.
440                 *
441                 * @return the source
442                 * @throws IllegalArgumentException if the client has no confidential authentication strategy
443                 * @since 1.0.0
444                 */
445                public @NonNull ClientCredentialsTokenSource build() {
446            if (!this.client.supportsClientCredentials())
447                throw new IllegalArgumentException("A client-credentials token source requires confidential authentication.");
448                        Limits.requireFallbackWithinMaximumCacheDuration(this.fallbackCacheDuration, this.maximumCacheDuration);
449                        Limits.requireRenewBeforeBelowMaximumCacheDuration(this.renewBefore, this.maximumCacheDuration);
450                        return new ClientCredentialsTokenSource(this);
451                }
452        }
453}