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.SealedStateType;
022import org.jspecify.annotations.NonNull;
023
024import javax.annotation.concurrent.Immutable;
025import java.time.Instant;
026import java.time.Duration;
027import java.util.Objects;
028import java.util.Optional;
029
030/**
031 * An engine-created pending SAML login. Place its sealed form in a Secure, HttpOnly, SameSite=None
032 * browser cookie for a cross-site POST ACS. A sealed cookie can be replayed in concurrent callbacks;
033 * the assertion replay cache still prevents releasing the same assertion twice. An atomic pending
034 * store is required when the application needs authoritative single consumption of the login itself.
035 *
036 * @since 1.0.0
037 */
038@Immutable
039public final class PendingSamlAuthentication {
040    private final @NonNull String spEntityId;
041    private final @NonNull String requestId;
042    private final @NonNull String relayState;
043    private final @NonNull String connectionId;
044    private final @NonNull String idpEntityId;
045    private final @NonNull String acs;
046    private final @NonNull Instant issuedAt;
047    private final @NonNull Instant expiresAt;
048    private final @NonNull SamlAuthenticationRequestOptions options;
049
050    PendingSamlAuthentication(@NonNull String spEntityId, @NonNull String requestId,
051            @NonNull String relayState, @NonNull String connectionId, @NonNull String idpEntityId,
052            @NonNull String acs, @NonNull Instant issuedAt, @NonNull Instant expiresAt) {
053        this(spEntityId, requestId, relayState, connectionId, idpEntityId, acs,
054                issuedAt, expiresAt, SamlAuthenticationRequestOptions.builder().build());
055    }
056
057    PendingSamlAuthentication(@NonNull String spEntityId, @NonNull String requestId,
058            @NonNull String relayState, @NonNull String connectionId, @NonNull String idpEntityId,
059            @NonNull String acs, @NonNull Instant issuedAt, @NonNull Instant expiresAt,
060            @NonNull SamlAuthenticationRequestOptions options) {
061        this.spEntityId = Objects.requireNonNull(spEntityId);
062        this.requestId = Objects.requireNonNull(requestId);
063        this.relayState = Objects.requireNonNull(relayState);
064        this.connectionId = Objects.requireNonNull(connectionId);
065        this.idpEntityId = Objects.requireNonNull(idpEntityId);
066        this.acs = Objects.requireNonNull(acs);
067        this.issuedAt = Objects.requireNonNull(issuedAt);
068        this.expiresAt = Objects.requireNonNull(expiresAt);
069        this.options = Objects.requireNonNull(options);
070    }
071
072    /**
073     * Seals this pending login under the SAML-specific type and exact application context.
074     * A valid pending record may exceed the configured sealer limit; this method then throws
075     * {@link IllegalArgumentException}. Persist successfully before delivering the request.
076     *
077     * @param sealer active and verification sealing keys
078     * @param context fixed application-selected cookie context
079     * @return the sealed value for a browser-bound cookie
080     * @since 1.0.0
081     */
082    public @NonNull String toSealedForm(@NonNull StateSealer sealer, @NonNull String context) {
083        String sealed = PendingSamlAuthenticationCodec.sealIfFits(this, Objects.requireNonNull(sealer),
084                SealedStateType.PENDING_SAML, Objects.requireNonNull(context));
085        if (sealed == null) throw new IllegalArgumentException("SAML pending state exceeds sealing limit");
086        return sealed;
087    }
088
089    /**
090     * Seals and saves this login under a browser-bound context. A possibly completed save returns
091     * INDETERMINATE; callers must not assume that retrying is safe.
092     * If the complete encoded record exceeds the configured sealer limit, returns UNAVAILABLE
093     * without calling the store or drawing sealing entropy. Shorten configuration or options
094     * before retrying; no pending state was saved. Invalid contexts remain argument errors.
095     *
096     * @param store atomic pending store
097     * @param sealer active and verification sealing keys
098     * @param context application-selected store namespace
099     * @param browserBinding browser-specific secret
100     * @param remaining positive operation budget
101     * @return the storage outcome
102     * @since 1.0.0
103     */
104    public @NonNull SamlPendingSaveResult saveToResult(@NonNull PendingSamlAuthenticationStore store,
105            @NonNull StateSealer sealer, @NonNull String context, @NonNull BrowserBinding browserBinding,
106            @NonNull Duration remaining) {
107        return saveToResult(store, sealer, context, Objects.requireNonNull(browserBinding).toSecretString(), remaining);
108    }
109
110    @NonNull SamlPendingSaveResult saveToResult(@NonNull PendingSamlAuthenticationStore store,
111            @NonNull StateSealer sealer, @NonNull String context, @NonNull String browserBinding,
112            @NonNull Duration remaining) {
113        Objects.requireNonNull(store);
114        Objects.requireNonNull(sealer);
115        Objects.requireNonNull(remaining);
116        if (remaining.isZero() || remaining.isNegative()) return SamlPendingSaveResult.UNAVAILABLE;
117        String bindingContext = SamlPendingBinding.context(Objects.requireNonNull(context),
118                Objects.requireNonNull(browserBinding));
119        String record = PendingSamlAuthenticationCodec.sealIfFits(this, sealer, SealedStateType.PENDING_SAML,
120                bindingContext);
121        if (record == null) return SamlPendingSaveResult.UNAVAILABLE;
122        long started = System.nanoTime();
123        try {
124            SamlPendingSaveResult result = store.save(browserBinding, relayState, record, expiresAt, remaining);
125            if (result == null || SamlPendingBudget.exhausted(started, remaining))
126                return SamlPendingSaveResult.INDETERMINATE;
127            return result;
128        } catch (RuntimeException exception) { return SamlPendingSaveResult.INDETERMINATE; }
129    }
130
131    /**
132     * Returns the generated request ID.
133     *
134     * @return request ID
135     * @since 1.0.0
136     */
137    public @NonNull String getRequestId() { return requestId; }
138    /**
139     * Returns the opaque RelayState handle.
140     *
141     * @return handle
142     * @since 1.0.0
143     */
144    public @NonNull String getRelayStateHandle() { return relayState; }
145    /**
146     * Returns the expiration of this login attempt.
147     *
148     * @return expiry
149     * @since 1.0.0
150     */
151    public @NonNull Instant getExpiresAt() { return expiresAt; }
152    /**
153     * Returns the app-owned hint sealed into this request, when supplied.
154     * @return optional application data
155     * @since 1.0.0
156     */
157    public @NonNull Optional<@NonNull String> getApplicationData() { return options.getApplicationData(); }
158    /**
159     * Redacts the pending identifiers.
160     *
161     * @since 1.0.0
162     */
163    @Override public @NonNull String toString() { return "PendingSamlAuthentication{<redacted>}"; }
164
165    @NonNull String spEntityId() { return spEntityId; }
166    @NonNull String requestId() { return requestId; }
167    @NonNull String relayState() { return relayState; }
168    @NonNull String connectionId() { return connectionId; }
169    @NonNull String idpEntityId() { return idpEntityId; }
170    @NonNull String acs() { return acs; }
171    @NonNull Instant issuedAt() { return issuedAt; }
172    @NonNull Instant expiresAt() { return expiresAt; }
173    @NonNull SamlAuthenticationRequestOptions options() { return options; }
174}