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.BrowserBinding;
020import com.revetsec.StateSealer;
021import com.google.errorprone.annotations.CheckReturnValue;
022import com.revetsec.internal.crypto.SealedStateAccess;
023import com.revetsec.internal.crypto.SealedStateType;
024import com.revetsec.internal.http.Deadline;
025import org.jspecify.annotations.NonNull;
026import org.jspecify.annotations.Nullable;
027
028import javax.annotation.concurrent.Immutable;
029import java.net.URI;
030import java.time.Instant;
031import java.time.Duration;
032import java.util.List;
033import java.util.Map;
034import java.util.Set;
035
036import static java.util.Objects.requireNonNull;
037
038/**
039 * One pending browser authorization, including secret state, PKCE verifier and an OIDC nonce slot. The public
040 * accessors expose only descriptive fields. The complete record can be placed in a sealed cookie or saved in a
041 * browser-bound store; neither path exposes a free-standing serializer. A sealed cookie can be replayed concurrently:
042 * use a durable shared atomic store when client-side single use is required across callbacks, nodes or restarts.
043 *
044 * @author <a href="https://www.revetkn.com">Mark Allen</a>
045 * @since 1.0.0
046 */
047@Immutable
048public final class PendingAuthorization {
049        private final @NonNull String kind;
050        private final @NonNull String issuer;
051        private final @NonNull String clientId;
052        private final @NonNull URI redirectUri;
053        private final @NonNull String state;
054        private final @NonNull String verifier;
055        private final @Nullable String nonce;
056        private final @NonNull Set<@NonNull String> scopes;
057        private final @NonNull List<@NonNull URI> resources;
058        private final AuthorizationRequestOptions.@NonNull ResponseMode responseMode;
059        private final @NonNull Instant createdAt;
060        private final @NonNull Instant expiresAt;
061        private final @NonNull Map<@NonNull String, @NonNull String> applicationData;
062        private final boolean issuerRequired;
063        private final @NonNull URI authorizationEndpoint;
064        private final @NonNull URI tokenEndpoint;
065        private final @Nullable Duration maxAge;
066        private final @NonNull Set<@NonNull String> acrValues;
067        private final @Nullable String prompt;
068
069        PendingAuthorization(@NonNull String kind, @NonNull String issuer, @NonNull String clientId,
070                        @NonNull URI redirectUri, @NonNull String state, @NonNull String verifier, @Nullable String nonce,
071                        @NonNull Set<@NonNull String> scopes, @NonNull List<@NonNull URI> resources,
072                        AuthorizationRequestOptions.@NonNull ResponseMode responseMode, @NonNull Instant createdAt,
073                        @NonNull Instant expiresAt, @NonNull Map<@NonNull String, @NonNull String> applicationData,
074                        boolean issuerRequired, @NonNull URI authorizationEndpoint, @NonNull URI tokenEndpoint) {
075                this(kind, issuer, clientId, redirectUri, state, verifier, nonce, scopes, resources, responseMode, createdAt,
076                                expiresAt, applicationData, issuerRequired, authorizationEndpoint, tokenEndpoint, null, Set.of(), null);
077        }
078
079        PendingAuthorization(@NonNull String kind, @NonNull String issuer, @NonNull String clientId,
080                        @NonNull URI redirectUri, @NonNull String state, @NonNull String verifier, @Nullable String nonce,
081                        @NonNull Set<@NonNull String> scopes, @NonNull List<@NonNull URI> resources,
082                        AuthorizationRequestOptions.@NonNull ResponseMode responseMode, @NonNull Instant createdAt,
083                        @NonNull Instant expiresAt, @NonNull Map<@NonNull String, @NonNull String> applicationData,
084                        boolean issuerRequired, @NonNull URI authorizationEndpoint, @NonNull URI tokenEndpoint,
085                        @Nullable Duration maxAge, @NonNull Set<@NonNull String> acrValues, @Nullable String prompt) {
086                this.kind = requireNonNull(kind);
087                this.issuer = requireNonNull(issuer);
088                this.clientId = requireNonNull(clientId);
089                this.redirectUri = requireNonNull(redirectUri);
090                this.state = requireNonNull(state);
091                this.verifier = requireNonNull(verifier);
092                this.nonce = nonce;
093                this.scopes = Set.copyOf(scopes);
094                this.resources = List.copyOf(resources);
095                this.responseMode = requireNonNull(responseMode);
096                this.createdAt = requireNonNull(createdAt);
097                this.expiresAt = requireNonNull(expiresAt);
098                this.applicationData = Map.copyOf(applicationData);
099                this.issuerRequired = issuerRequired;
100                this.authorizationEndpoint = requireNonNull(authorizationEndpoint);
101                this.tokenEndpoint = requireNonNull(tokenEndpoint);
102                this.maxAge = maxAge; this.acrValues = Set.copyOf(acrValues); this.prompt = prompt;
103        }
104
105        /**
106         * Returns the initiating authorization-server issuer.
107         *
108         * @return the issuer
109         * @since 1.0.0
110         */
111        public @NonNull String getIssuer() { return this.issuer; }
112
113        /**
114         * Returns the initiating client ID.
115         *
116         * @return the client ID
117         * @since 1.0.0
118         */
119        public @NonNull String getClientId() { return this.clientId; }
120
121        /**
122         * Returns the exact registered redirect URI sent at begin.
123         *
124         * @return the redirect URI
125         * @since 1.0.0
126         */
127        public @NonNull URI getRedirectUri() { return this.redirectUri; }
128
129        /**
130         * Returns the requested scope set.
131         *
132         * @return scopes
133         * @since 1.0.0
134         */
135        public @NonNull Set<@NonNull String> getRequestedScopes() { return this.scopes; }
136
137        /**
138         * Returns the creation instant.
139         *
140         * @return creation
141         * @since 1.0.0
142         */
143        public @NonNull Instant getCreatedAt() { return this.createdAt; }
144
145        /**
146         * Returns the expiry bound by the sealed form or trusted-store integrity.
147         *
148         * @return expiry
149         * @since 1.0.0
150         */
151        public @NonNull Instant getExpiresAt() { return this.expiresAt; }
152
153        /**
154         * Returns application data bound by the seal or trusted-store integrity, still subject to application redirect allowlisting.
155         *
156         * @return data
157         * @since 1.0.0
158         */
159        public @NonNull Map<@NonNull String, @NonNull String> getApplicationData() { return this.applicationData; }
160
161        /**
162         * Seals the complete record under the pending-authorization label and exact application context.
163         *
164         * @param sealer the active and verification keys
165         * @param context an application-chosen fixed context
166         * @return the sealed form for a secure browser cookie
167         * @since 1.0.0
168         */
169        public @NonNull String toSealedForm(@NonNull StateSealer sealer, @NonNull String context) {
170                return SealedStateAccess.get().seal(requireNonNull(sealer), SealedStateType.PENDING_AUTHORIZATION,
171                                PendingAuthorizationCodec.encode(this, null), requireNonNull(context), this.expiresAt);
172        }
173
174        /**
175         * Saves plaintext protocol state with an unkeyed digest of the browser binding. The trusted store must protect
176         * confidentiality and integrity; the digest is a comparison value, not cryptographic authentication. It receives the exact expiry and must
177         * consume atomically. This convenience overload supplies a five-second budget.
178         *
179         * @param store the store
180         * @param browserBinding a browser-specific secret
181         * @return the fixed storage outcome
182         * @since 1.0.0
183         */
184        @CheckReturnValue
185        public @NonNull PendingAuthorizationSaveResult saveToResult(@NonNull PendingAuthorizationStore store, @NonNull BrowserBinding browserBinding) {
186                return saveToResult(store, requireNonNull(browserBinding), Duration.ofSeconds(5));
187        }
188
189        @CheckReturnValue
190        @NonNull PendingAuthorizationSaveResult saveToResult(@NonNull PendingAuthorizationStore store, @NonNull String browserBinding) {
191                return saveToResult(store, browserBinding, Duration.ofSeconds(5));
192        }
193
194        /**
195         * Saves the complete browser-bound record within the supplied operation budget. Continue the browser
196         * authorization flow only after SAVED. A late, failed or possibly completed provider call returns
197         * INDETERMINATE; it must not be treated as an absent record or an instruction to retry.
198         * @param store the store
199         * @param browserBinding browser-specific secret
200         * @param remaining positive time left for this operation
201         * @return the fixed storage outcome
202         * @since 1.0.0
203         */
204        @CheckReturnValue
205        public @NonNull PendingAuthorizationSaveResult saveToResult(@NonNull PendingAuthorizationStore store, @NonNull BrowserBinding browserBinding,
206                        @NonNull Duration remaining) {
207                return saveToResult(store, requireNonNull(browserBinding).toSecretString(), remaining);
208        }
209
210        @CheckReturnValue
211        @NonNull PendingAuthorizationSaveResult saveToResult(@NonNull PendingAuthorizationStore store, @NonNull String browserBinding,
212                        @NonNull Duration remaining) {
213                requireNonNull(store);
214                requireNonNull(browserBinding);
215                if (browserBinding.isEmpty()) throw new IllegalArgumentException("A browser binding must not be empty.");
216                requireNonNull(remaining);
217                if (remaining.isNegative() || remaining.isZero() || Thread.currentThread().isInterrupted())
218                        return PendingAuthorizationSaveResult.UNAVAILABLE;
219                Deadline deadline = Deadline.fromNow(remaining);
220                String encoded = PendingAuthorizationCodec.encode(this, PendingAuthorizationCodec.bindingDigest(browserBinding));
221                if (deadline.isExpired() || Thread.currentThread().isInterrupted())
222                        return PendingAuthorizationSaveResult.UNAVAILABLE;
223                try {
224                        PendingAuthorizationSaveResult result = store.save(browserBinding, this.state, encoded, this.expiresAt, deadline.remaining());
225                        if (result == null || deadline.isExpired() || Thread.currentThread().isInterrupted())
226                                return PendingAuthorizationSaveResult.INDETERMINATE;
227                        return result;
228                } catch (VirtualMachineError fatal) {
229                        throw fatal;
230                } catch (Throwable failure) {
231                        if (failure instanceof InterruptedException) Thread.currentThread().interrupt();
232                        return PendingAuthorizationSaveResult.INDETERMINATE;
233                }
234        }
235
236        @Nullable Duration maxAge() { return this.maxAge; }
237        @NonNull Set<@NonNull String> acrValues() { return this.acrValues; }
238        @Nullable String prompt() { return this.prompt; }
239
240        @NonNull String kind() { return this.kind; }
241        @NonNull String state() { return this.state; }
242        @NonNull String verifier() { return this.verifier; }
243        @Nullable String nonce() { return this.nonce; }
244        @NonNull List<@NonNull URI> resources() { return this.resources; }
245        AuthorizationRequestOptions.@NonNull ResponseMode responseMode() { return this.responseMode; }
246        boolean issuerRequired() { return this.issuerRequired; }
247        @NonNull URI authorizationEndpoint() { return this.authorizationEndpoint; }
248        @NonNull URI tokenEndpoint() { return this.tokenEndpoint; }
249
250        /**
251         * Redacts all pending secrets and application data.
252         *
253         * @return a redacted description
254         * @since 1.0.0
255         */
256        @Override
257        public @NonNull String toString() { return "PendingAuthorization{secrets=<redacted>}"; }
258}