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.oidc;
018
019import com.revetsec.BrowserBinding;
020import com.revetsec.StateSealer;
021import com.revetsec.internal.crypto.SealedStateAccess;
022import com.revetsec.internal.crypto.SealedStateType;
023import com.revetsec.internal.crypto.UnsealException;
024import com.revetsec.internal.http.Deadline;
025import com.revetsec.oauth.PendingAuthorizationStore;
026import org.jspecify.annotations.NonNull;
027import org.jspecify.annotations.Nullable;
028import javax.annotation.concurrent.Immutable;
029import java.net.URI;
030import java.time.Clock;
031import java.time.Instant;
032import java.time.ZoneOffset;
033import java.util.Optional;
034import static java.util.Objects.requireNonNull;
035
036/**
037 * A typed browser-bound source for logout return correlation. The application clears a sealed cookie on every
038 * callback, including failures/exceptions; that cookie cannot promise atomic concurrent single use. A qualified
039 * shared store must consume atomically across participating nodes/restarts. No state-only source exists.
040 * @author <a href="https://www.revetkn.com">Mark Allen</a>
041 * @since 1.0.0
042 */
043@Immutable
044public final class PendingOidcLogoutSource {
045        private final @Nullable String sealed, context, binding;
046        private final @Nullable StateSealer sealer;
047        private final @Nullable PendingAuthorizationStore store;
048        private PendingOidcLogoutSource(@Nullable String sealed, @Nullable StateSealer sealer, @Nullable String context, @Nullable PendingAuthorizationStore store, @Nullable String binding) {
049                this.sealed = sealed; this.sealer = sealer; this.context = context; this.store = store; this.binding = binding;
050        }
051        /**
052         * Selects only a typed pending-logout cookie supplied by that browser. Clear it on every callback.
053         * @param sealedForm received browser cookie
054         * @param sealer application-owned sealer
055         * @param context fixed application cookie context
056         * @return source with no atomic-single-use guarantee
057         * @throws NullPointerException if a required argument is null
058         * @throws IllegalArgumentException if the trusted context is outside the sealer profile
059         * @since 1.0.0
060         */
061        public static @NonNull PendingOidcLogoutSource fromSealedForm(@NonNull String sealedForm, @NonNull StateSealer sealer, @NonNull String context) {
062                requireNonNull(sealedForm); requireNonNull(sealer); com.revetsec.internal.crypto.SealerV1.requireContext(requireNonNull(context));
063                return new PendingOidcLogoutSource(sealedForm, sealer, context, null, null);
064        }
065        /**
066         * Selects a trusted opaque atomic store and this browser's separately generated binding.
067         * @param store shared store whose consume must be atomic
068         * @param browserBinding nonempty browser-specific secret, at most512UTF8bytes
069         * @return source
070         * @throws NullPointerException if a required argument is null
071         * @throws IllegalArgumentException if browser binding is outside the fixed profile
072         * @since 1.0.0
073         */
074        public static @NonNull PendingOidcLogoutSource fromStore(@NonNull PendingAuthorizationStore store, @NonNull BrowserBinding browserBinding) {
075                return fromStore(requireNonNull(store), requireNonNull(browserBinding).toSecretString());
076        }
077        static @NonNull PendingOidcLogoutSource fromStore(@NonNull PendingAuthorizationStore store, @NonNull String browserBinding) {
078                OidcLogoutSupport.binding(requireNonNull(browserBinding));
079                return new PendingOidcLogoutSource(null, null, null, requireNonNull(store), browserBinding);
080        }
081
082        @NonNull OidcLogoutResult complete(@NonNull String state, @NonNull String issuer, @NonNull String clientId, @NonNull URI callback, @NonNull Clock clock, @NonNull Deadline deadline) {
083                OidcLogoutSupport.active(deadline); Instant before = readClock(clock, false, deadline); OidcLogoutSupport.active(deadline);
084                String record; boolean entered = false;
085                try {
086                        if (this.store != null) {
087                                java.time.Duration allowance = OidcLogoutSupport.remaining(deadline); entered = true;
088                                Optional<String> consumed = this.store.consume(requireNonNull(this.binding), state, allowance);
089                                if (consumed == null || deadline.isExpired() || Thread.currentThread().isInterrupted()) throw indeterminate();
090                                if (consumed.isEmpty()) return rejected(OidcLogoutResult.Reason.PENDING_NOT_FOUND, entered, deadline);
091                                record = consumed.get();
092                        } else {
093                                if (requireNonNull(this.sealed).length() > 16_384) return rejected(OidcLogoutResult.Reason.PENDING_INVALID, entered, deadline);
094                                record = SealedStateAccess.get().unseal(requireNonNull(this.sealer), SealedStateType.PENDING_OIDC_LOGOUT, this.sealed, requireNonNull(this.context), Clock.fixed(before, ZoneOffset.UTC));
095                                OidcLogoutSupport.active(deadline);
096                        }
097                        OidcLogoutPendingCodec.Decoded decoded;
098                        try { decoded = OidcLogoutPendingCodec.decode(record); }
099                        catch (IllegalArgumentException invalid) { return rejected(OidcLogoutResult.Reason.PENDING_INVALID, entered, deadline); }
100                        PendingOidcLogout pending = decoded.pending();
101                        if (!pending.getIssuer().equals(issuer) || !pending.getClientId().equals(clientId) || !pending.getCallbackUri().toString().equals(callback.toString()))
102                                return rejected(OidcLogoutResult.Reason.CLIENT_MISMATCH, entered, deadline);
103                        if (!OidcLogoutSupport.same(pending.state(), state)) return rejected(OidcLogoutResult.Reason.STATE_MISMATCH, entered, deadline);
104                        String digest = decoded.bindingDigest();
105                        if (this.store == null ? digest != null : digest == null) return rejected(OidcLogoutResult.Reason.PENDING_INVALID, entered, deadline);
106                        if (this.store != null && !OidcLogoutSupport.same(requireNonNull(digest), OidcLogoutPendingCodec.digest(requireNonNull(this.binding))))
107                                return rejected(OidcLogoutResult.Reason.BROWSER_BINDING_MISMATCH, entered, deadline);
108                        Instant now = readClock(clock, entered, deadline);
109                        if (now.isBefore(before)) throw entered ? indeterminate() : OidcLogoutSupport.failure(OidcLogoutException.Reason.PROVIDER_UNAVAILABLE);
110                        if (now.isBefore(pending.getCreatedAt())) return rejected(OidcLogoutResult.Reason.PENDING_INVALID, entered, deadline);
111                        if (!now.isBefore(pending.getExpiresAt())) return rejected(OidcLogoutResult.Reason.PENDING_EXPIRED, entered, deadline);
112                        if (entered && (deadline.isExpired() || Thread.currentThread().isInterrupted())) throw indeterminate();
113                        OidcLogoutSupport.active(deadline); return OidcLogoutResult.returned();
114                } catch (UnsealException invalid) {
115                        return rejected(invalid.getKind() == UnsealException.Kind.EXPIRED ? OidcLogoutResult.Reason.PENDING_EXPIRED : OidcLogoutResult.Reason.PENDING_INVALID, entered, deadline);
116                } catch (VirtualMachineError fatal) { throw fatal; }
117                catch (OidcLogoutException failure) {
118                        if (entered) throw indeterminate();
119                        throw failure;
120                } catch (Throwable unavailable) {
121                        if (unavailable instanceof InterruptedException) Thread.currentThread().interrupt();
122                        if (entered) throw indeterminate();
123                        OidcLogoutSupport.active(deadline); throw OidcLogoutSupport.failure(OidcLogoutException.Reason.PROVIDER_UNAVAILABLE);
124                }
125        }
126        private static @NonNull Instant readClock(@NonNull Clock clock, boolean entered, @NonNull Deadline deadline) {
127                try { return requireNonNull(clock.instant()); }
128                catch (VirtualMachineError fatal) { throw fatal; }
129                catch (RuntimeException | Error unavailable) { if (entered) throw indeterminate(); OidcLogoutSupport.active(deadline); throw OidcLogoutSupport.failure(OidcLogoutException.Reason.PROVIDER_UNAVAILABLE); }
130        }
131        private static @NonNull OidcLogoutResult rejected(OidcLogoutResult.@NonNull Reason reason, boolean entered, @NonNull Deadline deadline) {
132                if (entered && (deadline.isExpired() || Thread.currentThread().isInterrupted())) throw indeterminate();
133                OidcLogoutSupport.active(deadline); return OidcLogoutResult.rejected(reason);
134        }
135        private static @NonNull OidcLogoutException indeterminate() { return OidcLogoutSupport.failure(OidcLogoutException.Reason.STORE_INDETERMINATE); }
136        /** Redacts source state and browser binding.
137         * @return redacted description
138         * @since 1.0.0
139         */
140        @Override public @NonNull String toString() { return "PendingOidcLogoutSource{correlation=<redacted>}"; }
141}