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.totp; 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.time.DateTimeException; 027import java.time.Duration; 028import java.time.Instant; 029import java.util.Arrays; 030import java.util.Base64; 031import java.util.HashMap; 032import java.util.HashSet; 033import java.util.Map; 034import java.util.Objects; 035import java.util.Optional; 036import java.util.Set; 037import java.util.concurrent.TimeUnit; 038import java.util.concurrent.locks.ReentrantLock; 039import org.jspecify.annotations.NonNull; 040import org.jspecify.annotations.Nullable; 041 042/** 043 * Explicit bounded, volatile, single-process TOTP demonstration store. Restart loses factors, 044 * recovery consumption, replay marks and every recovery/clock fence. Never use it as an automatic 045 * fallback, as authoritative storage for established accounts or across independent processes. 046 * No record is evicted or expired. A configured namespace begins NEW and activates only through 047 * an atomic initialization write. Fresh recovery epochs retain old records and permanently fence 048 * old writers; this process-local history is not a substitute for an external durable controller. 049 * <p>The first operational call establishes this store's own volatile UTC projection and metadata. 050 * The authenticator's worker Clock is not its time source. The store checks its elapsed projection 051 * against a fresh host UTC sample on each operation. A discontinuity starts a new clock generation, 052 * fencing work from the old generation; after a backward step the store remains unavailable until 053 * host UTC reaches the last published point. This is a local demonstration assertion, not external 054 * UTC, restore, device-durability or suspend/rate qualification. 055 * @since 1.0.0 056 */ 057@javax.annotation.concurrent.ThreadSafe 058@CheckReturnValue 059public final class InMemoryTotpStore implements TotpStore { 060 private static final int MAXIMUM_ENTRIES = 65536; 061 private static final long MAXIMUM_BYTES = 268435456L; 062 private static final long MAXIMUM_BUDGET_NANOS = TimeUnit.SECONDS.toNanos(30); 063 private static final @NonNull Duration LOCAL_UTC_ERROR = Duration.ofMillis(250); 064 private final @NonNull ReentrantLock lock = new ReentrantLock(); 065 private final @NonNull String credentialNamespace; 066 private final int maximumEntries; 067 private final long maximumSealedBytes; 068 // All mutable store state below is guarded by lock. 069 private final @NonNull Set<@NonNull String> usedEpochs = new HashSet<>(); 070 private @NonNull String recoveryEpoch; 071 private volatile boolean activated; 072 private @NonNull Map<@NonNull TotpStoreKey, @NonNull TotpStoreRecord> records = Map.of(); 073 private long sealedBytes; 074 private @Nullable EntropySource entropy; 075 private @Nullable StoreAdmission admission; 076 private @Nullable String clockGeneration; 077 private @Nullable Instant authorityAnchor; 078 private @Nullable Instant authorityHighWater; 079 private long authorityStartedNanos; 080 private long lastAuthorityNanos; 081 private boolean authorityContinuityLost; 082 083 private InMemoryTotpStore(@NonNull Builder builder) { 084 this.credentialNamespace = builder.credentialNamespace; 085 this.recoveryEpoch = builder.recoveryEpoch; 086 this.maximumEntries = builder.maximumEntries; 087 this.maximumSealedBytes = builder.maximumSealedBytes; 088 this.usedEpochs.add(this.recoveryEpoch); 089 } 090 /** 091 * Starts configuration for one explicit volatile namespace and fresh recovery epoch. 092 * @param credentialNamespace the visible ASCII namespace 093 * @param recoveryEpoch the never-reused recovery epoch 094 * @return a caller-thread builder 095 * @since 1.0.0 096 */ 097 public static @NonNull Builder withNamespace(@NonNull String credentialNamespace, 098 @NonNull String recoveryEpoch) { return new Builder(credentialNamespace, recoveryEpoch); } 099 100 /** 101 * Provisions and fences to a fresh epoch in this demonstration store. The application must close 102 * admission and drain operations before calling it. Existing records remain retained and count 103 * against capacity. An epoch previously used by this store can never be selected again. 104 * The time projection and authority identity continue; only data recovery admission changes. 105 * This cannot repair lost clock continuity or establish shared-store recovery after restart. 106 * @param recoveryEpoch the fresh never-reused epoch 107 * @param remainingBudget remaining positive administration budget 108 * @return factual COMMITTED, or CAPACITY_REFUSED/UNAVAILABLE before mutation 109 * @since 1.0.0 110 */ 111 public @NonNull TotpStoreCommitResult provisionRecoveryEpoch(@NonNull String recoveryEpoch, 112 @NonNull Duration remainingBudget) { 113 TotpStoreKey.validateScope(recoveryEpoch); 114 long deadline = deadline(remainingBudget); 115 if (!acquire(deadline)) return TotpStoreCommitResult.UNAVAILABLE; 116 try { 117 if (expired(deadline)) return TotpStoreCommitResult.UNAVAILABLE; 118 if (this.usedEpochs.contains(recoveryEpoch)) 119 throw new IllegalArgumentException("TOTP recovery epochs cannot be reused"); 120 if (this.usedEpochs.size() >= MAXIMUM_ENTRIES) return TotpStoreCommitResult.CAPACITY_REFUSED; 121 StoreAdmission nextAdmission; 122 try { 123 StoreAdmission current = operationalAdmission(); 124 nextAdmission = StoreAdmission.fromIdentifiers(current.getAuthorityId(), newIdentity()); 125 } catch (RuntimeException unavailable) { return TotpStoreCommitResult.UNAVAILABLE; } 126 if (expired(deadline)) return TotpStoreCommitResult.UNAVAILABLE; 127 this.usedEpochs.add(recoveryEpoch); 128 this.recoveryEpoch = recoveryEpoch; 129 this.admission = nextAdmission; 130 this.activated = false; 131 // This process knows the assignment happened; a late acknowledgement cannot erase it. 132 return TotpStoreCommitResult.COMMITTED; 133 } finally { this.lock.unlock(); } 134 } 135 136 @Override public @NonNull TotpStoreReadResult read(@NonNull Set<@NonNull TotpStoreKey> keys, 137 @NonNull Duration remainingBudget) { 138 validateKeys(keys); 139 long deadline = deadline(remainingBudget); 140 if (!acquire(deadline)) return TotpStoreReadResult.Unavailable.get(); 141 try { 142 if (expired(deadline)) return TotpStoreReadResult.Unavailable.get(); 143 TotpStoreKey first = keys.iterator().next(); 144 if (!isActiveScope(first.getCredentialNamespace(), first.getRecoveryEpoch())) return TotpStoreReadResult.Fenced.get(); 145 TotpStoreKey root = TotpStoreKey.forNamespace(this.credentialNamespace, this.recoveryEpoch); 146 if ((this.activated && !this.records.containsKey(root)) 147 || (!this.activated && (keys.size() != 1 || !keys.contains(root)))) return TotpStoreReadResult.Unavailable.get(); 148 Map<TotpStoreKey, TotpStoreEntry> observed = new HashMap<>(); 149 for (TotpStoreKey key : keys) { 150 TotpStoreRecord record = this.records.get(key); 151 observed.put(key, record == null ? TotpStoreEntry.Absent.confirmed() : TotpStoreEntry.Present.fromRecord(record)); 152 } 153 StoreTimeObservation time; 154 try { time = observe(); } catch (RuntimeException unavailable) { return TotpStoreReadResult.Unavailable.get(); } 155 TotpStoreSnapshot snapshot = TotpStoreSnapshot.fromEntries(keys, observed, time); 156 return expired(deadline) ? TotpStoreReadResult.Unavailable.get() : TotpStoreReadResult.Available.fromSnapshot(snapshot); 157 } finally { this.lock.unlock(); } 158 } 159 160 @Override public @NonNull TotpStoreCommitReceipt compareAndCommit(@NonNull TotpStoreWrite write, 161 @NonNull Duration remainingBudget) { 162 Objects.requireNonNull(write); 163 long deadline = deadline(remainingBudget); 164 if (!acquire(deadline)) return refuse(TotpStoreCommitResult.UNAVAILABLE); 165 try { 166 if (expired(deadline)) return refuse(TotpStoreCommitResult.UNAVAILABLE); 167 if (!isActiveScope(write.getCredentialNamespace(), write.getRecoveryEpoch())) return refuse(TotpStoreCommitResult.FENCED); 168 StoreAdmission current; 169 try { current = operationalAdmission(); } catch (RuntimeException unavailable) { return refuse(TotpStoreCommitResult.UNAVAILABLE); } 170 StoreTemporalCondition condition = write.getTemporalCondition(); 171 if (!StoreTimeRules.sameAdmission(current, condition.getAdmission()) 172 || !Objects.equals(this.clockGeneration, condition.getClockGeneration())) return refuse(TotpStoreCommitResult.FENCED); 173 TotpStoreKey root = TotpStoreKey.forNamespace(this.credentialNamespace, this.recoveryEpoch); 174 if (write.getPurpose() == TotpStoreWrite.Purpose.INITIALIZE_NAMESPACE) { 175 if (this.activated) return refuse(this.records.containsKey(root) ? TotpStoreCommitResult.CONFLICT : TotpStoreCommitResult.UNAVAILABLE); 176 if (this.records.containsKey(root)) return refuse(TotpStoreCommitResult.UNAVAILABLE); 177 } else if (!this.activated || !this.records.containsKey(root)) return refuse(TotpStoreCommitResult.UNAVAILABLE); 178 for (Map.Entry<TotpStoreKey, TotpStoreEntry> predicate : write.getSnapshot().getEntries().entrySet()) { 179 TotpStoreRecord actual = this.records.get(predicate.getKey()); 180 TotpStoreEntry expected = predicate.getValue(); 181 if ((expected instanceof TotpStoreEntry.Absent && actual != null) 182 || (expected instanceof TotpStoreEntry.Present present 183 && (actual == null || !present.getRecord().getVersion().equals(actual.getVersion())))) return refuse(TotpStoreCommitResult.CONFLICT); 184 } 185 StoreTimeObservation time; 186 try { time = observe(); } catch (RuntimeException unavailable) { return refuse(TotpStoreCommitResult.TIME_UNAVAILABLE); } 187 if (!(time instanceof StoreTimeObservation.Healthy healthy)) return refuse(TotpStoreCommitResult.TIME_UNAVAILABLE); 188 StoreTimeObservation snapshotTime = write.getSnapshot().getTimeObservation(); 189 if (!(snapshotTime instanceof StoreTimeObservation.Healthy attempted) || !StoreTimeRules.sameProfile(attempted, healthy)) 190 return refuse(TotpStoreCommitResult.FENCED); 191 if (healthy.getObservedAt().isBefore(condition.getNotBeforeInclusive())) return refuse(TotpStoreCommitResult.TIME_BEFORE_FLOOR); 192 if (condition.getValidBeforeExclusive().isPresent() 193 && !healthy.getObservedAt().isBefore(condition.getValidBeforeExclusive().get())) return refuse(TotpStoreCommitResult.TIME_EXPIRED); 194 if (write.getMutations().isEmpty()) { 195 TotpStoreCommitReceipt barrier = TotpStoreCommitReceipt.fromCommittedTiming(StoreCommitTiming.fromTimes(healthy, null)); 196 return expired(deadline) ? refuse(TotpStoreCommitResult.UNAVAILABLE) : barrier; 197 } 198 Map<TotpStoreKey, TotpStoreRecord> next = new HashMap<>(this.records); 199 long nextBytes = this.sealedBytes; 200 for (TotpStoreWrite.Mutation mutation : write.getMutations()) { 201 TotpStoreRecord previous = next.put(mutation.getKey(), mutation.getRecord()); 202 if (previous != null) nextBytes -= previous.getSealedBytes().length; 203 nextBytes += mutation.getRecord().getSealedBytes().length; 204 } 205 if (next.size() > this.maximumEntries || nextBytes > this.maximumSealedBytes) return refuse(TotpStoreCommitResult.CAPACITY_REFUSED); 206 TotpStoreCommitReceipt committed = TotpStoreCommitReceipt.fromCommittedTiming(StoreCommitTiming.fromTimes(healthy, null)); 207 if (expired(deadline)) return refuse(TotpStoreCommitResult.UNAVAILABLE); 208 this.records = next; 209 this.sealedBytes = nextBytes; 210 if (write.getPurpose() == TotpStoreWrite.Purpose.INITIALIZE_NAMESPACE) this.activated = true; 211 return committed; 212 } finally { this.lock.unlock(); } 213 } 214 215 private static @NonNull TotpStoreCommitReceipt refuse(@NonNull TotpStoreCommitResult status) { 216 return TotpStoreCommitReceipt.fromRefusal(status); 217 } 218 // Caller holds lock; first operational use, not construction, establishes metadata. 219 private @NonNull StoreAdmission operationalAdmission() { 220 StoreAdmission current = this.admission; 221 if (current == null) { 222 StoreAdmission created = StoreAdmission.fromIdentifiers(newIdentity(), newIdentity()); 223 String clock = newIdentity(); 224 this.admission = created; 225 this.clockGeneration = clock; 226 return created; 227 } 228 return current; 229 } 230 // Caller holds lock; the worker's configured Clock is never sampled here. 231 private @NonNull StoreTimeObservation observe() { 232 StoreAdmission current = operationalAdmission(); 233 long before = System.nanoTime(); 234 Instant captured = Instant.now(); 235 long after = System.nanoTime(); 236 Optional<Duration> bracket = StoreTimeRules.elapsed(before, after); 237 if (bracket.isEmpty() || bracket.get().compareTo(LOCAL_UTC_ERROR) > 0 || !supported(captured)) 238 return StoreTimeObservation.Unavailable.fromAdmission(current); 239 if (this.authorityContinuityLost) 240 return StoreTimeObservation.Unavailable.fromAdmission(current); 241 Instant anchor = this.authorityAnchor; 242 if (anchor == null) { 243 Instant highWater = this.authorityHighWater; 244 if (highWater != null && captured.isBefore(highWater)) 245 return StoreTimeObservation.Unavailable.fromAdmission(current); 246 return reanchor(current, captured, after); 247 } 248 Optional<Duration> lowerElapsed = StoreTimeRules.elapsed(this.authorityStartedNanos, before); 249 Optional<Duration> upperElapsed = StoreTimeRules.elapsed(this.authorityStartedNanos, after); 250 if (StoreTimeRules.elapsed(this.lastAuthorityNanos, after).isEmpty() 251 || lowerElapsed.isEmpty() || upperElapsed.isEmpty()) { 252 this.authorityContinuityLost = true; 253 return StoreTimeObservation.Unavailable.fromAdmission(current); 254 } 255 try { 256 Instant lower = anchor.plus(lowerElapsed.get()); 257 Instant point = anchor.plus(upperElapsed.get()); 258 if (!supported(point)) { 259 this.authorityContinuityLost = true; 260 return StoreTimeObservation.Unavailable.fromAdmission(current); 261 } 262 if (captured.isBefore(lower.minus(LOCAL_UTC_ERROR)) 263 || captured.isAfter(point.plus(LOCAL_UTC_ERROR))) { 264 this.clockGeneration = newIdentity(); 265 this.authorityAnchor = null; 266 this.authorityStartedNanos = after; 267 this.lastAuthorityNanos = after; 268 Instant highWater = this.authorityHighWater; 269 if (highWater != null && captured.isBefore(highWater)) 270 return StoreTimeObservation.Unavailable.fromAdmission(current); 271 return reanchor(current, captured, after); 272 } 273 Instant highWater = this.authorityHighWater; 274 if (highWater != null && point.isBefore(highWater)) { 275 this.authorityContinuityLost = true; 276 return StoreTimeObservation.Unavailable.fromAdmission(current); 277 } 278 this.lastAuthorityNanos = after; 279 this.authorityHighWater = point; 280 return StoreTimeObservation.Healthy.fromObservation(current, Objects.requireNonNull(this.clockGeneration), point, LOCAL_UTC_ERROR); 281 } catch (DateTimeException | ArithmeticException invalid) { 282 this.authorityContinuityLost = true; 283 return StoreTimeObservation.Unavailable.fromAdmission(current); 284 } 285 } 286 private @NonNull StoreTimeObservation reanchor(@NonNull StoreAdmission admission, 287 @NonNull Instant captured, long after) { 288 this.authorityAnchor = captured; 289 this.authorityHighWater = captured; 290 this.authorityStartedNanos = after; 291 this.lastAuthorityNanos = after; 292 return StoreTimeObservation.Healthy.fromObservation(admission, 293 Objects.requireNonNull(this.clockGeneration), captured, LOCAL_UTC_ERROR); 294 } 295 private static boolean supported(@NonNull Instant time) { return time.getEpochSecond() >= 0 && time.getEpochSecond() <= 253402300799L; } 296 private @NonNull String newIdentity() { 297 EntropySource source = this.entropy; 298 if (source == null) { 299 source = EntropySource.fromDefaults(); 300 this.entropy = source; 301 } 302 byte[] value = source.nextBytes(32); 303 try { return Base64.getUrlEncoder().withoutPadding().encodeToString(value); } 304 finally { Arrays.fill(value, (byte) 0); } 305 } 306 private boolean isActiveScope(@NonNull String namespace, @NonNull String epoch) { 307 return this.credentialNamespace.equals(namespace) && this.recoveryEpoch.equals(epoch); 308 } 309 private static void validateKeys(@NonNull Set<@NonNull TotpStoreKey> keys) { 310 Objects.requireNonNull(keys); 311 if (keys.isEmpty() || keys.size() > 16) throw new IllegalArgumentException("Invalid TOTP read set"); 312 TotpStoreKey first = Objects.requireNonNull(keys.iterator().next()); 313 for (TotpStoreKey key : keys) { 314 Objects.requireNonNull(key); 315 if (!key.getCredentialNamespace().equals(first.getCredentialNamespace()) || !key.getRecoveryEpoch().equals(first.getRecoveryEpoch())) 316 throw new IllegalArgumentException("Mixed TOTP read scope"); 317 } 318 } 319 private static long deadline(@NonNull Duration budget) { 320 Objects.requireNonNull(budget); 321 if (budget.isNegative() || budget.isZero()) return 0; 322 long nanos = budget.compareTo(Duration.ofSeconds(30)) >= 0 ? MAXIMUM_BUDGET_NANOS : budget.toNanos(); 323 return System.nanoTime() + nanos; 324 } 325 private boolean acquire(long deadline) { 326 if (deadline == 0) return false; 327 long remaining = deadline - System.nanoTime(); 328 if (remaining <= 0 || Thread.currentThread().isInterrupted()) return false; 329 try { return this.lock.tryLock(remaining, TimeUnit.NANOSECONDS); } 330 catch (InterruptedException interrupted) { Thread.currentThread().interrupt(); return false; } 331 } 332 private static boolean expired(long deadline) { return Thread.currentThread().isInterrupted() || deadline - System.nanoTime() <= 0; } 333 /** 334 * Redacts stored records and recovery configuration. 335 * @return the fixed redacted description 336 * @since 1.0.0 337 */ 338 @Override public @NonNull String toString() { return "InMemoryTotpStore{records=<redacted>}"; } 339 340 /** 341 * Caller-thread configuration for explicit volatile storage. Defaults allow 1024 permanent 342 * records and 16 MiB of sealed payload. Building performs no I/O and creates no threads. 343 * @since 1.0.0 344 */ 345 @javax.annotation.concurrent.NotThreadSafe 346 @CheckReturnValue 347 public static final class Builder { 348 private final @NonNull String credentialNamespace; 349 private final @NonNull String recoveryEpoch; 350 private int maximumEntries = 1024; 351 private long maximumSealedBytes = 16777216L; 352 private Builder(@NonNull String namespace, @NonNull String epoch) { 353 TotpStoreKey.validateScope(namespace); TotpStoreKey.validateScope(epoch); 354 this.credentialNamespace = namespace; this.recoveryEpoch = epoch; 355 } 356 /** 357 * Sets the permanent record-count capacity; records are never evicted. 358 * @param maximumEntries capacity from 1 to 65536, including namespace and old-epoch records; null restores 1024 359 * @return this builder 360 * @since 1.0.0 361 */ 362 public @NonNull Builder maximumEntries(@Nullable Integer maximumEntries) { 363 if (maximumEntries == null) { this.maximumEntries = 1024; return this; } 364 if (maximumEntries < 1 || maximumEntries > MAXIMUM_ENTRIES) 365 throw new IllegalArgumentException("Invalid TOTP record capacity"); 366 this.maximumEntries = maximumEntries; return this; 367 } 368 /** 369 * Sets aggregate sealed-payload capacity. 370 * @param maximumSealedBytes capacity from 1 to 268435456 bytes; null restores 16 MiB 371 * @return this builder 372 * @since 1.0.0 373 */ 374 public @NonNull Builder maximumSealedBytes(@Nullable Long maximumSealedBytes) { 375 if (maximumSealedBytes == null) { this.maximumSealedBytes = 16777216L; return this; } 376 if (maximumSealedBytes < 1 || maximumSealedBytes > MAXIMUM_BYTES) 377 throw new IllegalArgumentException("Invalid TOTP byte capacity"); 378 this.maximumSealedBytes = maximumSealedBytes; return this; 379 } 380 /** 381 * Creates a fresh process-local store with NEW activation state. 382 * @return the explicitly selected volatile store 383 * @since 1.0.0 384 */ 385 public @NonNull InMemoryTotpStore build() { return new InMemoryTotpStore(this); } 386 } 387}