dotprot 0.4.0

Lock up .env files (and anything in .prot) inside a 1Password vault.
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
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
//! The dotprot commands: setup, lock, unlock, and the bare-toggle dispatcher.

use std::collections::BTreeSet;
use std::fs;
use std::path::{Path, PathBuf};

use anyhow::{bail, Context, Result};

use crate::backup;
use crate::op::OpBackend;
use crate::prot::{self, ProtData};

pub const VAULT_NAME: &str = ".prot";
pub const PROT_FILE: &str = ".prot";
const VAULT_DESCRIPTION: &str = "Managed by dotprot — protected .env and config files.";

/// Ensure the user is signed in to 1Password before running a command.
///
/// The default entry point used by the commands; it asks the user via an
/// interactive terminal prompt. See [`ensure_signed_in_with`] for the testable
/// core that takes the confirmation decision as a parameter.
fn ensure_signed_in(op: &impl OpBackend) -> Result<()> {
    ensure_signed_in_with(op, || {
        prompt_yes_no("You are not signed in to 1Password. Sign in now?")
    })
}

/// Core of [`ensure_signed_in`], with the "should we sign in?" decision injected
/// so it can be exercised without a real terminal.
///
/// If already signed in, returns immediately. Otherwise `confirm` decides
/// whether to run `op signin`; the production path makes that an interactive
/// prompt that is itself a no (false) in non-interactive contexts, so CI and
/// pipes never hang — they fall back to the same clear error as before.
fn ensure_signed_in_with(
    op: &impl OpBackend,
    confirm: impl FnOnce() -> Result<bool>,
) -> Result<()> {
    if op.is_signed_in()? {
        return Ok(());
    }

    if !confirm()? {
        bail!("You are not signed in to 1Password. Run `op signin` first.");
    }

    op.sign_in()?;

    // `op signin` reported success; confirm the session is actually usable
    // before we proceed to touch any protected files.
    if op.is_signed_in()? {
        Ok(())
    } else {
        bail!("Still not signed in to 1Password after `op signin`. Aborting.");
    }
}

/// Ask a yes/no question on the terminal, defaulting to "no".
///
/// Returns `Ok(false)` without prompting when stdin/stdout isn't an interactive
/// terminal, so non-interactive runs (CI, pipes) fail fast with a clear error
/// rather than blocking on input that will never arrive.
fn prompt_yes_no(question: &str) -> Result<bool> {
    use std::io::{IsTerminal, Write};

    if !std::io::stdin().is_terminal() || !std::io::stdout().is_terminal() {
        return Ok(false);
    }

    print!("{question} [y/N] ");
    std::io::stdout().flush().ok();

    let mut answer = String::new();
    std::io::stdin().read_line(&mut answer)?;
    let answer = answer.trim().to_lowercase();
    Ok(answer == "y" || answer == "yes")
}

fn prot_path(cwd: &Path) -> PathBuf {
    cwd.join(PROT_FILE)
}

/// Mirror the just-written `.prot` to its backup under `~/.prot/backups`.
///
/// Strictly best-effort: `.prot` on disk is already correct, and a backup
/// problem (no home dir, a read-only home, …) must never abort a lock that is
/// otherwise proceeding safely — so failures warn loudly and carry on.
fn backup_prot(home: Option<&Path>, cwd: &Path, data: &ProtData) {
    let Some(home) = home else {
        eprintln!("  warning: could not determine your home directory — {PROT_FILE} not backed up");
        return;
    };
    if let Err(e) = backup::save(home, cwd, data) {
        eprintln!("  warning: could not back up {PROT_FILE}: {e:#}");
    }
}

/// Expand the user's patterns against the working dir into concrete relative
/// file paths. The `.prot` file itself is always excluded. Globs only match
/// files that exist on disk (used by lock). Results are sorted and de-duped.
fn expand_patterns(cwd: &Path, patterns: &[String]) -> Result<Vec<String>> {
    let mut matches: BTreeSet<String> = BTreeSet::new();

    // The working directory becomes the literal prefix of every glob, so any
    // metacharacters in it (`[`, `?`, `*` — brackets in directory names are
    // real) must be escaped or matching silently fails.
    let escaped_cwd = glob::Pattern::escape(&cwd.to_string_lossy());

    for pattern in patterns {
        // Resolve the glob relative to cwd, then store the path back as a
        // cwd-relative string so document titles and .prot keys stay stable.
        // A rooted/absolute pattern stands alone (Path::join semantics — the
        // base is replaced): gluing it onto cwd would silently re-anchor
        // `/shared/x.env` at `<cwd>/shared/x.env`, a different file that
        // could then be locked and deleted.
        let abs_pattern = if Path::new(pattern).has_root() {
            cwd.join(pattern).to_string_lossy().into_owned()
        } else {
            format!("{escaped_cwd}{}{pattern}", std::path::MAIN_SEPARATOR)
        };
        for entry in glob::glob(&abs_pattern)? {
            let path = match entry {
                Ok(p) => p,
                Err(e) => {
                    // An entry we couldn't read (e.g. a permission error while
                    // walking). Don't abort the whole lock over one bad entry,
                    // but never swallow it silently: a file the user meant to
                    // protect could otherwise be skipped while they believe it
                    // was handled, leaving a secret in plaintext on disk.
                    eprintln!("  warning: could not read {} — skipped", e.path().display());
                    continue;
                }
            };
            if !path.is_file() {
                continue;
            }
            // A pattern like `../shared/.env` can match outside the working
            // directory. strip_prefix is lexical — `cwd/../x` still "strips" —
            // so any remaining `..` component also means the file is outside.
            // dotprot only protects files under cwd; say so loudly, or the
            // user will believe the file is locked while it sits in plaintext.
            let rel = path.strip_prefix(cwd).ok().filter(|rel| {
                !rel.components()
                    .any(|c| matches!(c, std::path::Component::ParentDir))
            });
            let Some(rel) = rel else {
                eprintln!(
                    "  warning: {} is outside {} — skipped (dotprot only \
                     protects files inside the working directory)",
                    path.display(),
                    cwd.display()
                );
                continue;
            };
            let rel = rel.to_string_lossy().to_string();
            if rel.chars().any(|c| c.is_control()) || rel != rel.trim() {
                // .prot is a line-oriented format whose parser trims each
                // recorded key: a control character (e.g. a newline) would
                // corrupt the line, and leading/trailing whitespace (a file
                // named `.env `) would round-trip to a different key — either
                // way the document id is unrecoverable from .prot after the
                // original file is already deleted.
                eprintln!(
                    "  warning: {rel:?} has control characters or leading/\
                     trailing whitespace in its name — skipped (unsupported \
                     in {PROT_FILE})"
                );
                continue;
            }
            if rel != PROT_FILE {
                matches.insert(rel);
            }
        }
    }

    Ok(matches.into_iter().collect())
}

/// A 1Password title that's unique per absolute file path.
fn document_title(cwd: &Path, rel_file: &str) -> String {
    cwd.join(rel_file).to_string_lossy().to_string()
}

/// Whether a protected file is present on disk.
///
/// Uses `try_exists` rather than `exists` so a "couldn't determine" (e.g. a
/// permission error) is not silently read as "absent". An indeterminate result
/// is treated as **present**, which is the safe bias for every caller: unlock
/// then declines to overwrite a file it can't read, and toggle steers away from
/// a destructive restore when it can't be sure the original is gone.
fn file_exists(p: &Path) -> bool {
    p.try_exists().unwrap_or(true)
}

// ---------------------------------------------------------------------------
// setup
// ---------------------------------------------------------------------------

pub fn setup(op: &impl OpBackend) -> Result<()> {
    ensure_signed_in(op)?;

    if let Some(id) = op.find_vault(VAULT_NAME)? {
        println!("Vault \"{VAULT_NAME}\" already exists ({id}).");
        return Ok(());
    }

    let id = op.create_vault(VAULT_NAME, VAULT_DESCRIPTION)?;
    println!("Created vault \"{VAULT_NAME}\" ({id}).");
    Ok(())
}

/// Resolve the 1Password vault ID to use for this run.
///
/// If `.prot` records a vault ID, verify it still refers to a vault actually
/// named ".prot" before using it. The ID is user-editable (and often committed
/// to version control), so trusting it blindly would let a tampered or
/// copy-pasted value silently point dotprot's document writes at some other
/// vault in the account.
///
/// Otherwise look the vault up by name. `create_if_missing` decides whether a
/// missing vault is created (lock — a one-time action, announced clearly) or
/// an error (unlock — a fresh empty vault could never contain the recorded
/// documents, so creating one only muddies the account).
fn resolve_vault(
    op: &impl OpBackend,
    prot: &mut ProtData,
    create_if_missing: bool,
) -> Result<String> {
    if let Some(id) = &prot.vault {
        return match op.vault_name(id)? {
            Some(name) if name == VAULT_NAME => Ok(id.clone()),
            Some(name) => bail!(
                "The vault recorded in {PROT_FILE} ({id}) is named \"{name}\", not \
                 \"{VAULT_NAME}\". Refusing to touch it. If that vault was renamed, \
                 rename it back; if the ID is stale, remove the `vault:` line from \
                 {PROT_FILE} and rerun."
            ),
            None => bail!(
                "The vault recorded in {PROT_FILE} ({id}) was not found in your \
                 1Password account. If it was deleted, remove the `vault:` line \
                 from {PROT_FILE} and rerun."
            ),
        };
    }
    let id = match op.find_vault(VAULT_NAME)? {
        Some(found) => found,
        None if create_if_missing => {
            let created = op.create_vault(VAULT_NAME, VAULT_DESCRIPTION)?;
            println!("Created 1Password vault \"{VAULT_NAME}\" ({created}).");
            println!("(one-time setup — future runs reuse it)");
            created
        }
        None => bail!(
            "No \"{VAULT_NAME}\" vault found in your 1Password account, but \
             {PROT_FILE} has documents recorded. Nothing to restore from."
        ),
    };
    prot.vault = Some(id.clone());
    Ok(id)
}

// ---------------------------------------------------------------------------
// lock
// ---------------------------------------------------------------------------

/// Lock the protected files into 1Password.
///
/// With `keep = true`, files are uploaded and verified but NOT deleted from
/// disk — useful for confirming the vault copy yourself before trusting
/// dotprot to remove anything.
pub fn lock(op: &impl OpBackend, cwd: &Path, keep: bool, home: Option<&Path>) -> Result<()> {
    ensure_signed_in(op)?;

    let file = prot_path(cwd);
    let mut prot = match prot::read(&file)? {
        Some(p) => p,
        None => {
            // Auto-create on first lock, defaulting to .env*.
            let p = ProtData::empty();
            prot::write(&file, &p)?;
            backup_prot(home, cwd, &p);
            println!(
                "Created {PROT_FILE} (protecting: {}).",
                p.patterns.join(", ")
            );
            p
        }
    };

    // Expand patterns first: it's free local work, and bailing on an empty
    // match must not cost the network round-trip that vault resolution takes.
    let files = expand_patterns(cwd, &prot.patterns)?;

    if files.is_empty() {
        bail!(
            "No files match the patterns in {PROT_FILE} ({}).\n\
             Either the files are already locked, or no matching files exist.",
            prot.patterns.join(", ")
        );
    }

    let vault = resolve_vault(op, &mut prot, true)?;

    let mut locked = 0;
    for rel_file in &files {
        let abs_file = cwd.join(rel_file);
        let content = fs::read(&abs_file)?;
        let title = document_title(cwd, rel_file);
        let file_name = Path::new(rel_file)
            .file_name()
            .map(|n| n.to_string_lossy().to_string())
            .unwrap_or_else(|| rel_file.clone());

        // op rejects empty stdin/empty files; a zero-byte file can't be stored
        // as a document. Skip it rather than fail.
        if content.is_empty() {
            println!("  skip {rel_file} (empty file — nothing to protect)");
            continue;
        }

        // Re-lock if we already have a doc id for this pattern entry; otherwise
        // create a fresh document.
        let id = match prot.document_id(rel_file) {
            Some(existing) => {
                let existing = existing.to_string();
                op.edit_document(&vault, &existing, &title, &file_name, &content)?;
                existing
            }
            None => op.create_document(&vault, &title, &file_name, &content)?,
        };

        // Verify-then-delete: read the document back and byte-compare before we
        // ever remove the original from disk.
        let round_trip = op.get_document(&vault, &id)?;
        if round_trip != content {
            bail!(
                "Verification failed for {rel_file}: the copy in 1Password does not \
                 match the file on disk. Left {rel_file} in place; nothing deleted."
            );
        }

        prot.set_document(rel_file, &id);
        // Persist the document id (and vault) immediately, before deleting the
        // file. If a later file fails, everything locked so far is recorded in
        // .prot and recoverable. The backup mirror keeps ~/.prot in step so
        // `dotprot restore` always has the latest state.
        prot::write(&file, &prot)?;
        backup_prot(home, cwd, &prot);
        if keep {
            println!("  uploaded {rel_file} -> 1Password (kept on disk)");
        } else {
            // The upload and read-back take real time (network round-trips);
            // the file may have been modified meanwhile, in which case the
            // verified vault copy is already stale and deleting would destroy
            // bytes that were never uploaded. Re-read and only delete if the
            // file is still exactly what we stored.
            let current = fs::read(&abs_file)
                .with_context(|| format!("re-reading {rel_file} before delete"))?;
            if current != content {
                bail!(
                    "{rel_file} changed on disk while it was being uploaded, so the \
                     copy in 1Password is already stale. Left {rel_file} in place — \
                     run `dotprot lock` again to store the new contents."
                );
            }
            fs::remove_file(&abs_file)?;
            println!("  locked {rel_file} -> 1Password");
        }
        locked += 1;
    }

    if keep {
        println!(
            "Uploaded {locked} file(s) to vault \"{VAULT_NAME}\". \
             Originals kept on disk (--keep); run `dotprot lock` to remove them."
        );
    } else {
        println!("Locked {locked} file(s) into vault \"{VAULT_NAME}\".");
    }
    Ok(())
}

// ---------------------------------------------------------------------------
// unlock
// ---------------------------------------------------------------------------

pub fn unlock(op: &impl OpBackend, cwd: &Path) -> Result<()> {
    ensure_signed_in(op)?;

    let file = prot_path(cwd);
    let mut prot = match prot::read(&file)? {
        Some(p) => p,
        None => bail!(
            "No {PROT_FILE} found in {}. Nothing to unlock.",
            cwd.display()
        ),
    };
    if prot.documents.is_empty() {
        bail!("{PROT_FILE} has no locked documents recorded. Nothing to unlock.");
    }

    // Validate every recorded path before restoring anything, so a tampered
    // entry aborts the run atomically instead of after a partial restore.
    for (rel_file, _) in &prot.documents {
        validate_restore_path(rel_file)?;
    }

    let vault = resolve_vault(op, &mut prot, false)?;

    let mut unlocked = 0;
    for (rel_file, id) in &prot.documents {
        let abs_file = cwd.join(rel_file);
        if file_exists(&abs_file) {
            println!("  skip {rel_file} (already present on disk)");
            continue;
        }
        let content = op.get_document(&vault, id)?;
        write_owner_only(&abs_file, &content)?;
        unlocked += 1;
        println!("  unlocked {rel_file} <- 1Password");
    }

    // Documents are intentionally kept in 1Password so the directory can
    // re-lock later. We leave prot.documents intact.
    println!("Unlocked {unlocked} file(s) from vault \"{VAULT_NAME}\".");
    Ok(())
}

/// Write a restored file with owner-only (0600) permissions on Unix.
///
/// Opens with `create_new` (O_CREAT|O_EXCL): the open fails if anything —
/// including a dangling symlink, which `file_exists` reads as "absent" —
/// already sits at the path. A plain `create(true)` would follow such a
/// symlink and write the secret to wherever it points.
fn write_owner_only(path: &Path, content: &[u8]) -> Result<()> {
    use std::io::Write;
    let mut opts = fs::OpenOptions::new();
    opts.write(true).create_new(true);
    #[cfg(unix)]
    {
        use std::os::unix::fs::OpenOptionsExt;
        opts.mode(0o600);
    }
    let mut f = opts.open(path).map_err(|e| {
        // create_new fails for opposite reasons; give the right advice for
        // each rather than one blanket message that misleads on the other.
        let hint = match e.kind() {
            std::io::ErrorKind::AlreadyExists => format!(
                "refusing to write {} — something already exists at that path \
                 (possibly a symlink); remove it and run `dotprot unlock` again",
                path.display()
            ),
            std::io::ErrorKind::NotFound => format!(
                "cannot write {} — its parent directory does not exist (git \
                 doesn't track empty directories); create the directory and \
                 run `dotprot unlock` again",
                path.display()
            ),
            _ => format!("opening {} for writing", path.display()),
        };
        anyhow::Error::new(e).context(hint)
    })?;
    f.write_all(content)?;
    Ok(())
}

/// Reject recorded file paths that could escape the working directory.
///
/// Lock only ever records cwd-relative paths, but `.prot` is user-editable and
/// often committed to version control, so unlock must not trust it: an entry
/// like `doc ../../.bashrc: <id>` would otherwise restore vault content to an
/// arbitrary path outside the project.
///
/// This is an allowlist — every component must be a plain name — because a
/// blocklist under-enumerates: a rooted-but-driveless Windows path like
/// `\Users\x` is not absolute and has no `Prefix` or `ParentDir` component,
/// yet `cwd.join()` replaces everything except the drive letter with it.
fn validate_restore_path(rel_file: &str) -> Result<()> {
    use std::path::Component;
    let path = Path::new(rel_file);
    if path.components().next().is_none()
        || !path.components().all(|c| matches!(c, Component::Normal(_)))
    {
        bail!(
            "Refusing to restore \"{rel_file}\": {PROT_FILE} entries must be \
             plain relative paths inside this directory (no absolute or rooted \
             paths, no `..`)."
        );
    }
    Ok(())
}

// ---------------------------------------------------------------------------
// restore — bring back a lost .prot from its local backup
// ---------------------------------------------------------------------------

/// Restore this directory's `.prot` from its backup under `~/.prot/backups`.
///
/// Purely local — no 1Password sign-in involved. The backup is the state as of
/// the last time dotprot wrote `.prot` here, so a restored file immediately
/// supports `dotprot unlock`.
pub fn restore(cwd: &Path, home: Option<&Path>) -> Result<()> {
    let Some(home) = home else {
        bail!("Could not determine your home directory, so there is no backup location to read.");
    };
    let backup_file = backup::backup_file(home, cwd);
    let file = prot_path(cwd);

    let backup_bytes = match fs::read(&backup_file) {
        Ok(bytes) => bytes,
        Err(e) if e.kind() == std::io::ErrorKind::NotFound => bail!(
            "No backup of {PROT_FILE} found for {} (looked at {}).\n\
             dotprot backs up {PROT_FILE} whenever it writes it — has \
             `dotprot lock` run in this directory before?",
            cwd.display(),
            backup_file.display()
        ),
        Err(e) => {
            return Err(e).with_context(|| format!("reading backup {}", backup_file.display()))
        }
    };

    if file_exists(&file) {
        let current =
            fs::read(&file).with_context(|| format!("reading existing {}", file.display()))?;
        if current == backup_bytes {
            println!("{PROT_FILE} already matches its backup — nothing to restore.");
            return Ok(());
        }
        bail!(
            "A {PROT_FILE} already exists here and differs from the backup \
             ({}).\nRefusing to overwrite it — move it aside first if you \
             really want the backup.",
            backup_file.display()
        );
    }

    write_owner_only(&file, &backup_bytes)?;
    println!("Restored {PROT_FILE} from {}.", backup_file.display());
    Ok(())
}

// ---------------------------------------------------------------------------
// bare `dotprot` — infer lock vs unlock from current state
// ---------------------------------------------------------------------------

pub fn toggle(op: &impl OpBackend, cwd: &Path, keep: bool, home: Option<&Path>) -> Result<()> {
    let file = prot_path(cwd);
    let prot = prot::read(&file)?;

    // No .prot at all (or nothing recorded) -> first run -> lock.
    let prot = match prot {
        Some(p) if !p.documents.is_empty() => p,
        _ => return lock(op, cwd, keep, home),
    };

    // The recorded paths are untrusted input here too: they steer the
    // lock-vs-unlock decision and are echoed in the mixed-state message, so a
    // tampered entry could otherwise probe paths outside the project.
    for (rel_file, _) in &prot.documents {
        validate_restore_path(rel_file)?;
    }

    // Compare recorded documents against what's on disk.
    let mut present: Vec<&str> = Vec::new();
    let mut absent: Vec<&str> = Vec::new();
    for (rel_file, _) in &prot.documents {
        if file_exists(&cwd.join(rel_file)) {
            present.push(rel_file);
        } else {
            absent.push(rel_file);
        }
    }

    if !present.is_empty() && !absent.is_empty() {
        bail!(
            "Mixed state: some recorded files are present on disk and others are missing, \
             so it's unclear whether you mean to lock or unlock.\n\
             \x20 present: {}\n\
             \x20 missing: {}\n\
             Use `dotprot lock` or `dotprot unlock` explicitly to resolve the ambiguity.",
            present.join(", "),
            absent.join(", "),
        );
    }

    if !absent.is_empty() {
        // Everything recorded is missing -> restore. Same note the explicit
        // `unlock --keep` prints — the flag must not be swallowed silently on
        // either entry path.
        if keep {
            eprintln!("note: --keep has no effect on unlock (nothing is deleted).");
        }
        unlock(op, cwd)
    } else {
        // Everything recorded is present -> re-lock.
        lock(op, cwd, keep, home)
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::op::OpBackend;
    use std::cell::RefCell;

    /// A fake [`OpBackend`] that records each call and stores "uploaded"
    /// document bytes in memory, so tests can drive lock/unlock without a live
    /// vault and assert the verify-then-delete ordering.
    struct MockOp {
        /// Ordered log of operations, for asserting sequencing.
        calls: RefCell<Vec<String>>,
        /// id -> bytes, as if stored in 1Password.
        docs: RefCell<Vec<(String, Vec<u8>)>>,
        /// When true, `get_document` returns bytes that differ from what was
        /// uploaded — simulating a corrupted or partial upload on read-back.
        corrupt_readback: bool,
        /// Current sign-in state. `sign_in()` flips it to true, modelling a
        /// successful `op signin`.
        signed_in: RefCell<bool>,
        /// When true, `sign_in()` does NOT flip `signed_in` — modelling a user
        /// who cancels the auth or whose session still isn't usable afterward.
        signin_fails: bool,
        /// When set, `get_document` rewrites this (path, bytes) on disk —
        /// simulating the protected file being modified by something else
        /// during the upload/verify round-trip.
        rewrite_on_get: Option<(PathBuf, Vec<u8>)>,
        /// What `vault_name` reports for any ID: the vault's current name, or
        /// `None` for a vault that no longer exists.
        vault_name_response: Option<String>,
        /// What `find_vault` reports: the vault's ID, or `None` when no vault
        /// named ".prot" exists in the account.
        find_vault_response: Option<String>,
    }

    impl MockOp {
        fn new() -> Self {
            MockOp {
                calls: RefCell::new(Vec::new()),
                docs: RefCell::new(Vec::new()),
                corrupt_readback: false,
                signed_in: RefCell::new(true),
                signin_fails: false,
                rewrite_on_get: None,
                vault_name_response: Some(VAULT_NAME.to_string()),
                find_vault_response: Some("VAULT".to_string()),
            }
        }

        fn corrupting() -> Self {
            let mut m = Self::new();
            m.corrupt_readback = true;
            m
        }

        /// A backend that starts signed out. `sign_in()` will flip it to
        /// signed-in unless `signin_fails` is also set.
        fn signed_out() -> Self {
            let m = Self::new();
            *m.signed_in.borrow_mut() = false;
            m
        }

        fn called(&self, name: &str) -> bool {
            self.calls.borrow().iter().any(|c| c == name)
        }

        fn store(&self, id: &str, content: &[u8]) {
            let mut docs = self.docs.borrow_mut();
            if let Some(entry) = docs.iter_mut().find(|(i, _)| i == id) {
                entry.1 = content.to_vec();
            } else {
                docs.push((id.to_string(), content.to_vec()));
            }
        }
    }

    impl OpBackend for MockOp {
        fn is_signed_in(&self) -> Result<bool> {
            self.calls.borrow_mut().push("is_signed_in".into());
            Ok(*self.signed_in.borrow())
        }
        fn sign_in(&self) -> Result<()> {
            self.calls.borrow_mut().push("sign_in".into());
            if !self.signin_fails {
                *self.signed_in.borrow_mut() = true;
            }
            Ok(())
        }
        fn find_vault(&self, _name: &str) -> Result<Option<String>> {
            self.calls.borrow_mut().push("find_vault".into());
            Ok(self.find_vault_response.clone())
        }
        fn vault_name(&self, _id: &str) -> Result<Option<String>> {
            self.calls.borrow_mut().push("vault_name".into());
            Ok(self.vault_name_response.clone())
        }
        fn create_vault(&self, _name: &str, _description: &str) -> Result<String> {
            self.calls.borrow_mut().push("create_vault".into());
            Ok("VAULT".into())
        }
        fn create_document(
            &self,
            _vault: &str,
            _title: &str,
            _file_name: &str,
            content: &[u8],
        ) -> Result<String> {
            self.calls.borrow_mut().push("create_document".into());
            let id = format!("DOC{}", self.docs.borrow().len());
            self.store(&id, content);
            Ok(id)
        }
        fn edit_document(
            &self,
            _vault: &str,
            id: &str,
            _title: &str,
            _file_name: &str,
            content: &[u8],
        ) -> Result<()> {
            self.calls.borrow_mut().push("edit_document".into());
            self.store(id, content);
            Ok(())
        }
        fn get_document(&self, _vault: &str, id: &str) -> Result<Vec<u8>> {
            self.calls.borrow_mut().push("get_document".into());
            if let Some((path, bytes)) = &self.rewrite_on_get {
                fs::write(path, bytes).unwrap();
            }
            let bytes = self
                .docs
                .borrow()
                .iter()
                .find(|(i, _)| i == id)
                .map(|(_, b)| b.clone())
                .unwrap_or_default();
            if self.corrupt_readback {
                // Return something that won't match what's on disk.
                Ok(b"CORRUPTED".to_vec())
            } else {
                Ok(bytes)
            }
        }
    }

    /// Write a `.prot` with a single `.env` pattern and a real `.env` file.
    fn setup_dir(secret: &[u8]) -> tempfile::TempDir {
        let dir = tempfile::tempdir().unwrap();
        fs::write(dir.path().join(".env"), secret).unwrap();
        let mut prot = ProtData::empty();
        prot.vault = Some("VAULT".to_string());
        prot::write(&dir.path().join(PROT_FILE), &prot).unwrap();
        dir
    }

    #[test]
    fn lock_deletes_only_after_successful_readback() {
        let dir = setup_dir(b"SECRET=1\n");
        let op = MockOp::new();

        lock(&op, dir.path(), false, None).unwrap();

        // File is gone, but only because the round-trip matched.
        assert!(!dir.path().join(".env").exists(), ".env should be deleted");

        // The read-back (get_document) must precede nothing destructive on disk,
        // and must come after the upload. Verify the upload->verify ordering.
        let calls = op.calls.borrow();
        let upload = calls.iter().position(|c| c == "create_document").unwrap();
        let verify = calls.iter().position(|c| c == "get_document").unwrap();
        assert!(
            upload < verify,
            "upload must happen before read-back verify"
        );

        // The document id was persisted to .prot.
        let prot = prot::read(&dir.path().join(PROT_FILE)).unwrap().unwrap();
        assert_eq!(prot.document_id(".env"), Some("DOC0"));
    }

    #[test]
    fn lock_keeps_file_when_readback_mismatches() {
        let dir = setup_dir(b"SECRET=1\n");
        let op = MockOp::corrupting();

        // The cardinal rule: a mismatched read-back must NOT delete the file.
        let err = lock(&op, dir.path(), false, None).unwrap_err();

        assert!(
            dir.path().join(".env").exists(),
            ".env must survive a failed verification"
        );
        assert!(
            err.to_string().contains("Verification failed"),
            "expected a verification-failed error, got: {err}"
        );
        // And we never recorded a (bogus) success in .prot.
        let prot = prot::read(&dir.path().join(PROT_FILE)).unwrap().unwrap();
        assert_eq!(prot.document_id(".env"), None);
    }

    #[test]
    fn lock_with_keep_uploads_and_verifies_but_does_not_delete() {
        let dir = setup_dir(b"SECRET=1\n");
        let op = MockOp::new();

        lock(&op, dir.path(), true, None).unwrap();

        assert!(
            dir.path().join(".env").exists(),
            "--keep must leave the file on disk"
        );
        // It was still uploaded and verified (id recorded), so the user can
        // confirm the vault copy before trusting deletion.
        let calls = op.calls.borrow();
        assert!(calls.iter().any(|c| c == "get_document"), "must verify");
        let prot = prot::read(&dir.path().join(PROT_FILE)).unwrap().unwrap();
        assert_eq!(prot.document_id(".env"), Some("DOC0"));
    }

    #[test]
    fn unlock_restores_file_with_owner_only_mode() {
        let dir = setup_dir(b"SECRET=restored\n");
        let op = MockOp::new();

        // Lock first (file gets deleted), then unlock to restore it.
        lock(&op, dir.path(), false, None).unwrap();
        assert!(!dir.path().join(".env").exists());

        unlock(&op, dir.path()).unwrap();

        let restored = fs::read(dir.path().join(".env")).unwrap();
        assert_eq!(restored, b"SECRET=restored\n");

        #[cfg(unix)]
        {
            use std::os::unix::fs::PermissionsExt;
            let mode = fs::metadata(dir.path().join(".env"))
                .unwrap()
                .permissions()
                .mode();
            assert_eq!(mode & 0o777, 0o600, "restored file must be 0600");
        }
    }

    #[test]
    fn lock_keeps_file_that_changed_during_upload() {
        let dir = setup_dir(b"SECRET=1\n");
        let mut op = MockOp::new();
        // The vault copy round-trips fine, but the file on disk is rewritten
        // during the verify step — deleting it would lose the new contents.
        op.rewrite_on_get = Some((dir.path().join(".env"), b"SECRET=2\n".to_vec()));

        let err = lock(&op, dir.path(), false, None).unwrap_err();

        assert!(
            err.to_string().contains("changed on disk"),
            "expected a changed-on-disk error, got: {err}"
        );
        assert_eq!(
            fs::read(dir.path().join(".env")).unwrap(),
            b"SECRET=2\n",
            "the modified file must survive untouched"
        );
    }

    #[cfg(unix)]
    #[test]
    fn unlock_refuses_to_write_through_dangling_symlink() {
        let dir = setup_dir(b"SECRET=1\n");
        let op = MockOp::new();
        lock(&op, dir.path(), false, None).unwrap();

        // Plant a dangling symlink where .env used to be. `file_exists` reads
        // it as absent (try_exists follows links), so unlock proceeds — but the
        // open must refuse to write through the link.
        let target = dir.path().join("attacker-target");
        std::os::unix::fs::symlink(&target, dir.path().join(".env")).unwrap();

        let err = unlock(&op, dir.path()).unwrap_err();
        assert!(
            format!("{err:#}").contains("refusing to write"),
            "expected a refusal error, got: {err:#}"
        );
        assert!(
            !target.exists(),
            "secret must not be written through the symlink"
        );
    }

    #[test]
    fn unlock_rejects_paths_that_escape_the_directory() {
        let dir = setup_dir(b"SECRET=1\n");
        let op = MockOp::new();
        lock(&op, dir.path(), false, None).unwrap();

        // Simulate a tampered .prot: rewrite the recorded entry to a traversal
        // path pointing outside the working directory.
        let mut prot = prot::read(&dir.path().join(PROT_FILE)).unwrap().unwrap();
        let id = prot.document_id(".env").unwrap().to_string();
        prot.documents = vec![("../escaped.env".to_string(), id)];
        prot::write(&dir.path().join(PROT_FILE), &prot).unwrap();

        let err = unlock(&op, dir.path()).unwrap_err();
        assert!(
            err.to_string().contains("Refusing to restore"),
            "expected a traversal refusal, got: {err}"
        );
        assert!(
            !dir.path().join("../escaped.env").exists(),
            "nothing may be written outside the working directory"
        );
    }

    #[test]
    fn unlock_reports_missing_parent_directory_accurately() {
        let dir = setup_dir(b"SECRET=1\n");
        let op = MockOp::new();
        lock(&op, dir.path(), false, None).unwrap();

        // A nested path whose directory is absent (e.g. a fresh clone — git
        // can't track the now-empty dir). The error must point at the missing
        // directory, not claim something already exists there.
        let mut prot = prot::read(&dir.path().join(PROT_FILE)).unwrap().unwrap();
        let id = prot.document_id(".env").unwrap().to_string();
        prot.documents = vec![("config/.env".to_string(), id)];
        prot::write(&dir.path().join(PROT_FILE), &prot).unwrap();

        let err = unlock(&op, dir.path()).unwrap_err();
        let msg = format!("{err:#}");
        assert!(
            msg.contains("parent directory does not exist"),
            "expected a missing-directory hint, got: {msg}"
        );
        assert!(
            !msg.contains("already exists"),
            "must not claim something exists when the parent dir is missing: {msg}"
        );
    }

    #[test]
    fn validate_restore_path_allows_only_plain_relative_paths() {
        assert!(validate_restore_path(".env").is_ok());
        assert!(validate_restore_path("nested/dir/.env").is_ok());
        assert!(validate_restore_path("../up.env").is_err());
        assert!(validate_restore_path("/abs/path.env").is_err());
        assert!(validate_restore_path("a/../b.env").is_err());
        assert!(validate_restore_path("").is_err());
    }

    /// On Windows, `\Users\x` is rooted but NOT absolute and has no Prefix or
    /// ParentDir component — `cwd.join()` would replace everything except the
    /// drive letter with it. The allowlist must reject it. (Runs on the
    /// windows-latest CI job; on Unix a backslash is an ordinary filename
    /// character, so this shape isn't parseable the same way.)
    #[cfg(windows)]
    #[test]
    fn validate_restore_path_rejects_rooted_driveless_windows_paths() {
        assert!(validate_restore_path(r"\Users\victim\startup.bat").is_err());
        assert!(validate_restore_path(r"C:\Users\victim\x").is_err());
        assert!(validate_restore_path(r"C:relative.env").is_err());
    }

    #[test]
    fn unlock_validates_all_paths_before_restoring_anything() {
        let dir = setup_dir(b"SECRET=1\n");
        let op = MockOp::new();
        lock(&op, dir.path(), false, None).unwrap();

        // Tamper: a good entry first, a traversal entry second. Unlock must
        // fail atomically — the good file must NOT be restored first.
        let mut prot = prot::read(&dir.path().join(PROT_FILE)).unwrap().unwrap();
        let id = prot.document_id(".env").unwrap().to_string();
        prot.documents = vec![
            (".env".to_string(), id.clone()),
            ("../evil".to_string(), id),
        ];
        prot::write(&dir.path().join(PROT_FILE), &prot).unwrap();

        let err = unlock(&op, dir.path()).unwrap_err();

        assert!(err.to_string().contains("Refusing to restore"));
        assert!(
            !dir.path().join(".env").exists(),
            "a tampered .prot must abort before any file is restored"
        );
    }

    #[test]
    fn toggle_rejects_tampered_document_paths() {
        let dir = setup_dir(b"SECRET=1\n");
        let op = MockOp::new();
        lock(&op, dir.path(), false, None).unwrap();

        // A tampered absolute entry must not let toggle probe (and echo the
        // existence of) paths outside the project.
        let mut prot = prot::read(&dir.path().join(PROT_FILE)).unwrap().unwrap();
        let id = prot.document_id(".env").unwrap().to_string();
        prot.documents.push(("/etc/hosts".to_string(), id));
        prot::write(&dir.path().join(PROT_FILE), &prot).unwrap();

        let err = toggle(&op, dir.path(), false, None).unwrap_err();
        assert!(
            err.to_string().contains("Refusing to restore"),
            "expected toggle to reject the tampered path, got: {err}"
        );
    }

    // --- pattern expansion --------------------------------------------------

    #[test]
    fn lock_works_in_directory_with_glob_metacharacters() {
        let outer = tempfile::tempdir().unwrap();
        let dir = outer.path().join("we[i]rd dir");
        fs::create_dir(&dir).unwrap();
        fs::write(dir.join(".env"), b"SECRET=1\n").unwrap();
        let mut prot = ProtData::empty();
        prot.vault = Some("VAULT".to_string());
        prot::write(&dir.join(PROT_FILE), &prot).unwrap();

        let op = MockOp::new();
        lock(&op, &dir, false, None).unwrap();

        assert!(
            !dir.join(".env").exists(),
            ".env must lock even when the project path contains [ ] metacharacters"
        );
    }

    #[test]
    fn expand_patterns_skips_matches_outside_the_working_directory() {
        let outer = tempfile::tempdir().unwrap();
        let dir = outer.path().join("project");
        fs::create_dir(&dir).unwrap();
        fs::write(outer.path().join("outside.env"), b"SECRET=1\n").unwrap();

        let matches = expand_patterns(&dir, &["../outside.env".to_string()]).unwrap();

        assert!(
            matches.is_empty(),
            "files outside cwd must not be treated as protectable: {matches:?}"
        );
    }

    #[test]
    fn expand_patterns_does_not_reanchor_absolute_patterns_under_cwd() {
        // Regression test: an absolute pattern must keep Path::join semantics
        // (the pattern stands alone). Concatenating it onto cwd would make
        // `/shared/x.env` match `<cwd>/shared/x.env` — a different file that
        // lock would then upload and DELETE.
        let dir = tempfile::tempdir().unwrap();
        fs::create_dir(dir.path().join("shared")).unwrap();
        fs::write(dir.path().join("shared/x.env"), b"SECRET=1\n").unwrap();

        let matches = expand_patterns(dir.path(), &["/shared/x.env".to_string()]).unwrap();

        assert!(
            matches.is_empty(),
            "an absolute pattern must not match a cwd-relative file: {matches:?}"
        );
    }

    #[test]
    fn expand_patterns_matches_absolute_pattern_inside_cwd() {
        // An absolute pattern that names a file inside the project worked
        // before the glob-escaping change and must keep working.
        let dir = tempfile::tempdir().unwrap();
        fs::write(dir.path().join(".env"), b"SECRET=1\n").unwrap();
        let abs = dir.path().join(".env").to_string_lossy().to_string();

        let matches = expand_patterns(dir.path(), &[abs]).unwrap();

        assert_eq!(matches, vec![".env".to_string()]);
    }

    #[cfg(unix)]
    #[test]
    fn expand_patterns_skips_filenames_with_control_characters() {
        let dir = tempfile::tempdir().unwrap();
        fs::write(dir.path().join(".env\nx"), b"SECRET=1\n").unwrap();
        fs::write(dir.path().join(".env"), b"SECRET=1\n").unwrap();

        let matches = expand_patterns(dir.path(), &[".env*".to_string()]).unwrap();

        assert_eq!(
            matches,
            vec![".env".to_string()],
            "a newline in a filename would corrupt the .prot line format"
        );
    }

    #[cfg(unix)]
    #[test]
    fn expand_patterns_skips_filenames_with_edge_whitespace() {
        // prot::parse trims each recorded key, so a file named `.env ` would
        // be locked and deleted but recorded under the trimmed key `.env` —
        // its mapping lost. Such names must be skipped before upload.
        let dir = tempfile::tempdir().unwrap();
        fs::write(dir.path().join(".env "), b"SECRET=1\n").unwrap();
        fs::write(dir.path().join(".env"), b"SECRET=1\n").unwrap();

        let matches = expand_patterns(dir.path(), &[".env*".to_string()]).unwrap();

        assert_eq!(
            matches,
            vec![".env".to_string()],
            "edge whitespace is trimmed by the .prot parser and must be refused"
        );
    }

    // --- .prot backup & restore ---------------------------------------------

    #[test]
    fn lock_mirrors_prot_to_the_home_backup() {
        let dir = setup_dir(b"SECRET=1\n");
        let home = tempfile::tempdir().unwrap();
        let op = MockOp::new();

        lock(&op, dir.path(), false, Some(home.path())).unwrap();

        let backup = crate::backup::backup_file(home.path(), dir.path());
        let backed_up = prot::read(&backup).unwrap().expect("backup must exist");
        assert_eq!(
            backed_up.document_id(".env"),
            Some("DOC0"),
            "backup must carry the recorded document id"
        );
    }

    #[test]
    fn restore_recovers_a_deleted_prot() {
        let dir = setup_dir(b"SECRET=1\n");
        let home = tempfile::tempdir().unwrap();
        let op = MockOp::new();
        lock(&op, dir.path(), false, Some(home.path())).unwrap();

        // The accident: .prot is gone.
        fs::remove_file(dir.path().join(PROT_FILE)).unwrap();

        restore(dir.path(), Some(home.path())).unwrap();

        let recovered = prot::read(&dir.path().join(PROT_FILE)).unwrap().unwrap();
        assert_eq!(
            recovered.document_id(".env"),
            Some("DOC0"),
            "restored .prot must still map .env to its document"
        );
        // The restored file immediately supports unlock.
        unlock(&op, dir.path()).unwrap();
        assert_eq!(fs::read(dir.path().join(".env")).unwrap(), b"SECRET=1\n");
    }

    #[test]
    fn restore_is_a_noop_when_prot_matches_the_backup() {
        let dir = setup_dir(b"SECRET=1\n");
        let home = tempfile::tempdir().unwrap();
        let op = MockOp::new();
        lock(&op, dir.path(), false, Some(home.path())).unwrap();

        let before = fs::read(dir.path().join(PROT_FILE)).unwrap();
        restore(dir.path(), Some(home.path())).unwrap();
        assert_eq!(fs::read(dir.path().join(PROT_FILE)).unwrap(), before);
    }

    #[test]
    fn restore_refuses_to_overwrite_a_differing_prot() {
        let dir = setup_dir(b"SECRET=1\n");
        let home = tempfile::tempdir().unwrap();
        let op = MockOp::new();
        lock(&op, dir.path(), false, Some(home.path())).unwrap();

        // The local .prot has since diverged from the backup.
        fs::write(dir.path().join(PROT_FILE), b"hand-edited\n").unwrap();

        let err = restore(dir.path(), Some(home.path())).unwrap_err();
        assert!(
            err.to_string().contains("Refusing to overwrite"),
            "expected an overwrite refusal, got: {err}"
        );
        assert_eq!(
            fs::read(dir.path().join(PROT_FILE)).unwrap(),
            b"hand-edited\n",
            "the diverged .prot must be left untouched"
        );
    }

    #[test]
    fn restore_errors_clearly_when_no_backup_exists() {
        let dir = tempfile::tempdir().unwrap();
        let home = tempfile::tempdir().unwrap();

        let err = restore(dir.path(), Some(home.path())).unwrap_err();
        assert!(
            err.to_string().contains("No backup"),
            "expected a no-backup error, got: {err}"
        );
    }

    #[test]
    fn lock_succeeds_even_when_backup_location_is_unavailable() {
        let dir = setup_dir(b"SECRET=1\n");
        let op = MockOp::new();

        // No home dir at all: the backup is skipped with a warning, but the
        // lock itself must proceed normally.
        lock(&op, dir.path(), false, None).unwrap();

        assert!(!dir.path().join(".env").exists(), ".env should still lock");
    }

    // --- vault resolution ---------------------------------------------------

    #[test]
    fn lock_refuses_vault_id_that_is_not_the_prot_vault() {
        let dir = setup_dir(b"SECRET=1\n");
        let mut op = MockOp::new();
        // The recorded vault ID resolves to some other vault in the account
        // (tampered or copy-pasted .prot).
        op.vault_name_response = Some("Personal".to_string());

        let err = lock(&op, dir.path(), false, None).unwrap_err();

        assert!(
            err.to_string().contains("is named \"Personal\""),
            "expected a wrong-vault refusal, got: {err}"
        );
        assert!(
            !op.called("create_document") && !op.called("edit_document"),
            "must not write documents into a vault that isn't \".prot\""
        );
        assert!(dir.path().join(".env").exists(), ".env must be untouched");
    }

    #[test]
    fn lock_refuses_vault_id_that_no_longer_exists() {
        let dir = setup_dir(b"SECRET=1\n");
        let mut op = MockOp::new();
        op.vault_name_response = None; // recorded vault ID resolves to nothing

        let err = lock(&op, dir.path(), false, None).unwrap_err();

        assert!(
            err.to_string().contains("was not found"),
            "expected a vault-not-found error, got: {err}"
        );
        assert!(dir.path().join(".env").exists(), ".env must be untouched");
    }

    #[test]
    fn unlock_errors_instead_of_creating_a_missing_vault() {
        let dir = setup_dir(b"SECRET=1\n");
        let op = MockOp::new();
        lock(&op, dir.path(), false, None).unwrap();

        // Simulate a .prot with documents recorded but no usable vault: drop
        // the cached ID and make the by-name lookup come up empty.
        let mut prot = prot::read(&dir.path().join(PROT_FILE)).unwrap().unwrap();
        prot.vault = None;
        prot::write(&dir.path().join(PROT_FILE), &prot).unwrap();
        let mut op = MockOp::new();
        op.find_vault_response = None;

        let err = unlock(&op, dir.path()).unwrap_err();

        assert!(
            err.to_string().contains("No \".prot\" vault found"),
            "expected a missing-vault error, got: {err}"
        );
        assert!(
            !op.called("create_vault"),
            "unlock must never create a vault — the recorded documents \
             couldn't be in a fresh one"
        );
    }

    // --- sign-in orchestration --------------------------------------------

    #[test]
    fn ensure_signed_in_is_noop_when_already_signed_in() {
        let op = MockOp::new(); // starts signed in
        ensure_signed_in_with(&op, || panic!("must not prompt when already signed in")).unwrap();
        assert!(
            !op.called("sign_in"),
            "must not sign in when already signed in"
        );
    }

    #[test]
    fn ensure_signed_in_signs_in_when_user_confirms() {
        let op = MockOp::signed_out();
        // User says yes.
        ensure_signed_in_with(&op, || Ok(true)).unwrap();
        assert!(op.called("sign_in"), "should have run sign_in on confirm");
    }

    #[test]
    fn ensure_signed_in_errors_and_skips_signin_when_user_declines() {
        let op = MockOp::signed_out();
        // User says no (this is also the non-interactive fallback: confirm = false).
        let err = ensure_signed_in_with(&op, || Ok(false)).unwrap_err();
        assert!(
            err.to_string().contains("not signed in"),
            "expected a not-signed-in error, got: {err}"
        );
        assert!(
            !op.called("sign_in"),
            "must not sign in when the user declines / non-interactive"
        );
    }

    #[test]
    fn ensure_signed_in_errors_when_signin_does_not_take() {
        let mut op = MockOp::signed_out();
        op.signin_fails = true; // op signin "succeeds" but session still unusable
        let err = ensure_signed_in_with(&op, || Ok(true)).unwrap_err();
        assert!(
            err.to_string().contains("Still not signed in"),
            "expected a post-signin failure, got: {err}"
        );
    }

    #[test]
    fn lock_aborts_without_touching_files_when_not_signed_in() {
        let dir = setup_dir(b"SECRET=1\n");
        // Signed out; non-interactive test harness means the prompt resolves to
        // "no", so lock must bail before uploading or deleting anything.
        let op = MockOp::signed_out();

        let err = lock(&op, dir.path(), false, None).unwrap_err();

        assert!(err.to_string().contains("not signed in"));
        assert!(
            dir.path().join(".env").exists(),
            ".env must be untouched when not signed in"
        );
        assert!(
            !op.called("create_document"),
            "must not upload when signed out"
        );
    }
}