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.StoreTemporalCondition;
021import com.revetsec.StoreTimeObservation;
022import com.revetsec.internal.StoreTimeRules;
023import java.util.HashSet;
024import java.util.List;
025import java.util.Objects;
026import java.util.Set;
027import org.jspecify.annotations.NonNull;
028
029/**
030 * An atomic comparison of every observed version and absence followed by all mutations or none.
031 * The backend must atomically compare its active recovery epoch too. Versions are generated by
032 * core, authenticated in the envelope, preserved exactly and never reused. There is no deletion,
033 * expiry or eviction operation: permanent fences survive credential removal.
034 * @since 1.0.0
035 */
036@javax.annotation.concurrent.Immutable
037@CheckReturnValue
038public final class TotpStoreWrite {
039 private final TotpStoreWrite.@NonNull Purpose purpose;
040 private final @NonNull TotpStoreSnapshot snapshot;
041 private final @NonNull List<TotpStoreWrite.@NonNull Mutation> mutations;
042 private final @NonNull StoreTemporalCondition temporalCondition;
043 private final @NonNull String credentialNamespace;
044 private final @NonNull String recoveryEpoch;
045 private TotpStoreWrite(TotpStoreWrite.@NonNull Purpose purpose, @NonNull TotpStoreSnapshot snapshot,
046   @NonNull List<TotpStoreWrite.@NonNull Mutation> mutations, @NonNull StoreTemporalCondition temporalCondition) {
047  this.purpose = purpose; this.snapshot = snapshot; this.mutations = List.copyOf(mutations);
048  this.temporalCondition = temporalCondition;
049  TotpStoreKey first = snapshot.getEntries().keySet().iterator().next();
050  this.credentialNamespace = first.getCredentialNamespace(); this.recoveryEpoch = first.getRecoveryEpoch();
051 }
052 /**
053  * Combines a complete predicate set with at most 16 distinct insertions or replacements.
054  * Initialization contains exactly the absent namespace record and its insertion. Updates must
055  * include a present namespace record predicate. An empty mutation set remains a predicate barrier.
056  * @param purpose namespace initialization or ordinary update
057  * @param snapshot the complete read set
058  * @param mutations the bounded change set
059  * @param temporalCondition engine-created inclusive floor and optional exclusive expiry
060  * @return the validated write
061  * @since 1.0.0
062  */
063 public static @NonNull TotpStoreWrite fromSnapshotAndMutations(TotpStoreWrite.@NonNull Purpose purpose,
064   @NonNull TotpStoreSnapshot snapshot, @NonNull List<TotpStoreWrite.@NonNull Mutation> mutations,
065   @NonNull StoreTemporalCondition temporalCondition) {
066  Objects.requireNonNull(purpose); Objects.requireNonNull(snapshot); Objects.requireNonNull(mutations);
067  Objects.requireNonNull(temporalCondition);
068  if (!(snapshot.getTimeObservation() instanceof StoreTimeObservation.Healthy healthy)
069    || !StoreTimeRules.sameAdmission(healthy.getAdmission(), temporalCondition.getAdmission())
070    || !healthy.getClockGeneration().equals(temporalCondition.getClockGeneration())
071    || temporalCondition.getNotBeforeInclusive().isBefore(healthy.getObservedAt()))
072   throw new IllegalArgumentException("Inconsistent TOTP temporal condition");
073  if (mutations.size() > 16) throw new IllegalArgumentException("Too many TOTP mutations");
074  TotpStoreKey first = snapshot.getEntries().keySet().iterator().next();
075  TotpStoreKey namespace = TotpStoreKey.forNamespace(first.getCredentialNamespace(), first.getRecoveryEpoch());
076  TotpStoreEntry namespaceEntry = snapshot.getEntries().get(namespace);
077  if (purpose == Purpose.INITIALIZE_NAMESPACE) {
078   if (snapshot.getEntries().size() != 1 || !(namespaceEntry instanceof TotpStoreEntry.Absent)
079     || mutations.size() != 1 || !mutations.get(0).getKey().equals(namespace)
080     || mutations.get(0).kind != Mutation.Kind.INSERT)
081    throw new IllegalArgumentException("Invalid TOTP namespace initialization");
082  } else if (!(namespaceEntry instanceof TotpStoreEntry.Present))
083   throw new IllegalArgumentException("TOTP update requires a present namespace predicate");
084  Set<TotpStoreKey> changed = new HashSet<>();
085  for (Mutation mutation : mutations) {
086   TotpStoreEntry prior = snapshot.getEntry(mutation.getKey());
087   if (!changed.add(mutation.getKey())
088     || (mutation.kind == Mutation.Kind.INSERT && !(prior instanceof TotpStoreEntry.Absent))
089     || (mutation.kind == Mutation.Kind.REPLACE && !(prior instanceof TotpStoreEntry.Present))
090     || (prior instanceof TotpStoreEntry.Present present
091       && present.getRecord().getVersion().equals(mutation.record.getVersion())))
092    throw new IllegalArgumentException("Invalid TOTP store mutation");
093  }
094  return new TotpStoreWrite(purpose, snapshot, mutations, temporalCondition);
095 }
096 /**
097  * Returns the authoritative namespace.
098  * @return the namespace
099  * @since 1.0.0
100  */
101 public @NonNull String getCredentialNamespace() { return this.credentialNamespace; }
102 /**
103  * Returns the recovery epoch that must be checked within the commit transaction.
104  * @return the epoch
105  * @since 1.0.0
106  */
107 public @NonNull String getRecoveryEpoch() { return this.recoveryEpoch; }
108 /**
109  * Returns initialization or update purpose.
110  * @return the purpose
111  * @since 1.0.0
112  */
113 public TotpStoreWrite.@NonNull Purpose getPurpose() { return this.purpose; }
114 /**
115  * Returns every exact version and absence predicate.
116  * @return the snapshot
117  * @since 1.0.0
118  */
119 public @NonNull TotpStoreSnapshot getSnapshot() { return this.snapshot; }
120 /**
121  * Returns the immutable mutation list.
122  * @return the mutations
123  * @since 1.0.0
124  */
125 public @NonNull List<TotpStoreWrite.@NonNull Mutation> getMutations() { return this.mutations; }
126 /**
127  * Returns the original temporal condition to validate under the final transaction locks.
128  * @return the exact inclusive floor and optional exclusive expiry
129  * @since 1.0.0
130  */
131 public @NonNull StoreTemporalCondition getTemporalCondition() { return this.temporalCondition; }
132 /**
133  * Redacts predicates and mutations.
134  * @since 1.0.0
135  */
136 @Override public @NonNull String toString() { return "TotpStoreWrite{write=<redacted>}"; }
137 /**
138  * Distinguishes one-time initialization from updates that cannot recreate the namespace.
139  * @since 1.0.0
140  */
141 @javax.annotation.concurrent.Immutable
142 public enum Purpose {
143  /**
144   * Activate only a newly provisioned recovery epoch.
145   */ INITIALIZE_NAMESPACE,
146  /**
147   * Compare an existing initialized namespace fence.
148   */ UPDATE
149 }
150 /**
151  * An insertion or replacement of one permanent record.
152  * @since 1.0.0
153  */
154 @javax.annotation.concurrent.Immutable
155 public static final class Mutation {
156  private final Mutation.@NonNull Kind kind;
157  private final @NonNull TotpStoreRecord record;
158  private Mutation(Mutation.@NonNull Kind kind, @NonNull TotpStoreRecord record) {
159   this.kind = kind; this.record = Objects.requireNonNull(record);
160  }
161  /**
162   * Inserts only after a matching confirmed absence predicate.
163   * @param record the new record
164   * @return the insertion
165   * @since 1.0.0
166   */
167  public static @NonNull Mutation insert(@NonNull TotpStoreRecord record) { return new Mutation(Kind.INSERT, record); }
168  /**
169   * Replaces only after a matching exact version predicate.
170   * @param record the replacement with a fresh non-reused version
171   * @return the replacement
172   * @since 1.0.0
173   */
174  public static @NonNull Mutation replace(@NonNull TotpStoreRecord record) { return new Mutation(Kind.REPLACE, record); }
175  /**
176   * Returns the changed address.
177   * @return the address
178   * @since 1.0.0
179   */
180  public @NonNull TotpStoreKey getKey() { return this.record.getKey(); }
181  /**
182   * Returns the immutable replacement record.
183   * @return the record
184   * @since 1.0.0
185   */
186  public @NonNull TotpStoreRecord getRecord() { return this.record; }
187  /**
188   * Returns the mutation kind.
189   * @return the kind
190   * @since 1.0.0
191   */
192  public Mutation.@NonNull Kind getKind() { return this.kind; }
193  /**
194   * Redacts the record.
195   * @since 1.0.0
196   */
197  @Override public @NonNull String toString() { return "Mutation{record=<redacted>}"; }
198  /**
199   * Permanent insertion or replacement; deletion is deliberately unavailable.
200   * @since 1.0.0
201   */
202  @javax.annotation.concurrent.Immutable
203  public enum Kind {
204   /**
205    * Insert after confirmed absence.
206    */ INSERT,
207   /**
208    * Replace an exact version.
209    */ REPLACE
210  }
211 }
212}