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.saml;
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 org.jspecify.annotations.NonNull;
025import org.jspecify.annotations.Nullable;
026
027import javax.annotation.concurrent.Immutable;
028import java.time.Clock;
029import java.time.Duration;
030import java.util.Objects;
031
032/**
033 * A sealed pending login obtained from the initiating browser's cookie. The application must bind
034 * the cookie to that browser and clear it after completion. A backend with atomic single-use
035 * consumption can be supplied through the separate pending-store source.
036 *
037 * @since 1.0.0
038 */
039@Immutable
040public final class PendingSamlAuthenticationSource {
041    private final @Nullable String sealedForm;
042    private final @NonNull StateSealer sealer;
043    private final @NonNull String context;
044    private final @Nullable PendingSamlAuthenticationStore store;
045    private final @Nullable String browserBinding;
046
047    private PendingSamlAuthenticationSource(@Nullable String sealedForm, @NonNull StateSealer sealer,
048            @NonNull String context, @Nullable PendingSamlAuthenticationStore store,
049            @Nullable String browserBinding) {
050        this.sealedForm = sealedForm;
051        this.sealer = sealer;
052        this.context = context;
053        this.store = store;
054        this.browserBinding = browserBinding;
055    }
056
057    /**
058     * Selects the sealed state received from the initiating browser.
059     *
060     * @param sealedForm value read from that browser's secure cookie
061     * @param sealer active and verification sealing keys
062     * @param context exact application-selected cookie context
063     * @return the pending source
064     * @since 1.0.0
065     */
066    public static @NonNull PendingSamlAuthenticationSource fromSealedForm(@NonNull String sealedForm,
067            @NonNull StateSealer sealer, @NonNull String context) {
068        return new PendingSamlAuthenticationSource(Objects.requireNonNull(sealedForm),
069                Objects.requireNonNull(sealer), Objects.requireNonNull(context), null, null);
070    }
071
072    /**
073     * Selects an atomic pending store for this browser. Completion consumes using the received
074     * RelayState handle before parsing XML.
075     *
076     * @param store atomic pending store
077     * @param browserBinding browser-specific secret
078     * @param sealer active and verification sealing keys
079     * @param context same application-selected namespace used when saving
080     * @return the pending source
081     * @since 1.0.0
082     */
083    public static @NonNull PendingSamlAuthenticationSource fromStore(@NonNull PendingSamlAuthenticationStore store,
084            @NonNull BrowserBinding browserBinding, @NonNull StateSealer sealer, @NonNull String context) {
085        return fromStore(Objects.requireNonNull(store), Objects.requireNonNull(browserBinding).toSecretString(), sealer, context);
086    }
087
088    static @NonNull PendingSamlAuthenticationSource fromStore(@NonNull PendingSamlAuthenticationStore store,
089            @NonNull String browserBinding, @NonNull StateSealer sealer, @NonNull String context) {
090        SamlPendingBinding.context(Objects.requireNonNull(context), Objects.requireNonNull(browserBinding));
091        return new PendingSamlAuthenticationSource(null, Objects.requireNonNull(sealer), context,
092                Objects.requireNonNull(store), browserBinding);
093    }
094
095    @NonNull Resolution resolve(@NonNull Clock clock, @Nullable String relayState, @NonNull Duration budget) {
096        String record = sealedForm;
097        String sealContext = context;
098        if (store != null) {
099            if (relayState == null || relayState.isEmpty()) return Rejected.INSTANCE;
100            SamlPendingConsumeResult consumed;
101            long started = System.nanoTime();
102            try { consumed = store.consume(Objects.requireNonNull(browserBinding), relayState, budget); }
103            catch (RuntimeException exception) { return Indeterminate.INSTANCE; }
104            if (consumed == null || SamlPendingBudget.exhausted(started, budget)) return Indeterminate.INSTANCE;
105            if (consumed instanceof SamlPendingConsumeResult.Missing) return Rejected.INSTANCE;
106            if (consumed instanceof SamlPendingConsumeResult.Unavailable) return Unavailable.INSTANCE;
107            if (consumed instanceof SamlPendingConsumeResult.Indeterminate) return Indeterminate.INSTANCE;
108            record = ((SamlPendingConsumeResult.Consumed) consumed).getSealedRecord();
109            sealContext = SamlPendingBinding.context(context, Objects.requireNonNull(browserBinding));
110        }
111        try {
112            String opened = SealedStateAccess.get().unseal(sealer, SealedStateType.PENDING_SAML,
113                    Objects.requireNonNull(record), sealContext, clock);
114            PendingSamlAuthentication pending = PendingSamlAuthenticationCodec.decode(opened);
115            return pending == null ? Rejected.INSTANCE : new Resolved(pending);
116        } catch (UnsealException exception) {
117            return Rejected.INSTANCE;
118        } catch (RuntimeException exception) {
119            return Unavailable.INSTANCE;
120        }
121    }
122
123    /** Redacts the sealed state. @since 1.0.0 */
124    @Override public @NonNull String toString() { return "PendingSamlAuthenticationSource{<redacted>}"; }
125
126    sealed interface Resolution permits Resolved, Rejected, Unavailable, Indeterminate { }
127    record Resolved(@NonNull PendingSamlAuthentication pending) implements Resolution { }
128    enum Rejected implements Resolution { INSTANCE }
129    enum Unavailable implements Resolution { INSTANCE }
130    enum Indeterminate implements Resolution { INSTANCE }
131}