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.webauthn;
018
019import com.google.errorprone.annotations.CheckReturnValue;
020import com.revetsec.StoreAdmission;
021import com.revetsec.StoreCommitTiming;
022import com.revetsec.StoreTemporalCondition;
023import com.revetsec.StoreTimeObservation;
024import com.revetsec.internal.StoreTimeRules;
025import com.revetsec.internal.crypto.EntropySource;
026import java.nio.ByteBuffer;
027import java.time.DateTimeException;
028import java.time.Duration;
029import java.time.Instant;
030import java.util.Arrays;
031import java.util.Base64;
032import java.util.HashMap;
033import java.util.HashSet;
034import java.util.Map;
035import java.util.Objects;
036import java.util.Optional;
037import java.util.Set;
038import java.util.concurrent.TimeUnit;
039import java.util.concurrent.locks.ReentrantLock;
040import org.jspecify.annotations.NonNull;
041import org.jspecify.annotations.Nullable;
042
043/**
044 * Explicit bounded, volatile, single-process WebAuthn store. Restart loses ceremonies,
045 * credentials, ownership tombstones, account fences and every recovery/time fence. Use durable
046 * shared authoritative storage for established accounts or deployments with several nodes.
047 * No ordinary read, predicate barrier or refusal reclaims records. A successful mutating commit
048 * atomically reclaims expired ceremonies outside its predicate set using the same fresh admitted
049 * store time. Permanent records are never evicted to make room.
050 * <p>The first operational call establishes this store's own volatile UTC/elapsed projection and
051 * admission metadata. The relying party's worker Clock is never its time source. Each operation
052 * checks the projection against fresh host UTC. A discontinuity starts a new clock generation,
053 * fencing old work; after a backward step the store waits for the last published time before it
054 * resumes. Construction performs no I/O, random acquisition or time sampling. This demonstration
055 * does not qualify external UTC, restore, device durability, suspend/rate continuity or a shared
056 * deployment.
057 * @since 1.0.0
058 */
059@javax.annotation.concurrent.ThreadSafe
060@CheckReturnValue
061public final class InMemoryWebAuthnStore implements WebAuthnStore {
062        private static final long MAXIMUM_BYTES = 268435456L;
063        private static final int MAXIMUM_ENTRIES = 65536;
064        private static final long MAXIMUM_BUDGET_NANOS = TimeUnit.SECONDS.toNanos(30);
065        private static final @NonNull Duration LOCAL_UTC_ERROR = Duration.ofMillis(250);
066        private final @NonNull ReentrantLock lock = new ReentrantLock();
067        private final int maximumEntries;
068        private final long maximumSealedBytes;
069        // Mutable state below is guarded by lock; construction only retains configuration.
070        private @NonNull Map<@NonNull WebAuthnStoreKey, @NonNull Stored> entries = Map.of();
071        private @NonNull Set<@NonNull String> activatedScopes = Set.of();
072        private long sealedBytes;
073        private long sequence;
074        private byte @Nullable [] versionPrefix;
075        private @Nullable EntropySource entropy;
076        private @Nullable StoreAdmission admission;
077        private @Nullable String clockGeneration;
078        private @Nullable Instant authorityAnchor;
079        private @Nullable Instant authorityHighWater;
080        private long authorityStartedNanos;
081        private long lastAuthorityNanos;
082        private boolean authorityContinuityLost;
083
084        private InMemoryWebAuthnStore(int maximumEntries, long maximumSealedBytes) {
085                this.maximumEntries = maximumEntries;
086                this.maximumSealedBytes = maximumSealedBytes;
087        }
088
089        /**
090         * Creates empty volatile storage with explicit count and aggregate sealed-byte capacity.
091         * Expired ceremonies may be reclaimed by a later successful mutating commit; permanent records
092         * are never evicted. One record may be up to 262144 bytes.
093         * @param maximumEntries capacity from 1 to 65536
094         * @param maximumSealedBytes aggregate capacity from 1 to 268435456 bytes
095         * @return a new empty process-local store
096         * @since 1.0.0
097         */
098        public static @NonNull InMemoryWebAuthnStore fromLimits(@NonNull Integer maximumEntries,
099                        @NonNull Long maximumSealedBytes) {
100                Objects.requireNonNull(maximumEntries);
101                Objects.requireNonNull(maximumSealedBytes);
102                if (maximumEntries < 1 || maximumEntries > MAXIMUM_ENTRIES
103                                || maximumSealedBytes < 1 || maximumSealedBytes > MAXIMUM_BYTES)
104                        throw new IllegalArgumentException("Invalid WebAuthn store limits");
105                return new InMemoryWebAuthnStore(maximumEntries, maximumSealedBytes);
106        }
107
108        @Override public @NonNull WebAuthnStoreReadResult read(@NonNull Set<@NonNull WebAuthnStoreKey> keys,
109                        @NonNull Duration remainingBudget) {
110                WebAuthnStoreSnapshot.validateRequestedKeys(keys);
111                long deadline = deadline(remainingBudget);
112                if (!acquire(deadline)) return WebAuthnStoreReadResult.Unavailable.get();
113                try {
114                        if (expired(deadline) || missingEstablishedRoot(keys)) return WebAuthnStoreReadResult.Unavailable.get();
115                        Map<WebAuthnStoreKey, WebAuthnStoreEntry> observed = new HashMap<>();
116                        for (WebAuthnStoreKey key : keys) {
117                                Stored stored = this.entries.get(key);
118                                observed.put(key, stored == null ? WebAuthnStoreEntry.Absent.confirmed()
119                                                : WebAuthnStoreEntry.Present.fromVersionAndSealedBytes(stored.version, stored.sealedBytes));
120                        }
121                        StoreTimeObservation time;
122                        try { time = observe(); } catch (RuntimeException unavailable) { return WebAuthnStoreReadResult.Unavailable.get(); }
123                        WebAuthnStoreSnapshot snapshot = WebAuthnStoreSnapshot.fromEntries(keys, observed, time);
124                        return expired(deadline) ? WebAuthnStoreReadResult.Unavailable.get() : WebAuthnStoreReadResult.Available.fromSnapshot(snapshot);
125                } finally { this.lock.unlock(); }
126        }
127
128        @Override public @NonNull WebAuthnStoreCommitReceipt compareAndCommit(@NonNull WebAuthnStoreWrite write,
129                        @NonNull Duration remainingBudget) {
130                Objects.requireNonNull(write);
131                long deadline = deadline(remainingBudget);
132                if (!acquire(deadline)) return refuse(WebAuthnStoreCommitResult.UNAVAILABLE);
133                try {
134                        if (expired(deadline) || missingEstablishedRoot(write.getSnapshot().getEntries().keySet())) return refuse(WebAuthnStoreCommitResult.UNAVAILABLE);
135                        StoreAdmission current;
136                        try { current = operationalAdmission(); } catch (RuntimeException unavailable) { return refuse(WebAuthnStoreCommitResult.UNAVAILABLE); }
137                        StoreTemporalCondition condition = write.getTemporalCondition();
138                        if (!StoreTimeRules.sameAdmission(current, condition.getAdmission())
139                                        || !Objects.equals(this.clockGeneration, condition.getClockGeneration())) return refuse(WebAuthnStoreCommitResult.FENCED);
140                        for (Map.Entry<WebAuthnStoreKey, WebAuthnStoreEntry> predicate : write.getSnapshot().getEntries().entrySet()) {
141                                Stored actual = this.entries.get(predicate.getKey());
142                                WebAuthnStoreEntry expected = predicate.getValue();
143                                if ((expected instanceof WebAuthnStoreEntry.Absent && actual != null)
144                                                || (expected instanceof WebAuthnStoreEntry.Present present
145                                                                && (actual == null || !Arrays.equals(present.getVersion(), actual.version)))) return refuse(WebAuthnStoreCommitResult.CONFLICT);
146                        }
147                        StoreTimeObservation time;
148                        try { time = observe(); } catch (RuntimeException unavailable) { return refuse(WebAuthnStoreCommitResult.TIME_UNAVAILABLE); }
149                        if (!(time instanceof StoreTimeObservation.Healthy healthy)) return refuse(WebAuthnStoreCommitResult.TIME_UNAVAILABLE);
150                        if (!(write.getSnapshot().getTimeObservation() instanceof StoreTimeObservation.Healthy original)
151                                        || !StoreTimeRules.sameProfile(original, healthy)) return refuse(WebAuthnStoreCommitResult.FENCED);
152                        if (healthy.getObservedAt().isBefore(condition.getNotBeforeInclusive())) return refuse(WebAuthnStoreCommitResult.TIME_BEFORE_FLOOR);
153                        if (condition.getValidBeforeExclusive().isPresent()
154                                        && !healthy.getObservedAt().isBefore(condition.getValidBeforeExclusive().orElseThrow())) return refuse(WebAuthnStoreCommitResult.TIME_EXPIRED);
155                        WebAuthnStoreCommitReceipt committed = WebAuthnStoreCommitReceipt.fromCommittedTiming(StoreCommitTiming.fromTimes(healthy, null));
156                        if (write.getMutations().isEmpty()) return expired(deadline) ? refuse(WebAuthnStoreCommitResult.UNAVAILABLE) : committed;
157                        Map<WebAuthnStoreKey, Stored> next = new HashMap<>(this.entries);
158                        Set<String> nextActivated = new HashSet<>(this.activatedScopes);
159                        long nextBytes = this.sealedBytes, nextSequence = this.sequence;
160                        for (var iterator = next.entrySet().iterator(); iterator.hasNext();) {
161                                Map.Entry<WebAuthnStoreKey, Stored> item = iterator.next();
162                                Stored stored = item.getValue();
163                                if (item.getKey().getKind() == WebAuthnStoreKey.Kind.CEREMONY
164                                                && stored.expiresAt != null && !stored.expiresAt.isAfter(healthy.getObservedAt())
165                                                && !write.getSnapshot().getEntries().containsKey(item.getKey())) {
166                                        nextBytes -= stored.sealedBytes.length;
167                                        iterator.remove();
168                                }
169                        }
170                        for (WebAuthnStoreWrite.Mutation mutation : write.getMutations()) {
171                                WebAuthnStoreKey key = mutation.getKey();
172                                Stored prior = next.get(key);
173                                if (prior != null) nextBytes -= prior.sealedBytes.length;
174                                if (mutation.getKind() == WebAuthnStoreWrite.Mutation.Kind.DELETE) next.remove(key);
175                                else {
176                                        if (nextSequence == Long.MAX_VALUE) return refuse(WebAuthnStoreCommitResult.CAPACITY);
177                                        byte[] prefix = this.versionPrefix;
178                                        if (prefix == null) { prefix = randomBytes(16); this.versionPrefix = prefix; }
179                                        byte[] version = ByteBuffer.allocate(24).put(prefix).putLong(++nextSequence).array();
180                                        byte[] bytes = mutation.getSealedBytes().orElseThrow();
181                                        next.put(key, new Stored(version, bytes, mutation.getExpiresAt().orElse(null))); nextBytes += bytes.length;
182                                        if (key.getKind() == WebAuthnStoreKey.Kind.NAMESPACE_CLOCK) nextActivated.add(WebAuthnStoreSnapshot.scopeOf(key));
183                                }
184                        }
185                        if (next.size() > this.maximumEntries || nextBytes > this.maximumSealedBytes || nextActivated.size() > MAXIMUM_ENTRIES)
186                                return refuse(WebAuthnStoreCommitResult.CAPACITY);
187                        if (expired(deadline)) return refuse(WebAuthnStoreCommitResult.UNAVAILABLE);
188                        this.entries = next; this.sealedBytes = nextBytes; this.sequence = nextSequence; this.activatedScopes = nextActivated;
189                        // This process knows the assignment happened; lateness cannot erase that factual commitment.
190                        return committed;
191                } finally { this.lock.unlock(); }
192        }
193
194        private boolean missingEstablishedRoot(@NonNull Set<@NonNull WebAuthnStoreKey> keys) {
195                String scope = WebAuthnStoreSnapshot.scopeOf(keys.iterator().next());
196                boolean asksRoot = false, rootPresent = false, hasData = false;
197                for (WebAuthnStoreKey key : keys) {
198                        if (key.getKind() == WebAuthnStoreKey.Kind.NAMESPACE_CLOCK) {
199                                if (this.entries.containsKey(key)) return false;
200                                asksRoot = true;
201                        }
202                }
203                if (!asksRoot && !this.activatedScopes.contains(scope)) return false;
204                for (WebAuthnStoreKey key : this.entries.keySet()) {
205                        if (!scope.equals(WebAuthnStoreSnapshot.scopeOf(key))) continue;
206                        hasData = true;
207                        if (key.getKind() == WebAuthnStoreKey.Kind.NAMESPACE_CLOCK) { rootPresent = true; break; }
208                }
209                return !rootPresent && (this.activatedScopes.contains(scope) || (asksRoot && hasData));
210        }
211
212        private static @NonNull WebAuthnStoreCommitReceipt refuse(@NonNull WebAuthnStoreCommitResult status) { return WebAuthnStoreCommitReceipt.fromRefusal(status); }
213
214        private @NonNull StoreAdmission operationalAdmission() {
215                StoreAdmission current = this.admission;
216                if (current == null) {
217                        current = StoreAdmission.fromIdentifiers(newIdentity(), newIdentity());
218                        this.clockGeneration = newIdentity(); this.admission = current;
219                }
220                return current;
221        }
222        private @NonNull StoreTimeObservation observe() {
223                StoreAdmission current = operationalAdmission();
224                long before = System.nanoTime();
225                Instant captured = Instant.now();
226                long after = System.nanoTime();
227                Optional<Duration> bracket = StoreTimeRules.elapsed(before, after);
228                if (bracket.isEmpty() || bracket.get().compareTo(LOCAL_UTC_ERROR) > 0 || !supported(captured))
229                        return StoreTimeObservation.Unavailable.fromAdmission(current);
230                if (this.authorityContinuityLost)
231                        return StoreTimeObservation.Unavailable.fromAdmission(current);
232                Instant anchor = this.authorityAnchor;
233                if (anchor == null) {
234                        Instant highWater = this.authorityHighWater;
235                        if (highWater != null && captured.isBefore(highWater))
236                                return StoreTimeObservation.Unavailable.fromAdmission(current);
237                        return reanchor(current, captured, after);
238                }
239                Optional<Duration> lowerElapsed = StoreTimeRules.elapsed(this.authorityStartedNanos, before);
240                Optional<Duration> upperElapsed = StoreTimeRules.elapsed(this.authorityStartedNanos, after);
241                if (StoreTimeRules.elapsed(this.lastAuthorityNanos, after).isEmpty()
242                                || lowerElapsed.isEmpty() || upperElapsed.isEmpty()) {
243                        this.authorityContinuityLost = true; return StoreTimeObservation.Unavailable.fromAdmission(current);
244                }
245                try {
246                        Instant lower = anchor.plus(lowerElapsed.get());
247                        Instant point = anchor.plus(upperElapsed.get());
248                        if (!supported(point)) { this.authorityContinuityLost = true; return StoreTimeObservation.Unavailable.fromAdmission(current); }
249                        if (captured.isBefore(lower.minus(LOCAL_UTC_ERROR))
250                                        || captured.isAfter(point.plus(LOCAL_UTC_ERROR))) {
251                                this.clockGeneration = newIdentity();
252                                this.authorityAnchor = null;
253                                this.authorityStartedNanos = after;
254                                this.lastAuthorityNanos = after;
255                                Instant highWater = this.authorityHighWater;
256                                if (highWater != null && captured.isBefore(highWater))
257                                        return StoreTimeObservation.Unavailable.fromAdmission(current);
258                                return reanchor(current, captured, after);
259                        }
260                        Instant highWater = this.authorityHighWater;
261                        if (highWater != null && point.isBefore(highWater)) {
262                                this.authorityContinuityLost = true;
263                                return StoreTimeObservation.Unavailable.fromAdmission(current);
264                        }
265                        this.lastAuthorityNanos = after;
266                        this.authorityHighWater = point;
267                        return StoreTimeObservation.Healthy.fromObservation(current, Objects.requireNonNull(this.clockGeneration), point, LOCAL_UTC_ERROR);
268                } catch (DateTimeException | ArithmeticException invalid) {
269                        this.authorityContinuityLost = true; return StoreTimeObservation.Unavailable.fromAdmission(current);
270                }
271        }
272        private @NonNull StoreTimeObservation reanchor(@NonNull StoreAdmission admission,
273                        @NonNull Instant captured, long after) {
274                this.authorityAnchor = captured;
275                this.authorityHighWater = captured;
276                this.authorityStartedNanos = after;
277                this.lastAuthorityNanos = after;
278                return StoreTimeObservation.Healthy.fromObservation(admission,
279                                Objects.requireNonNull(this.clockGeneration), captured, LOCAL_UTC_ERROR);
280        }
281        private static boolean supported(@NonNull Instant time) { return time.getEpochSecond() >= 0 && time.getEpochSecond() <= 253402300799L; }
282        private byte @NonNull [] randomBytes(int count) {
283                EntropySource source = this.entropy;
284                if (source == null) { source = EntropySource.fromDefaults(); this.entropy = source; }
285                return source.nextBytes(count);
286        }
287        private @NonNull String newIdentity() {
288                byte[] value = randomBytes(32);
289                try { return Base64.getUrlEncoder().withoutPadding().encodeToString(value); }
290                finally { Arrays.fill(value, (byte) 0); }
291        }
292        private static long deadline(@NonNull Duration budget) {
293                Objects.requireNonNull(budget);
294                if (budget.isNegative() || budget.isZero()) return 0;
295                return System.nanoTime() + (budget.compareTo(Duration.ofSeconds(30)) >= 0 ? MAXIMUM_BUDGET_NANOS : budget.toNanos());
296        }
297        private boolean acquire(long deadline) {
298                if (deadline == 0) return false;
299                long remaining = deadline - System.nanoTime();
300                if (remaining <= 0 || Thread.currentThread().isInterrupted()) return false;
301                try { return this.lock.tryLock(remaining, TimeUnit.NANOSECONDS); }
302                catch (InterruptedException interrupted) { Thread.currentThread().interrupt(); return false; }
303        }
304        private static boolean expired(long deadline) { return Thread.currentThread().isInterrupted() || deadline - System.nanoTime() <= 0; }
305
306        /** Redacts stored records and admission metadata. @since 1.0.0 */
307        @Override public @NonNull String toString() { return "InMemoryWebAuthnStore{records=<redacted>}"; }
308
309        private static final class Stored {
310                private final byte @NonNull [] version;
311                private final byte @NonNull [] sealedBytes;
312                private final @Nullable Instant expiresAt;
313                private Stored(byte @NonNull [] version, byte @NonNull [] sealedBytes, @Nullable Instant expiresAt) {
314                        this.version = version; this.sealedBytes = sealedBytes; this.expiresAt = expiresAt;
315                }
316        }
317}