passalong-core 0.3.0

Core library for passalong: configuration, item model, storage traits, and telemetry
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
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
//! Changing a store's encryption: setting it up on an empty store, a fresh
//! start that keeps the earlier items unencrypted in `plain/`, joining it
//! with its words, and changing its words.

use std::sync::Arc;

use super::header::encryption_dir;
use super::header_change::run_change;
use super::journal::{HeaderChangeKind, count_staged, sweep_staged};
use super::open::rewrite_started;
use super::rewrite::fold;
use super::{
    EncryptionError, PLAIN_DIR, REWRITE_DIR, STOP_FILE, StoreHeader, read_header, write_stop_file,
};
use crate::clock::SystemClock;
use crate::crypto::{DataKey, KdfParams, KeyId, Words, unwrap, wrap};
use crate::fs::{FsError, RemoteFs, RemotePath, SubFs};
use crate::random::StdRandom;
use crate::store::{FsStore, Store, StoreError};

/// What a store's root says about its encryption.
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub enum StoreState {
    /// No header: a plaintext store.
    Plain {
        /// How many items it holds.
        items: usize,
    },
    /// An encrypted store.
    Encrypted {
        /// Id of its data key.
        key_id: KeyId,
        /// Plaintext items a fresh start left in `plain/items/`.
        plain_left: usize,
    },
    /// Its items are being re-encrypted.
    Rewriting {
        /// When that started, if known.
        started: Option<String>,
    },
    /// Part of an encrypted layout without the rest, such as a stop file or
    /// an `encryption/` folder without a header, or a header beside an
    /// `items/` folder. It is never used as plaintext.
    Broken,
}

/// What a store's root holds, read the same way for [`inspect`] and for
/// opening the store.
pub(super) enum Layout {
    /// `.rewrite/` is there.
    Rewriting {
        /// When the change started, if known.
        started: Option<String>,
    },
    /// A readable header, and no `items/` folder beside it.
    Encrypted(StoreHeader),
    /// Part of an encrypted layout without the rest.
    Broken,
    /// Nothing of an encrypted layout.
    Plain,
}

/// Reads the store's root and tells its layout apart. Any part of an
/// encrypted layout without the rest, as a synced folder may deliver it,
/// is [`Layout::Broken`], never [`Layout::Plain`].
///
/// # Errors
///
/// The filesystem's error, or [`EncryptionError::Header`] for a header that
/// cannot be parsed.
pub(super) async fn classify<F: RemoteFs + ?Sized>(fs: &F) -> Result<Layout, StoreError> {
    if fs.stat(&RemotePath::new(REWRITE_DIR)?).await?.is_some() {
        return Ok(Layout::Rewriting {
            started: rewrite_started(fs).await,
        });
    }
    let items = fs.stat(&items_path()).await?;
    let items_folder = items.as_ref().is_some_and(|meta| meta.is_dir);
    if fs.stat(&encryption_dir()?).await?.is_some() {
        return Ok(match read_header(fs).await? {
            Some(header) if !items_folder => Layout::Encrypted(header),
            _ => Layout::Broken,
        });
    }
    Ok(if items.is_some() && !items_folder {
        Layout::Broken
    } else {
        Layout::Plain
    })
}

fn items_path() -> RemotePath {
    RemotePath::new(STOP_FILE).expect("a valid path")
}

fn plain_path() -> RemotePath {
    RemotePath::new(PLAIN_DIR).expect("a valid path")
}

/// `tmp/`, where a plaintext store stages uploads and deletions.
pub(super) fn plain_tmp() -> RemotePath {
    RemotePath::new("tmp").expect("a valid path")
}

/// What an encrypted store holds but no longer uses;
/// `passalong prune --plain` removes it.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
#[non_exhaustive]
pub struct Leftovers {
    /// Entries of `tmp/`, the plaintext staging: uploads and deletions cut
    /// short before encryption, which may hold plaintext.
    pub plaintext_staging: usize,
    /// Journals staged for locks that were never taken.
    pub staged_journals: usize,
}

impl Leftovers {
    /// Whether there is nothing to remove.
    pub fn is_empty(&self) -> bool {
        self.plaintext_staging == 0 && self.staged_journals == 0
    }

    /// Leftovers of `n` entries of plaintext staging.
    pub(crate) fn plaintext(n: usize) -> Self {
        Self {
            plaintext_staging: n,
            staged_journals: 0,
        }
    }
}

impl std::fmt::Display for Leftovers {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        let mut parts = Vec::new();
        if self.plaintext_staging > 0 {
            let n = self.plaintext_staging;
            let noun = if n == 1 { "leftover" } else { "leftovers" };
            parts.push(format!("{n} unencrypted {noun} of cut-short uploads"));
        }
        if self.staged_journals > 0 {
            let n = self.staged_journals;
            let noun = if n == 1 { "journal" } else { "journals" };
            parts.push(format!("{n} unused {noun}"));
        }
        if parts.is_empty() {
            return f.write_str("no leftovers");
        }
        f.write_str(&parts.join(", "))
    }
}

/// Counts an encrypted store's [`Leftovers`].
///
/// # Errors
///
/// The refusal for a store that is not encrypted, and the filesystem's
/// error.
pub async fn leftovers<F: RemoteFs + ?Sized>(fs: &F) -> Result<Leftovers, StoreError> {
    match inspect(fs).await? {
        StoreState::Encrypted { .. } => count_leftovers(fs).await,
        other => Err(refuse(other)),
    }
}

async fn count_leftovers<F: RemoteFs + ?Sized>(fs: &F) -> Result<Leftovers, StoreError> {
    let plaintext_staging = match fs.read_dir(&plain_tmp()).await {
        Ok(entries) => entries.len(),
        Err(FsError::NotFound(_)) => 0,
        Err(err) => return Err(err.into()),
    };
    Ok(Leftovers {
        plaintext_staging,
        staged_journals: count_staged(fs).await?,
    })
}

/// Removes an encrypted store's [`Leftovers`], and returns what it found.
///
/// # Errors
///
/// As [`leftovers`].
pub async fn remove_leftovers<F: RemoteFs + ?Sized>(fs: &F) -> Result<Leftovers, StoreError> {
    let found = leftovers(fs).await?;
    fs.remove_dir_all(&plain_tmp()).await?;
    sweep_staged(fs).await?;
    Ok(found)
}

/// The plaintext items a fresh start kept, as a store of their own, for
/// listing and pruning them.
pub fn plain_store<F: RemoteFs + ?Sized>(fs: &F) -> FsStore<SubFs<&F>> {
    FsStore::new(
        SubFs::new(fs, plain_path()),
        Arc::new(SystemClock),
        Box::new(StdRandom::new()),
    )
}

/// Reads what the store's root says about its encryption.
///
/// # Errors
///
/// The filesystem's error, or [`EncryptionError::Header`] for a header
/// that cannot be read.
pub async fn inspect<F: RemoteFs + ?Sized>(fs: &F) -> Result<StoreState, StoreError> {
    Ok(match classify(fs).await? {
        Layout::Rewriting { started } => StoreState::Rewriting { started },
        Layout::Encrypted(header) => StoreState::Encrypted {
            key_id: header.key_id(),
            plain_left: plain_store(fs).list_ids().await?.len(),
        },
        Layout::Broken => StoreState::Broken,
        Layout::Plain => {
            let plain = FsStore::new(fs, Arc::new(SystemClock), Box::new(StdRandom::new()));
            StoreState::Plain {
                items: plain.list_ids().await?.len(),
            }
        }
    })
}

/// The error for a store in a state the operation cannot start from.
pub(super) fn refuse(state: StoreState) -> StoreError {
    match state {
        StoreState::Plain { .. } => EncryptionError::NotEncrypted.into(),
        StoreState::Encrypted { .. } => EncryptionError::AlreadyEncrypted.into(),
        StoreState::Rewriting { started } => EncryptionError::Rewriting { started }.into(),
        StoreState::Broken => EncryptionError::HeaderMissing.into(),
    }
}

fn new_key(words: &Words, kdf: KdfParams) -> Result<(DataKey, StoreHeader), StoreError> {
    let key = DataKey::generate()?;
    let header = StoreHeader::new(wrap(&key, words, kdf)?);
    Ok((key, header))
}

/// Encrypts an empty plaintext store under a new data key wrapped with
/// `words`, and returns the key. The stop file comes first, so clients
/// before v0.2.0 are shut out before the header appears.
///
/// # Errors
///
/// [`EncryptionError::Layout`] when the store holds items or other files,
/// the refusal for a store that is not plaintext, and the filesystem's
/// error otherwise.
pub async fn set_up<F: RemoteFs + ?Sized>(
    fs: &F,
    words: &Words,
    kdf: KdfParams,
) -> Result<DataKey, StoreError> {
    match inspect(fs).await? {
        StoreState::Plain { items: 0 } => {}
        StoreState::Plain { items } => {
            return Err(EncryptionError::Layout(format!(
                "the store holds {items} items; encrypt it with a fresh start or by migrating"
            ))
            .into());
        }
        other => return Err(refuse(other)),
    }
    let items = items_path();
    if fs.stat(&items).await?.is_some_and(|meta| meta.is_dir)
        && !fs.read_dir(&items).await?.is_empty()
    {
        return Err(EncryptionError::Layout(format!(
            "`{STOP_FILE}` holds files that are not items; move them away first"
        ))
        .into());
    }
    let (key, header) = new_key(words, kdf)?;
    run_change(fs, HeaderChangeKind::SetUp, &header, None).await?;
    Ok(key)
}

/// Encrypts a plaintext store under a new data key wrapped with `words`,
/// without re-encrypting its items: they move to `plain/items/`, where the
/// storage can read them until `prune --plain` removes them. Returns the
/// key.
///
/// # Errors
///
/// The refusal for a store that is not plaintext, and the filesystem's
/// error otherwise.
pub async fn fresh_start<F: RemoteFs + ?Sized>(
    fs: &F,
    words: &Words,
    kdf: KdfParams,
) -> Result<DataKey, StoreError> {
    match inspect(fs).await? {
        StoreState::Plain { .. } => {}
        other => return Err(refuse(other)),
    }
    let (key, header) = new_key(words, kdf)?;
    run_change(fs, HeaderChangeKind::FreshStart, &header, None).await?;
    Ok(key)
}

/// Makes way for the stop file and writes it: an empty `items/` is
/// removed, and one holding items moves to `plain/items/`; once more when a
/// client before v0.2.0 recreated `items/` in between. Then the plaintext
/// staging `tmp/` goes: with the stop file in place, nothing staged there
/// can be published any more.
pub(super) async fn stop_old_clients<F: RemoteFs + ?Sized>(fs: &F) -> Result<(), StoreError> {
    clear_items(fs).await?;
    if let Err(err) = write_stop_file(fs).await {
        if !matches!(err, StoreError::Encryption(EncryptionError::Layout(_))) {
            return Err(err);
        }
        clear_items(fs).await?;
        write_stop_file(fs).await?;
    }
    fs.remove_dir_all(&plain_tmp()).await?;
    Ok(())
}

async fn clear_items<F: RemoteFs + ?Sized>(fs: &F) -> Result<(), StoreError> {
    let items = items_path();
    if !fs.stat(&items).await?.is_some_and(|meta| meta.is_dir) {
        return Ok(());
    }
    if fs.read_dir(&items).await?.is_empty() {
        fs.remove_dir_all(&items).await?;
        return Ok(());
    }
    move_items_to_plain(fs).await
}

/// Undoes [`stop_old_clients`]: removes the stop file, and moves
/// `plain/items/` back to `items/`.
pub(super) async fn restore_items<F: RemoteFs + ?Sized>(fs: &F) -> Result<(), StoreError> {
    let items = items_path();
    if fs.stat(&items).await?.is_some_and(|meta| !meta.is_dir) {
        fs.remove_file(&items).await?;
    }
    let kept = plain_path().join(STOP_FILE)?;
    if fs.stat(&kept).await?.is_some() {
        fold(fs, &kept, &items).await?;
    }
    let plain = plain_path();
    if fs.stat(&plain).await?.is_some() && fs.read_dir(&plain).await?.is_empty() {
        fs.remove_dir_all(&plain).await?;
    }
    Ok(())
}

/// Moves `items/` to `plain/items/`: in one rename when there is no
/// `plain/items/` yet, and item by item otherwise.
async fn move_items_to_plain<F: RemoteFs + ?Sized>(fs: &F) -> Result<(), StoreError> {
    let items = items_path();
    if !fs.stat(&items).await?.is_some_and(|meta| meta.is_dir) {
        return Ok(());
    }
    let target = plain_path().join(STOP_FILE)?;
    fs.create_dir_all(&plain_path()).await?;
    if fs.stat(&target).await?.is_none() {
        fs.rename(&items, &target).await?;
        return Ok(());
    }
    for entry in fs.read_dir(&items).await? {
        let from = items.join(&entry.name)?;
        match fs.rename(&from, &target.join(&entry.name)?).await {
            Ok(()) => {}
            // The same item was moved before.
            Err(FsError::AlreadyExists(_)) => fs.remove_dir_all(&from).await?,
            Err(err) => return Err(err.into()),
        }
    }
    fs.remove_dir_all(&items).await?;
    Ok(())
}

/// This device's key for an encrypted store: its data key, unwrapped with
/// the store's `words`.
///
/// # Errors
///
/// [`EncryptionError::NotEncrypted`] and the other refusals for a store
/// that is not encrypted, and [`CryptoError::WrongWords`] for wrong words.
///
/// [`CryptoError::WrongWords`]: crate::crypto::CryptoError::WrongWords
pub async fn join<F: RemoteFs + ?Sized>(fs: &F, words: &Words) -> Result<DataKey, StoreError> {
    match inspect(fs).await? {
        StoreState::Encrypted { .. } => {}
        other => return Err(refuse(other)),
    }
    let header = read_header(fs)
        .await?
        .ok_or(EncryptionError::HeaderMissing)?;
    Ok(unwrap(header.wrapped(), words)?)
}

/// Replaces an encrypted store's words: its data key is unwrapped with
/// `current` and wrapped again with `new`, so no item is re-encrypted and
/// every device that joined keeps working. Returns the key's id.
///
/// # Errors
///
/// As [`join`], and the filesystem's error while replacing the header.
pub async fn change_words<F: RemoteFs + ?Sized>(
    fs: &F,
    current: &Words,
    new: &Words,
    kdf: KdfParams,
) -> Result<KeyId, StoreError> {
    let key = join(fs, current).await?;
    let old = read_header(fs)
        .await?
        .ok_or(EncryptionError::HeaderMissing)?;
    let header = StoreHeader::new(wrap(&key, new, kdf)?);
    run_change(fs, HeaderChangeKind::Words, &header, Some(&old)).await?;
    Ok(key.key_id())
}

/// Removes `plain/` once it holds no items; `true` when it was removed.
///
/// # Errors
///
/// The filesystem's error.
pub async fn remove_plain_if_empty<F: RemoteFs + ?Sized>(fs: &F) -> Result<bool, StoreError> {
    let plain = plain_path();
    if fs.stat(&plain).await?.is_none() || !plain_store(fs).list_ids().await?.is_empty() {
        return Ok(false);
    }
    fs.remove_dir_all(&plain).await?;
    Ok(true)
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::crypto::{CryptoError, KDF_SALT_LEN};
    use crate::encryption::open_with_key;
    use crate::fs::LocalFs;
    use crate::model::NewItem;
    use crate::testing::ManualClock;
    use tempfile::TempDir;

    const W1: &str = "abacus abdomen abdominal abide abiding ability";
    const W2: &str = "zoom zoom zoom zoom zoom zoom";

    fn words(text: &str) -> Words {
        Words::parse(text).unwrap()
    }

    fn quick() -> KdfParams {
        KdfParams {
            m_kib: 64,
            t: 1,
            p: 1,
            salt: [4; KDF_SALT_LEN],
        }
    }

    fn text(bytes: &[u8]) -> crate::fs::BoxRead {
        Box::new(std::io::Cursor::new(bytes.to_vec()))
    }

    async fn seed(fs: &LocalFs, n: usize) {
        let store = FsStore::new(
            fs.clone(),
            Arc::new(ManualClock::at("2026-09-12T09:53:11Z")),
            Box::new(StdRandom::new()),
        );
        for i in 0..n {
            store
                .put(NewItem::text("box"), text(format!("old {i}").as_bytes()))
                .await
                .unwrap();
        }
    }

    async fn open(fs: &LocalFs, key: &DataKey) -> Box<dyn Store> {
        open_with_key(
            fs.clone(),
            Some(key.clone()),
            Arc::new(SystemClock),
            Box::new(StdRandom::new()),
        )
        .await
        .unwrap()
    }

    fn is(err: StoreError, want: &EncryptionError) -> bool {
        matches!(err, StoreError::Encryption(got) if got == *want)
    }

    #[tokio::test]
    async fn inspect_tells_every_state_apart() {
        let dir = TempDir::new().unwrap();
        let fs = LocalFs::new(dir.path());
        assert_eq!(inspect(&fs).await.unwrap(), StoreState::Plain { items: 0 });
        seed(&fs, 2).await;
        assert_eq!(inspect(&fs).await.unwrap(), StoreState::Plain { items: 2 });

        let other = TempDir::new().unwrap();
        let fs = LocalFs::new(other.path());
        write_stop_file(&fs).await.unwrap();
        assert_eq!(inspect(&fs).await.unwrap(), StoreState::Broken);
        std::fs::create_dir(other.path().join(".rewrite")).unwrap();
        assert_eq!(
            inspect(&fs).await.unwrap(),
            StoreState::Rewriting { started: None }
        );
    }

    #[tokio::test]
    async fn leftovers_are_counted_and_removed_on_an_encrypted_store() {
        let dir = TempDir::new().unwrap();
        let fs = LocalFs::new(dir.path());
        assert!(is(
            leftovers(&fs).await.unwrap_err(),
            &EncryptionError::NotEncrypted
        ));
        set_up(&fs, &words(W1), quick()).await.unwrap();
        assert!(leftovers(&fs).await.unwrap().is_empty());
        // What passalong 0.2.0 kept: an upload and a deletion cut short
        // before encryption, and a journal staged for a lock never taken.
        std::fs::create_dir_all(dir.path().join("tmp/0123")).unwrap();
        std::fs::write(dir.path().join("tmp/0123/content"), "plaintext").unwrap();
        std::fs::create_dir_all(dir.path().join("tmp/deleted-x")).unwrap();
        std::fs::create_dir(dir.path().join(".rewrite-00ff")).unwrap();
        let found = leftovers(&fs).await.unwrap();
        assert_eq!((found.plaintext_staging, found.staged_journals), (2, 1));
        assert_eq!(
            found.to_string(),
            "2 unencrypted leftovers of cut-short uploads, 1 unused journal"
        );
        assert_eq!(remove_leftovers(&fs).await.unwrap(), found);
        assert!(leftovers(&fs).await.unwrap().is_empty());
        assert!(!dir.path().join("tmp").exists());
    }

    #[tokio::test]
    async fn parts_of_an_encrypted_layout_are_broken_never_plain() {
        let dir = TempDir::new().unwrap();
        let fs = LocalFs::new(dir.path());
        seed(&fs, 1).await;
        std::fs::create_dir(dir.path().join("encryption")).unwrap();
        assert_eq!(inspect(&fs).await.unwrap(), StoreState::Broken);
        // The header arrived, but `items/` is still the plaintext folder.
        let header = crate::encryption::header::tests::quick_header(&DataKey::generate().unwrap());
        std::fs::write(dir.path().join("encryption/header.json"), header.to_json()).unwrap();
        assert_eq!(inspect(&fs).await.unwrap(), StoreState::Broken);
    }

    #[tokio::test]
    async fn set_up_encrypts_an_empty_store_once() {
        let dir = TempDir::new().unwrap();
        let fs = LocalFs::new(dir.path());
        std::fs::create_dir(dir.path().join("items")).unwrap();
        let key = set_up(&fs, &words(W1), quick()).await.unwrap();
        assert_eq!(
            inspect(&fs).await.unwrap(),
            StoreState::Encrypted {
                key_id: key.key_id(),
                plain_left: 0
            }
        );
        assert!(dir.path().join("items").is_file());
        open(&fs, &key)
            .await
            .put(NewItem::text("box"), text(b"sealed"))
            .await
            .unwrap();
        assert!(is(
            set_up(&fs, &words(W1), quick()).await.unwrap_err(),
            &EncryptionError::AlreadyEncrypted
        ));
    }

    #[tokio::test]
    async fn set_up_refuses_a_store_with_items_or_other_files() {
        let dir = TempDir::new().unwrap();
        let fs = LocalFs::new(dir.path());
        seed(&fs, 1).await;
        assert!(matches!(
            set_up(&fs, &words(W1), quick()).await,
            Err(StoreError::Encryption(EncryptionError::Layout(_)))
        ));
        let other = TempDir::new().unwrap();
        std::fs::create_dir_all(other.path().join("items/not-an-item")).unwrap();
        let fs = LocalFs::new(other.path());
        assert!(matches!(
            set_up(&fs, &words(W1), quick()).await,
            Err(StoreError::Encryption(EncryptionError::Layout(_)))
        ));
        assert!(!other.path().join("encryption").exists());
    }

    #[tokio::test]
    async fn a_fresh_start_keeps_the_old_items_in_plain() {
        let dir = TempDir::new().unwrap();
        let fs = LocalFs::new(dir.path());
        seed(&fs, 2).await;
        let before = FsStore::new(
            fs.clone(),
            Arc::new(SystemClock),
            Box::new(StdRandom::new()),
        )
        .list_ids()
        .await
        .unwrap();
        let key = fresh_start(&fs, &words(W1), quick()).await.unwrap();
        assert_eq!(
            inspect(&fs).await.unwrap(),
            StoreState::Encrypted {
                key_id: key.key_id(),
                plain_left: 2
            }
        );
        assert_eq!(plain_store(&fs).list_ids().await.unwrap(), before);
        assert!(open(&fs, &key).await.list().await.unwrap().is_empty());

        assert!(!remove_plain_if_empty(&fs).await.unwrap());
        let plain = plain_store(&fs);
        for id in &before {
            plain.delete(id).await.unwrap();
        }
        assert!(remove_plain_if_empty(&fs).await.unwrap());
        assert!(!dir.path().join("plain").exists());
        assert!(!remove_plain_if_empty(&fs).await.unwrap());
    }

    #[tokio::test]
    async fn a_fresh_start_merges_into_an_existing_plain_folder() {
        let dir = TempDir::new().unwrap();
        let fs = LocalFs::new(dir.path());
        seed(&fs, 2).await;
        let first = FsStore::new(
            fs.clone(),
            Arc::new(SystemClock),
            Box::new(StdRandom::new()),
        )
        .list_ids()
        .await
        .unwrap()[0]
            .clone();
        std::fs::create_dir_all(dir.path().join("plain/items")).unwrap();
        let copy = dir.path().join(format!("plain/items/{first}"));
        std::fs::create_dir(&copy).unwrap();
        fresh_start(&fs, &words(W1), quick()).await.unwrap();
        // The earlier copy of the first item stays; the second one moves in.
        assert_eq!(plain_store(&fs).list_ids().await.unwrap().len(), 2);
        assert!(dir.path().join("items").is_file());
    }

    #[tokio::test]
    async fn joining_needs_the_store_s_words() {
        let dir = TempDir::new().unwrap();
        let fs = LocalFs::new(dir.path());
        assert!(is(
            join(&fs, &words(W1)).await.unwrap_err(),
            &EncryptionError::NotEncrypted
        ));
        let key = set_up(&fs, &words(W1), quick()).await.unwrap();
        assert_eq!(
            join(&fs, &words(W1)).await.unwrap().as_bytes(),
            key.as_bytes()
        );
        assert!(is(
            join(&fs, &words(W2)).await.unwrap_err(),
            &EncryptionError::Crypto(CryptoError::WrongWords)
        ));
    }

    #[tokio::test]
    async fn new_words_keep_the_key_and_rewrite_no_item() {
        let dir = TempDir::new().unwrap();
        let fs = LocalFs::new(dir.path());
        let key = set_up(&fs, &words(W1), quick()).await.unwrap();
        let item = open(&fs, &key)
            .await
            .put(NewItem::text("box"), text(b"kept"))
            .await
            .unwrap()
            .meta;
        let content = dir.path().join(format!("v2/items/{}/content", item.id));
        let before = std::fs::read(&content).unwrap();

        assert!(is(
            change_words(&fs, &words(W2), &words(W2), quick())
                .await
                .unwrap_err(),
            &EncryptionError::Crypto(CryptoError::WrongWords)
        ));
        let id = change_words(&fs, &words(W1), &words(W2), quick())
            .await
            .unwrap();
        assert_eq!(id, key.key_id());
        assert_eq!(
            join(&fs, &words(W2)).await.unwrap().as_bytes(),
            key.as_bytes()
        );
        assert!(join(&fs, &words(W1)).await.is_err());
        assert_eq!(std::fs::read(&content).unwrap(), before);
        assert_eq!(open(&fs, &key).await.list().await.unwrap(), vec![item]);
    }
}