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 */
016package com.revetsec.saml;
017
018import com.revetsec.BrowserBinding;
019import com.revetsec.StateSealer;
020import com.revetsec.internal.crypto.SealedStateAccess;
021import com.revetsec.internal.crypto.SealedStateType;
022import com.revetsec.internal.crypto.UnsealException;
023import org.jspecify.annotations.NonNull;
024import org.jspecify.annotations.Nullable;
025import javax.annotation.concurrent.Immutable;
026import java.time.Clock;
027import java.time.Duration;
028import java.util.Objects;
029import java.util.concurrent.atomic.AtomicReference;
030import java.util.function.Predicate;
031
032/**
033 * Browser-bound source of one SP-initiated pending logout. The caller clears the cookie after
034 * a verified terminal status; a conditional atomic store supplies single use across callbacks
035 * and nodes without consuming state for an invalid response.
036 *
037 * @since 1.0.0
038 */
039@Immutable
040public final class PendingSamlLogoutSource {
041    private final @Nullable String sealedForm;
042    private final @Nullable PendingSamlAuthenticationStore store;
043    private final @Nullable String browserBinding;
044    private final @NonNull StateSealer sealer;
045    private final @NonNull String context;
046
047    private PendingSamlLogoutSource(@Nullable String sealedForm,
048            @Nullable PendingSamlAuthenticationStore store, @Nullable String browserBinding,
049            @NonNull StateSealer sealer, @NonNull String context) {
050        this.sealedForm = sealedForm;
051        this.store = store;
052        this.browserBinding = browserBinding;
053        this.sealer = sealer;
054        this.context = context;
055    }
056
057    /**
058     * Selects a sealed browser cookie.
059     *
060     * @param sealedForm received cookie value
061     * @param sealer active and verification keys
062     * @param context exact cookie namespace
063     * @return pending source
064     * @since 1.0.0
065     */
066    public static @NonNull PendingSamlLogoutSource fromSealedForm(@NonNull String sealedForm,
067            @NonNull StateSealer sealer, @NonNull String context) {
068        return new PendingSamlLogoutSource(Objects.requireNonNull(sealedForm), null, null,
069                Objects.requireNonNull(sealer), Objects.requireNonNull(context));
070    }
071
072    /**
073     * Selects an atomic pending store and browser binding. Logout completion requires the
074     * store's conditional consume operation so authenticated pending state can be checked
075     * against the response before removal.
076     *
077     * @param store atomic store
078     * @param browserBinding browser-specific secret
079     * @param sealer active and verification keys
080     * @param context same namespace used when saving
081     * @return pending source
082     * @since 1.0.0
083     */
084    public static @NonNull PendingSamlLogoutSource fromStore(@NonNull PendingSamlAuthenticationStore store,
085            @NonNull BrowserBinding browserBinding, @NonNull StateSealer sealer, @NonNull String context) {
086        return fromStore(Objects.requireNonNull(store), Objects.requireNonNull(browserBinding).toSecretString(), sealer, context);
087    }
088
089    static @NonNull PendingSamlLogoutSource fromStore(@NonNull PendingSamlAuthenticationStore store,
090            @NonNull String browserBinding, @NonNull StateSealer sealer, @NonNull String context) {
091        SamlPendingBinding.context(Objects.requireNonNull(context) + "|logout",
092                Objects.requireNonNull(browserBinding));
093        return new PendingSamlLogoutSource(null, Objects.requireNonNull(store), browserBinding,
094                Objects.requireNonNull(sealer), context);
095    }
096
097    @NonNull Resolution resolve(@NonNull Clock clock, @Nullable String relay, @NonNull Duration budget) {
098        return resolve(clock, relay, budget, pending -> true);
099    }
100
101    @NonNull Resolution resolve(@NonNull Clock clock, @Nullable String relay, @NonNull Duration budget,
102            @NonNull Predicate<@NonNull PendingSamlAuthentication> matches) {
103        if (store == null) return open(Objects.requireNonNull(sealedForm), context, clock, matches);
104        if (relay == null || relay.isEmpty()) return Rejected.INSTANCE;
105        String binding = Objects.requireNonNull(browserBinding);
106        String sealContext = SamlPendingBinding.context(context + "|logout", binding);
107        AtomicReference<@Nullable Checked> checked = new AtomicReference<>();
108        SamlPendingConsumeResult consumed;
109        long started = System.nanoTime();
110        try {
111            consumed = store.consumeIfMatches(binding, relay, record -> {
112                Resolution result = open(record, sealContext, clock, matches);
113                checked.set(new Checked(record, result));
114                return result instanceof Resolved;
115            }, budget);
116        } catch (RuntimeException exception) { return Indeterminate.INSTANCE; }
117        if (consumed == null || SamlPendingBudget.exhausted(started, budget))
118            return Indeterminate.INSTANCE;
119        if (consumed instanceof SamlPendingConsumeResult.Unavailable) return Unavailable.INSTANCE;
120        if (consumed instanceof SamlPendingConsumeResult.Indeterminate) return Indeterminate.INSTANCE;
121        Checked approval = checked.get();
122        if (consumed instanceof SamlPendingConsumeResult.Missing)
123            return approval != null && approval.result() instanceof Unavailable
124                    ? Unavailable.INSTANCE : Rejected.INSTANCE;
125        String record = ((SamlPendingConsumeResult.Consumed) consumed).getSealedRecord();
126        // A provider must remove the exact record approved by the predicate, never a replacement.
127        if (approval == null || !(approval.result() instanceof Resolved)
128                || !approval.sealedRecord().equals(record)) return Indeterminate.INSTANCE;
129        Resolution rechecked = open(record, sealContext, clock, matches);
130        // Removal is confirmed. A later expiry or capability failure cannot make state reusable.
131        return rechecked instanceof Resolved resolved
132                ? new Resolved(resolved.pending(), true) : Indeterminate.INSTANCE;
133    }
134
135    private @NonNull Resolution open(@NonNull String record, @NonNull String sealContext,
136            @NonNull Clock clock, @NonNull Predicate<@NonNull PendingSamlAuthentication> matches) {
137        try {
138            String opened = SealedStateAccess.get().unseal(sealer, SealedStateType.PENDING_SAML_LOGOUT,
139                    record, sealContext, clock);
140            PendingSamlAuthentication pending = PendingSamlAuthenticationCodec.decode(opened);
141            return pending == null || !matches.test(pending) ? Rejected.INSTANCE : new Resolved(pending, false);
142        } catch (UnsealException exception) { return Rejected.INSTANCE; }
143        catch (RuntimeException exception) { return Unavailable.INSTANCE; }
144    }
145
146    /**
147     * Redacts state and store details.
148     *
149     * @return redacted description
150     * @since 1.0.0
151     */
152    @Override public @NonNull String toString() { return "PendingSamlLogoutSource{<redacted>}"; }
153    sealed interface Resolution permits Resolved, Rejected, Unavailable, Indeterminate { }
154    record Resolved(@NonNull PendingSamlAuthentication pending, boolean consumed) implements Resolution { }
155    enum Rejected implements Resolution { INSTANCE }
156    enum Unavailable implements Resolution { INSTANCE }
157    enum Indeterminate implements Resolution { INSTANCE }
158    private record Checked(@NonNull String sealedRecord, @NonNull Resolution result) { }
159}