qualia2fa-core 0.1.1

Qualia2FA core library: TOTP/HOTP primitives, encrypted vault and device sync
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
// Copyright (C) 2026 Qualia2FA contributors
//
// This library is free software; you can redistribute it and/or modify it under
// the terms of the GNU Lesser General Public License as published by the Free
// Software Foundation; either version 3 of the License, or (at your option) any
// later version.
//
// This library is distributed in the hope that it will be useful, but WITHOUT
// ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
// FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
// details.
//
// You should have received a copy of the GNU Lesser General Public License
// along with this library; if not, see <https://www.gnu.org/licenses/>.

//! Applying the user's decision to one conflict.
//!
//! [`merge_into`](crate::sync::merge_into) reports a [`Conflict`] instead of deciding, because
//! the two sides disagree about content a human cares about: which version of an entry is the
//! real one, and whether an entry was deleted. This module holds the other half — what
//! "keep mine" and "take theirs" mean for each shape of conflict, and what they write into the
//! vault.
//!
//! # The decision is applied locally, and is not remembered
//!
//! Nothing here records *why* the user decided what they decided, so the same disagreement can
//! be reported again by a later sync. Applying "take theirs" does converge: a second merge of
//! the same peer payload finds the two sides identical and reports no conflict at all. Applying
//! "keep mine" cannot converge on its own — the peer still holds the other version, and its own
//! user is asked when it is their turn. A record of decisions that both sides apply without
//! asking is not implemented; see the D2 note in the project plan.
//!
//! # This layer never picks a side
//!
//! Every function here takes the [`Decision`] as an argument. Timestamps are not consulted,
//! even where they are known: the peer fills in its own, and deleting an entry is
//! irreversible, so "which side is newer" is a fact to show the user, not a rule to apply
//! behind their back.

use crate::Result;
use crate::sync::merge::{Conflict, ConflictKind};
use crate::vault::Vault;

/// What the user decided about one conflict.
///
/// The two variants are the whole vocabulary on purpose: the alternative — one "resolution"
/// value per conflict shape — would let a caller pair the wrong decision with a shape, and the
/// shapes are not symmetric ("keep" means "keep the entry" in one and "keep it deleted" in
/// another).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Decision {
    /// Keep the state of **this** device; the peer's version is discarded.
    KeepLocal,
    /// Take the peer's version, discarding the state of this device.
    TakeIncoming,
}

/// What applying a [`Decision`] did.
///
/// Returned rather than implied so that a caller can report it, and so that a test can assert
/// which of the three writes happened instead of only that the entry count changed.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Adjudicated {
    /// The local version stays, and nothing was written.
    KeptLocal,
    /// The peer's entry replaced the local entry of the same ID.
    TookIncomingEntry,
    /// The deletion was applied: the local entry is gone and a tombstone covers the ID.
    DeletionApplied,
    /// The entry came back: the local tombstone was dropped in favour of the peer's entry.
    Restored,
}

/// Applies one user decision to the vault.
///
/// # What each shape of conflict means
///
/// | conflict | [`Decision::KeepLocal`] | [`Decision::TakeIncoming`] |
/// |---|---|---|
/// | [`ConflictKind::EntryMismatch`] | the local entry stays | the peer's entry replaces it |
/// | [`ConflictKind::DeletionConflict`] with `local: None` — the peer deleted it | the local entry stays | the entry is deleted and the tombstone recorded |
/// | [`ConflictKind::DeletionConflict`] with `local: Some(..)` — this device deleted it | it stays deleted | the peer's entry is restored and the local tombstone dropped |
///
/// The two [`ConflictKind::DeletionConflict`] directions are told apart by `local`, which is
/// the convention [`crate::sync::merge_into`] documents: the peer's record is the one that is
/// **not** yet in the vault, so the local content appears there only when the local side has
/// no live entry to read.
///
/// # Restoring an entry removes the tombstone
///
/// The tombstone is what tells every other device that the deletion happened. Keeping it
/// while the entry is alive would leave a state that is neither: the payload builder sends
/// the tombstone and not the entry (see [`crate::sync::Payload::from_vault`]), so the peer
/// would delete the entry again.
///
/// # Errors
///
/// [`crate::Error::VaultEntryNotFound`] when the conflict no longer describes the vault —
/// the local entry is gone, or the entry was already re-created. Decisions belong to the
/// merge that produced them; a stale one is refused rather than applied to whatever is there
/// now. Nothing is written when the call fails.
///
/// Structural failures are propagated from [`crate::vault::Entry::duplicate`], which copies
/// the entry that is about to be written.
pub fn adjudicate(
    vault: &mut Vault,
    conflict: &Conflict,
    decision: Decision,
) -> Result<Adjudicated> {
    match &conflict.kind {
        ConflictKind::EntryMismatch { incoming, .. } => match decision {
            Decision::KeepLocal => Ok(Adjudicated::KeptLocal),
            Decision::TakeIncoming => {
                vault.replace(conflict.entry_id, incoming.duplicate()?)?;
                Ok(Adjudicated::TookIncomingEntry)
            }
        },
        ConflictKind::DeletionConflict {
            local, incoming, ..
        } => match (decision, local) {
            (Decision::KeepLocal, _) => Ok(Adjudicated::KeptLocal),
            (Decision::TakeIncoming, None) => {
                vault.remove(&conflict.entry_id, incoming.deleted_at);
                vault.record_tombstone(incoming.as_ref().clone());
                Ok(Adjudicated::DeletionApplied)
            }
            (Decision::TakeIncoming, Some(entry)) => {
                vault.insert_with_id(conflict.entry_id, entry.duplicate()?)?;
                vault.forget_tombstone(&conflict.entry_id);
                Ok(Adjudicated::Restored)
            }
        },
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::otp::{Algorithm, Digits, OtpSecret};
    use crate::sync::{MergedRecord, RecordSet, merge_into};
    use crate::vault::{Entry, EntryId, Timestamp, Tombstone};

    /// A sample entry whose content is recognisable in an assertion.
    fn sample_entry(name: &str, updated_at: u64) -> Entry {
        Entry::new(
            name.into(),
            Some("Example".into()),
            "user@example.com".into(),
            OtpSecret::from_base32("JBSWY3DPEHPK3PXP").expect("valid Base32"),
            Algorithm::Sha1,
            Digits::Six,
            30,
            None,
            String::new(),
            Timestamp::from(1_700_000_000_u64),
            Timestamp::from(updated_at),
        )
        .expect("the fields are valid")
    }

    fn entry_id(seed: u8) -> EntryId {
        EntryId::from_bytes([seed; 16])
    }

    /// A vault holding one entry under `id`.
    fn vault_with(id: EntryId, name: &str, updated_at: u64) -> Vault {
        let mut vault = Vault::new();
        vault
            .insert_with_id(id, sample_entry(name, updated_at))
            .expect("the vault is empty");
        vault
    }

    /// A vault that has deleted `id` at `deleted_at`.
    fn vault_that_deleted(id: EntryId, deleted_at: u64) -> Vault {
        let mut vault = vault_with(id, "deleted", deleted_at);
        vault.remove(&id, Timestamp::from(deleted_at));
        vault
    }

    /// The conflict a peer's differing entry produces when both sides hold the ID.
    fn mismatch(id: EntryId, local: &Entry, incoming: &Entry) -> Conflict {
        Conflict {
            entry_id: id,
            kind: ConflictKind::EntryMismatch {
                local: Box::new(local.duplicate().expect("the entry can be copied")),
                incoming: Box::new(incoming.duplicate().expect("the entry can be copied")),
            },
        }
    }

    /// The conflict a peer's entry produces when this device has deleted the ID.
    fn peer_entry_against_local_tombstone(
        id: EntryId,
        incoming: &Entry,
        deleted_at: u64,
    ) -> Conflict {
        Conflict {
            entry_id: id,
            kind: ConflictKind::DeletionConflict {
                local: Some(Box::new(
                    incoming.duplicate().expect("the entry can be copied"),
                )),
                incoming: Box::new(Tombstone {
                    entry_id: id,
                    deleted_at: Timestamp::from(deleted_at),
                    deleted_by: None,
                }),
                local_is_newer: incoming.updated_at > Timestamp::from(deleted_at),
            },
        }
    }

    /// The conflict a peer's tombstone produces when this device holds a newer entry.
    fn peer_tombstone_against_local_entry(id: EntryId, deleted_at: u64) -> Conflict {
        Conflict {
            entry_id: id,
            kind: ConflictKind::DeletionConflict {
                local: None,
                incoming: Box::new(Tombstone {
                    entry_id: id,
                    deleted_at: Timestamp::from(deleted_at),
                    deleted_by: None,
                }),
                local_is_newer: true,
            },
        }
    }

    /// Merges one peer entry again, as a later sync of the same peer would.
    fn merge_peer_entry(
        vault: &mut Vault,
        id: EntryId,
        entry: &Entry,
    ) -> crate::sync::MergeOutcome {
        let mut records = RecordSet::new();
        records.insert(MergedRecord::Entry {
            id,
            entry: Box::new(entry.duplicate().expect("the entry can be copied")),
        });
        merge_into(vault, &records).expect("the merge only copies entries")
    }

    /// Merges one peer tombstone again.
    fn merge_peer_tombstone(vault: &mut Vault, tombstone: &Tombstone) -> crate::sync::MergeOutcome {
        let mut records = RecordSet::new();
        records.insert(MergedRecord::Tombstone(Box::new(tombstone.clone())));
        merge_into(vault, &records).expect("a tombstone holds no key material to copy")
    }

    #[test]
    fn taking_the_peer_version_replaces_the_local_entry() {
        let id = entry_id(1);
        let local = sample_entry("local", 1_700_000_000);
        let peer = sample_entry("peer", 1_700_000_100);
        let mut vault = vault_with(id, "local", 1_700_000_000);

        let outcome = adjudicate(
            &mut vault,
            &mismatch(id, &local, &peer),
            Decision::TakeIncoming,
        )
        .expect("the entry is present");

        assert_eq!(outcome, Adjudicated::TookIncomingEntry);
        assert_eq!(vault.len(), 1, "replacing must not add an entry");
        let stored = vault.get(&id).expect("the entry is still there");
        assert_eq!(stored.name, "peer");
        assert_eq!(
            stored.updated_at, peer.updated_at,
            "the peer's content is adopted as it is, timestamps included"
        );

        let again = merge_peer_entry(&mut vault, id, &peer);
        assert!(
            again.conflicts.is_empty() && again.unchanged == 1,
            "the decision must close the conflict: {again:?}"
        );
    }

    #[test]
    fn keeping_the_local_version_writes_nothing() {
        let id = entry_id(2);
        let local = sample_entry("local", 1_700_000_000);
        let peer = sample_entry("peer", 1_700_000_100);
        let mut vault = vault_with(id, "local", 1_700_000_000);

        let outcome = adjudicate(
            &mut vault,
            &mismatch(id, &local, &peer),
            Decision::KeepLocal,
        )
        .expect("keeping the local version cannot fail");

        assert_eq!(outcome, Adjudicated::KeptLocal);
        assert_eq!(vault.get(&id).expect("the entry stays").name, "local");
    }

    #[test]
    fn a_peer_deletion_is_applied_with_the_peers_own_tombstone() {
        let id = entry_id(3);
        let mut vault = vault_with(id, "local", 1_700_000_200);

        let outcome = adjudicate(
            &mut vault,
            &peer_tombstone_against_local_entry(id, 1_700_000_100),
            Decision::TakeIncoming,
        )
        .expect("the entry is present");

        assert_eq!(outcome, Adjudicated::DeletionApplied);
        assert_eq!(vault.len(), 0, "the entry must be gone");
        let tombstone = vault
            .get_tombstone(&id)
            .cloned()
            .expect("the deletion is recorded");
        assert_eq!(tombstone.deleted_at, Timestamp::from(1_700_000_100_u64));
        assert_eq!(
            vault.tombstone_count(),
            1,
            "exactly one tombstone: the entry's own deletion must not be recorded twice"
        );

        let again = merge_peer_tombstone(&mut vault, &tombstone);
        assert!(
            again.conflicts.is_empty() && again.unchanged == 1,
            "the decision must close the conflict: {again:?}"
        );
    }

    #[test]
    fn keeping_the_entry_overrules_a_peer_deletion() {
        let id = entry_id(4);
        let mut vault = vault_with(id, "local", 1_700_000_200);

        let outcome = adjudicate(
            &mut vault,
            &peer_tombstone_against_local_entry(id, 1_700_000_100),
            Decision::KeepLocal,
        )
        .expect("keeping the local version cannot fail");

        assert_eq!(outcome, Adjudicated::KeptLocal);
        assert_eq!(vault.len(), 1, "the entry stays");
        assert_eq!(
            vault.tombstone_count(),
            0,
            "the peer's tombstone must not be recorded: it was not accepted"
        );
    }

    #[test]
    fn the_peer_entry_restores_an_entry_deleted_here() {
        let id = entry_id(5);
        let peer = sample_entry("peer", 1_700_000_300);
        let mut vault = vault_that_deleted(id, 1_700_000_100);

        let outcome = adjudicate(
            &mut vault,
            &peer_entry_against_local_tombstone(id, &peer, 1_700_000_100),
            Decision::TakeIncoming,
        )
        .expect("nothing is copied from the vault here");

        assert_eq!(outcome, Adjudicated::Restored);
        assert_eq!(vault.get(&id).expect("the entry is back").name, "peer");
        assert_eq!(
            vault.tombstone_count(),
            0,
            "a tombstone next to a live entry would be sent on its own and delete the entry again"
        );

        let again = merge_peer_entry(&mut vault, id, &peer);
        assert!(
            again.conflicts.is_empty() && again.unchanged == 1,
            "the decision must close the conflict: {again:?}"
        );
    }

    #[test]
    fn confirming_a_deletion_here_drops_the_peer_entry() {
        let id = entry_id(6);
        let peer = sample_entry("peer", 1_700_000_300);
        let mut vault = vault_that_deleted(id, 1_700_000_100);

        let outcome = adjudicate(
            &mut vault,
            &peer_entry_against_local_tombstone(id, &peer, 1_700_000_100),
            Decision::KeepLocal,
        )
        .expect("keeping the local version cannot fail");

        assert_eq!(outcome, Adjudicated::KeptLocal);
        assert!(vault.get(&id).is_none(), "the entry stays deleted");
        assert!(
            vault.get_tombstone(&id).is_some(),
            "the deletion is still recorded, so it keeps travelling"
        );
    }

    #[test]
    fn a_decision_for_an_entry_that_no_longer_exists_is_refused() {
        let id = entry_id(7);
        let local = sample_entry("local", 1_700_000_000);
        let peer = sample_entry("peer", 1_700_000_100);
        let mut vault = Vault::new();

        let result = adjudicate(
            &mut vault,
            &mismatch(id, &local, &peer),
            Decision::TakeIncoming,
        );

        assert!(
            matches!(result, Err(crate::Error::VaultEntryNotFound)),
            "actual {result:?}"
        );
        assert_eq!(vault.len(), 0, "a refused decision must write nothing");
    }
}