dotprot 0.3.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
//! 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, Result};

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

pub const VAULT_NAME: &str = ".prot";
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)
}

/// 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();

    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.
        let abs_pattern = cwd.join(pattern);
        let abs_pattern = abs_pattern.to_string_lossy();
        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;
            }
            if let Ok(rel) = path.strip_prefix(cwd) {
                let rel = rel.to_string_lossy().to_string();
                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 vault ID, finding it if not already cached in `prot`. If the
/// vault doesn't exist in 1Password yet, create it (a one-time action) and
/// announce it clearly so the user knows a vault was made in their account.
fn ensure_vault(op: &impl OpBackend, prot: &mut ProtData) -> Result<String> {
    if let Some(v) = &prot.vault {
        return Ok(v.clone());
    }
    let id = match op.find_vault(VAULT_NAME)? {
        Some(found) => found,
        None => {
            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
        }
    };
    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) -> 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)?;
            println!("Created {PROT_FILE} (protecting: {}).", p.patterns.join(", "));
            p
        }
    };

    let vault = ensure_vault(op, &mut prot)?;
    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 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.
        prot::write(&file, &prot)?;
        if keep {
            println!("  uploaded {rel_file} -> 1Password (kept on disk)");
        } else {
            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.");
    }

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

    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.
fn write_owner_only(path: &Path, content: &[u8]) -> Result<()> {
    use std::io::Write;
    let mut opts = fs::OpenOptions::new();
    opts.write(true).create(true).truncate(true);
    #[cfg(unix)]
    {
        use std::os::unix::fs::OpenOptionsExt;
        opts.mode(0o600);
    }
    let mut f = opts.open(path)?;
    f.write_all(content)?;
    Ok(())
}

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

pub fn toggle(op: &impl OpBackend, cwd: &Path, keep: bool) -> 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),
    };

    // 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. (--keep is a no-op here.)
        unlock(op, cwd)
    } else {
        // Everything recorded is present -> re-lock.
        lock(op, cwd, keep)
    }
}

#[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,
    }

    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,
            }
        }

        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>> {
            Ok(Some("VAULT".into()))
        }
        fn create_vault(&self, _name: &str, _description: &str) -> Result<String> {
            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());
            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).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).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).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).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");
        }
    }

    // --- 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).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"
        );
    }
}