bigtext 0.19.0

Free editor for huge text and log files (1-50+ GB): opens them without loading them into memory, 4 GB/s search, atomic save
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
701
702
703
704
705
706
707
708
709
710
711
712
713
//! Where API keys live. A key in an environment variable is used as it is and never stored.
//! Otherwise the system's keychain keeps it (Windows Credential Manager, the macOS keychain,
//! the Secret Service on Linux); a portable copy, and a computer without a keychain, keep keys
//! in a file encrypted with ChaCha20-Poly1305, so they move with the portable folder. That
//! file's key is a random key file next to it, or a passphrase the user chooses. Keys never
//! go into the settings file, sessions, the settings export or error messages.

use std::collections::BTreeMap;
use std::path::{Path, PathBuf};

use ring::aead::{self, Aad, LessSafeKey, Nonce, UnboundKey, CHACHA20_POLY1305};
use ring::rand::{SecureRandom, SystemRandom};

use super::Preset;

/// The name keys are stored under in the keychain.
pub const SERVICE: &str = "BigText AI";

/// The generic variable read for any provider when its own is not set.
pub const ENV_ANY: &str = "BIGTEXT_AI_KEY";

/// The provider's key from the environment, and the variable it came from.
pub fn from_env(p: &Preset) -> Option<(String, &'static str)> {
    [p.env, ENV_ANY]
        .into_iter()
        .filter(|v| !v.is_empty())
        .find_map(|v| {
            let k = std::env::var(v).ok()?;
            let k = k.trim();
            (!k.is_empty()).then(|| (k.to_string(), v))
        })
}

#[derive(Clone, Debug, PartialEq, Eq)]
pub enum KeyError {
    /// The key file is locked with a passphrase that has not been given.
    NeedPassphrase,
    WrongPassphrase,
    Other(String),
}

impl std::fmt::Display for KeyError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            KeyError::NeedPassphrase => f.write_str("The keys are locked with a passphrase."),
            KeyError::WrongPassphrase => f.write_str("The passphrase is not right."),
            KeyError::Other(e) => f.write_str(e),
        }
    }
}

/// Where a store keeps its keys.
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum Kind {
    Keychain,
    /// An encrypted file (portable copies, or no keychain).
    File(PathBuf),
}

/// The keys of this copy of BigText.
#[derive(Clone, Debug)]
pub struct KeyStore {
    pub kind: Kind,
    /// Unlocks a file kept with a passphrase.
    pub passphrase: Option<String>,
}

/// The encrypted file in `dir`.
pub fn file_in(dir: &Path) -> PathBuf {
    dir.join("ai-keys.dat")
}

impl KeyStore {
    /// The keychain, or in portable mode the encrypted file in the portable folder.
    pub fn for_this_copy() -> KeyStore {
        let kind = match crate::settings_file::portable_dir() {
            Some(d) => Kind::File(file_in(&d)),
            None => Kind::Keychain,
        };
        KeyStore {
            kind,
            passphrase: None,
        }
    }

    /// The encrypted file used when the keychain cannot be: next to the settings file.
    fn fallback() -> Option<PathBuf> {
        Some(file_in(crate::settings_file::state_file()?.parent()?))
    }

    pub fn get(&self, account: &str) -> Result<Option<String>, KeyError> {
        match &self.kind {
            Kind::File(p) => FileKeys::read(p, self.passphrase.as_deref()).map(|f| f.get(account)),
            Kind::Keychain => match os::get(account) {
                Ok(Some(k)) => Ok(Some(k)),
                // A key saved when the keychain could not be used.
                r => match Self::fallback().filter(|p| p.exists()) {
                    Some(p) => FileKeys::read(&p, self.passphrase.as_deref())
                        .map(|f| f.get(account))
                        .or(r.map_err(KeyError::Other)),
                    None => r.map_err(KeyError::Other),
                },
            },
        }
    }

    /// Stores `key`; returns where it went (the keychain, or the file when the keychain
    /// failed).
    pub fn set(&self, account: &str, key: &str) -> Result<Kind, KeyError> {
        let key = key.trim();
        match &self.kind {
            Kind::File(p) => {
                let mut f = FileKeys::read(p, self.passphrase.as_deref())?;
                f.keys.insert(account.to_string(), key.to_string());
                f.write(p)?;
                Ok(self.kind.clone())
            }
            Kind::Keychain => match os::set(account, key) {
                Ok(()) => Ok(Kind::Keychain),
                Err(e) => {
                    let p = Self::fallback().ok_or(KeyError::Other(e))?;
                    let mut f = FileKeys::read(&p, self.passphrase.as_deref())?;
                    f.keys.insert(account.to_string(), key.to_string());
                    f.write(&p)?;
                    Ok(Kind::File(p))
                }
            },
        }
    }

    pub fn delete(&self, account: &str) -> Result<(), KeyError> {
        let file = match &self.kind {
            Kind::File(p) => Some(p.clone()),
            Kind::Keychain => {
                os::delete(account).map_err(KeyError::Other)?;
                Self::fallback().filter(|p| p.exists())
            }
        };
        if let Some(p) = file {
            let mut f = FileKeys::read(&p, self.passphrase.as_deref())?;
            if f.keys.remove(account).is_some() {
                f.write(&p)?;
            }
        }
        Ok(())
    }

    /// Whether the file store is locked with a passphrase.
    pub fn locked_file(&self) -> bool {
        match &self.kind {
            Kind::File(p) => FileKeys::mode(p) == Some(Mode::Passphrase),
            Kind::Keychain => false,
        }
    }

    /// Re-encrypts the file store with `passphrase` (`None`: with a random key file).
    pub fn set_passphrase(&mut self, passphrase: Option<String>) -> Result<(), KeyError> {
        let Kind::File(p) = &self.kind else {
            return Err(KeyError::Other(
                "Only the key file has a passphrase.".into(),
            ));
        };
        let mut f = FileKeys::read(p, self.passphrase.as_deref())?;
        f.passphrase = passphrase.clone().filter(|s| !s.is_empty());
        f.write(p)?;
        self.passphrase = f.passphrase;
        Ok(())
    }
}

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum Mode {
    KeyFile = 0,
    Passphrase = 1,
}

const MAGIC: &[u8; 4] = b"BTAK";
const VERSION: u8 = 1;
const PBKDF2_ROUNDS: u32 = 300_000;

/// The keys of an encrypted file, decrypted.
#[derive(Default)]
struct FileKeys {
    keys: BTreeMap<String, String>,
    passphrase: Option<String>,
}

fn random<const N: usize>() -> Result<[u8; N], KeyError> {
    let mut b = [0u8; N];
    SystemRandom::new()
        .fill(&mut b)
        .map_err(|_| KeyError::Other("No random numbers from the system.".into()))?;
    Ok(b)
}

/// The key file next to `data` (`ai-keys.dat` → `ai-keys.key`).
fn key_path(data: &Path) -> PathBuf {
    data.with_extension("key")
}

fn write_private(path: &Path, bytes: &[u8]) -> Result<(), KeyError> {
    let io = |e: std::io::Error| KeyError::Other(format!("{}: {e}", path.display()));
    if let Some(d) = path.parent() {
        std::fs::create_dir_all(d).map_err(io)?;
    }
    let tmp = path.with_extension("tmp");
    std::fs::write(&tmp, bytes).map_err(io)?;
    #[cfg(unix)]
    {
        use std::os::unix::fs::PermissionsExt;
        let _ = std::fs::set_permissions(&tmp, std::fs::Permissions::from_mode(0o600));
    }
    std::fs::rename(&tmp, path).map_err(io)
}

impl FileKeys {
    fn mode(path: &Path) -> Option<Mode> {
        let b = std::fs::read(path).ok()?;
        (b.len() > 6 && &b[..4] == MAGIC).then(|| {
            if b[5] == Mode::Passphrase as u8 {
                Mode::Passphrase
            } else {
                Mode::KeyFile
            }
        })
    }

    fn cipher_key(
        mode: Mode,
        salt: &[u8],
        passphrase: Option<&str>,
        data: &Path,
        create: bool,
    ) -> Result<LessSafeKey, KeyError> {
        let mut key = [0u8; 32];
        match mode {
            Mode::Passphrase => {
                let pw = passphrase.ok_or(KeyError::NeedPassphrase)?;
                ring::pbkdf2::derive(
                    ring::pbkdf2::PBKDF2_HMAC_SHA256,
                    std::num::NonZeroU32::new(PBKDF2_ROUNDS).unwrap(),
                    salt,
                    pw.as_bytes(),
                    &mut key,
                );
            }
            Mode::KeyFile => {
                let kp = key_path(data);
                match std::fs::read(&kp) {
                    Ok(b) if b.len() == 32 => key.copy_from_slice(&b),
                    _ if create => {
                        key = random::<32>()?;
                        write_private(&kp, &key)?;
                    }
                    _ => {
                        return Err(KeyError::Other(format!(
                            "{} is missing: the keys cannot be read.",
                            kp.display()
                        )))
                    }
                }
            }
        }
        Ok(LessSafeKey::new(
            UnboundKey::new(&CHACHA20_POLY1305, &key)
                .map_err(|_| KeyError::Other("bad key".into()))?,
        ))
    }

    /// The keys in `path` (none when it does not exist yet).
    fn read(path: &Path, passphrase: Option<&str>) -> Result<FileKeys, KeyError> {
        let b = match std::fs::read(path) {
            Ok(b) => b,
            Err(e) if e.kind() == std::io::ErrorKind::NotFound => {
                return Ok(FileKeys {
                    keys: BTreeMap::new(),
                    passphrase: passphrase.map(str::to_string),
                })
            }
            Err(e) => return Err(KeyError::Other(format!("{}: {e}", path.display()))),
        };
        let bad = || KeyError::Other(format!("{} is damaged.", path.display()));
        if b.len() < 6 + 16 + 12 + aead::MAX_TAG_LEN || &b[..4] != MAGIC || b[4] != VERSION {
            return Err(bad());
        }
        let mode = if b[5] == Mode::Passphrase as u8 {
            Mode::Passphrase
        } else {
            Mode::KeyFile
        };
        let salt = &b[6..22];
        let nonce: [u8; 12] = b[22..34].try_into().map_err(|_| bad())?;
        let key = Self::cipher_key(mode, salt, passphrase, path, false)?;
        let mut sealed = b[34..].to_vec();
        let plain = key
            .open_in_place(
                Nonce::assume_unique_for_key(nonce),
                Aad::from(&b[..6]),
                &mut sealed,
            )
            .map_err(|_| match mode {
                Mode::Passphrase => KeyError::WrongPassphrase,
                Mode::KeyFile => bad(),
            })?;
        let keys = serde_json::from_slice(plain).map_err(|_| bad())?;
        Ok(FileKeys {
            keys,
            passphrase: match mode {
                Mode::Passphrase => passphrase.map(str::to_string),
                Mode::KeyFile => None,
            },
        })
    }

    fn get(&self, account: &str) -> Option<String> {
        self.keys.get(account).cloned()
    }

    fn write(&self, path: &Path) -> Result<(), KeyError> {
        let mode = if self.passphrase.is_some() {
            Mode::Passphrase
        } else {
            Mode::KeyFile
        };
        let salt = random::<16>()?;
        let nonce = random::<12>()?;
        let key = Self::cipher_key(mode, &salt, self.passphrase.as_deref(), path, true)?;
        let mut head = MAGIC.to_vec();
        head.extend([VERSION, mode as u8]);
        let mut data = serde_json::to_vec(&self.keys).unwrap_or_default();
        key.seal_in_place_append_tag(
            Nonce::assume_unique_for_key(nonce),
            Aad::from(&head[..]),
            &mut data,
        )
        .map_err(|_| KeyError::Other("encryption failed".into()))?;
        let mut out = head;
        out.extend(salt);
        out.extend(nonce);
        out.extend(data);
        write_private(path, &out)?;
        if mode == Mode::Passphrase {
            // The passphrase replaces the key file.
            let _ = std::fs::remove_file(key_path(path));
        }
        Ok(())
    }
}

#[cfg(windows)]
mod os {
    use windows_sys::Win32::Foundation::{GetLastError, ERROR_NOT_FOUND, FILETIME};
    use windows_sys::Win32::Security::Credentials::{
        CredDeleteW, CredFree, CredReadW, CredWriteW, CREDENTIALW, CRED_PERSIST_LOCAL_MACHINE,
        CRED_TYPE_GENERIC,
    };

    fn wide(s: &str) -> Vec<u16> {
        s.encode_utf16().chain(std::iter::once(0)).collect()
    }

    fn target(account: &str) -> Vec<u16> {
        wide(&format!("{}/{account}", super::SERVICE))
    }

    pub fn get(account: &str) -> Result<Option<String>, String> {
        let t = target(account);
        let mut p: *mut CREDENTIALW = std::ptr::null_mut();
        // SAFETY: `t` is a NUL-terminated wide string; `p` receives a buffer freed below.
        let ok = unsafe { CredReadW(t.as_ptr(), CRED_TYPE_GENERIC, 0, &mut p) };
        if ok == 0 {
            // SAFETY: no arguments.
            let e = unsafe { GetLastError() };
            return if e == ERROR_NOT_FOUND {
                Ok(None)
            } else {
                Err(format!("Windows Credential Manager error {e}"))
            };
        }
        // SAFETY: CredReadW succeeded, so `p` points at a credential with a blob of that size.
        let key = unsafe {
            let c = &*p;
            let blob = if c.CredentialBlob.is_null() {
                &[][..]
            } else {
                std::slice::from_raw_parts(c.CredentialBlob, c.CredentialBlobSize as usize)
            };
            let k = String::from_utf8_lossy(blob).into_owned();
            CredFree(p as *const _);
            k
        };
        Ok(Some(key))
    }

    pub fn set(account: &str, key: &str) -> Result<(), String> {
        let mut t = target(account);
        let mut user = wide("BigText");
        let mut blob = key.as_bytes().to_vec();
        let c = CREDENTIALW {
            Flags: 0,
            Type: CRED_TYPE_GENERIC,
            TargetName: t.as_mut_ptr(),
            Comment: std::ptr::null_mut(),
            LastWritten: FILETIME {
                dwLowDateTime: 0,
                dwHighDateTime: 0,
            },
            CredentialBlobSize: blob.len() as u32,
            CredentialBlob: blob.as_mut_ptr(),
            Persist: CRED_PERSIST_LOCAL_MACHINE,
            AttributeCount: 0,
            Attributes: std::ptr::null_mut(),
            TargetAlias: std::ptr::null_mut(),
            UserName: user.as_mut_ptr(),
        };
        // SAFETY: every pointer in `c` points at a live buffer for the duration of the call.
        if unsafe { CredWriteW(&c, 0) } == 0 {
            // SAFETY: no arguments.
            return Err(format!("Windows Credential Manager error {}", unsafe {
                GetLastError()
            }));
        }
        Ok(())
    }

    pub fn delete(account: &str) -> Result<(), String> {
        let t = target(account);
        // SAFETY: `t` is a NUL-terminated wide string.
        if unsafe { CredDeleteW(t.as_ptr(), CRED_TYPE_GENERIC, 0) } == 0 {
            // SAFETY: no arguments.
            let e = unsafe { GetLastError() };
            if e != ERROR_NOT_FOUND {
                return Err(format!("Windows Credential Manager error {e}"));
            }
        }
        Ok(())
    }
}

/// A key goes into a command's input, never its arguments (other programs can list those).
#[cfg(unix)]
fn safe_for_input(key: &str) -> Result<(), String> {
    if key.contains(['"', '\\', '\n', '\r']) {
        Err("The key has characters a key does not have.".into())
    } else {
        Ok(())
    }
}

#[cfg(target_os = "macos")]
mod os {
    use std::io::Write;
    use std::process::{Command, Stdio};

    const SECURITY: &str = "/usr/bin/security";
    /// `security`'s exit code for "no such item".
    const NOT_FOUND: i32 = 44;

    pub fn get(account: &str) -> Result<Option<String>, String> {
        let out = Command::new(SECURITY)
            .args([
                "find-generic-password",
                "-s",
                super::SERVICE,
                "-a",
                account,
                "-w",
            ])
            .output()
            .map_err(|e| e.to_string())?;
        if out.status.success() {
            return Ok(Some(
                String::from_utf8_lossy(&out.stdout).trim().to_string(),
            ));
        }
        if out.status.code() == Some(NOT_FOUND) {
            return Ok(None);
        }
        Err(String::from_utf8_lossy(&out.stderr).trim().to_string())
    }

    pub fn set(account: &str, key: &str) -> Result<(), String> {
        super::safe_for_input(key)?;
        // Interactive mode reads the command from its input, so the key is not an argument.
        let mut child = Command::new(SECURITY)
            .arg("-i")
            .stdin(Stdio::piped())
            .stdout(Stdio::null())
            .stderr(Stdio::piped())
            .spawn()
            .map_err(|e| e.to_string())?;
        let cmd = format!(
            "add-generic-password -U -s \"{}\" -a \"{account}\" -w \"{key}\"\n",
            super::SERVICE
        );
        if let Some(mut i) = child.stdin.take() {
            i.write_all(cmd.as_bytes()).map_err(|e| e.to_string())?;
        }
        let out = child.wait_with_output().map_err(|e| e.to_string())?;
        if !out.status.success() || !out.stderr.is_empty() {
            return Err(String::from_utf8_lossy(&out.stderr).trim().to_string());
        }
        Ok(())
    }

    pub fn delete(account: &str) -> Result<(), String> {
        let out = Command::new(SECURITY)
            .args([
                "delete-generic-password",
                "-s",
                super::SERVICE,
                "-a",
                account,
            ])
            .output()
            .map_err(|e| e.to_string())?;
        if out.status.success() || out.status.code() == Some(NOT_FOUND) {
            Ok(())
        } else {
            Err(String::from_utf8_lossy(&out.stderr).trim().to_string())
        }
    }
}

/// Linux and the other Unixes: the Secret Service (GNOME Keyring, KWallet) through
/// `secret-tool`, which takes the key on its input.
#[cfg(all(unix, not(target_os = "macos")))]
mod os {
    use std::io::Write;
    use std::process::{Command, Stdio};

    fn tool() -> Command {
        Command::new("secret-tool")
    }

    fn missing(e: std::io::Error) -> String {
        if e.kind() == std::io::ErrorKind::NotFound {
            "secret-tool is not installed (package libsecret-tools or libsecret)".into()
        } else {
            e.to_string()
        }
    }

    pub fn get(account: &str) -> Result<Option<String>, String> {
        let out = tool()
            .args(["lookup", "service", super::SERVICE, "account", account])
            .output()
            .map_err(missing)?;
        let key = String::from_utf8_lossy(&out.stdout).trim().to_string();
        if out.status.success() && !key.is_empty() {
            return Ok(Some(key));
        }
        if out.stderr.is_empty() {
            return Ok(None);
        }
        Err(String::from_utf8_lossy(&out.stderr).trim().to_string())
    }

    pub fn set(account: &str, key: &str) -> Result<(), String> {
        super::safe_for_input(key)?;
        let label = format!("{}: {account}", super::SERVICE);
        let mut child = tool()
            .args([
                "store",
                "--label",
                &label,
                "service",
                super::SERVICE,
                "account",
                account,
            ])
            .stdin(Stdio::piped())
            .stdout(Stdio::null())
            .stderr(Stdio::piped())
            .spawn()
            .map_err(missing)?;
        if let Some(mut i) = child.stdin.take() {
            i.write_all(key.as_bytes()).map_err(|e| e.to_string())?;
        }
        let out = child.wait_with_output().map_err(|e| e.to_string())?;
        if out.status.success() {
            Ok(())
        } else {
            Err(String::from_utf8_lossy(&out.stderr).trim().to_string())
        }
    }

    pub fn delete(account: &str) -> Result<(), String> {
        let out = tool()
            .args(["clear", "service", super::SERVICE, "account", account])
            .output()
            .map_err(missing)?;
        if out.status.success() || out.stderr.is_empty() {
            Ok(())
        } else {
            Err(String::from_utf8_lossy(&out.stderr).trim().to_string())
        }
    }
}

#[cfg(not(any(windows, unix)))]
mod os {
    pub fn get(_: &str) -> Result<Option<String>, String> {
        Err("no keychain".into())
    }
    pub fn set(_: &str, _: &str) -> Result<(), String> {
        Err("no keychain".into())
    }
    pub fn delete(_: &str) -> Result<(), String> {
        Ok(())
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    fn file_store(dir: &Path) -> KeyStore {
        KeyStore {
            kind: Kind::File(file_in(dir)),
            passphrase: None,
        }
    }

    #[test]
    fn file_keys_round_trip_encrypted() {
        let dir = tempfile::tempdir().unwrap();
        let s = file_store(dir.path());
        assert_eq!(s.get("anthropic").unwrap(), None);
        assert_eq!(s.set("anthropic", " sk-ant-secret-1 ").unwrap(), s.kind);
        s.set("openai", "sk-openai-2").unwrap();
        assert_eq!(
            s.get("anthropic").unwrap().as_deref(),
            Some("sk-ant-secret-1")
        );
        let raw = std::fs::read(file_in(dir.path())).unwrap();
        assert!(
            !raw.windows(6).any(|w| w == b"sk-ant"),
            "stored in the clear"
        );
        assert!(dir.path().join("ai-keys.key").exists());
        s.delete("anthropic").unwrap();
        assert_eq!(s.get("anthropic").unwrap(), None);
        assert_eq!(s.get("openai").unwrap().as_deref(), Some("sk-openai-2"));
    }

    #[test]
    fn a_passphrase_locks_the_file() {
        let dir = tempfile::tempdir().unwrap();
        let mut s = file_store(dir.path());
        s.set("groq", "gsk-123456").unwrap();
        s.set_passphrase(Some("correct horse".into())).unwrap();
        assert!(s.locked_file());
        assert!(!dir.path().join("ai-keys.key").exists());
        let locked = file_store(dir.path());
        assert_eq!(locked.get("groq"), Err(KeyError::NeedPassphrase));
        let wrong = KeyStore {
            passphrase: Some("wrong".into()),
            ..file_store(dir.path())
        };
        assert_eq!(wrong.get("groq"), Err(KeyError::WrongPassphrase));
        assert_eq!(s.get("groq").unwrap().as_deref(), Some("gsk-123456"));
        s.set_passphrase(None).unwrap();
        assert_eq!(
            file_store(dir.path()).get("groq").unwrap().as_deref(),
            Some("gsk-123456")
        );
    }

    #[test]
    fn a_damaged_file_is_an_error_not_a_panic() {
        let dir = tempfile::tempdir().unwrap();
        let s = file_store(dir.path());
        s.set("a", "k-123456").unwrap();
        let p = file_in(dir.path());
        let mut b = std::fs::read(&p).unwrap();
        let last = b.len() - 1;
        b[last] ^= 1;
        std::fs::write(&p, b).unwrap();
        assert!(matches!(s.get("a"), Err(KeyError::Other(_))));
        std::fs::write(&p, b"xx").unwrap();
        assert!(matches!(s.get("a"), Err(KeyError::Other(_))));
    }

    #[test]
    fn environment_keys() {
        let p = Preset {
            env: "BIGTEXT_TEST_KEY_VAR_XYZ",
            ..*super::super::preset("openai").unwrap()
        };
        std::env::set_var("BIGTEXT_TEST_KEY_VAR_XYZ", "  sk-env  ");
        assert_eq!(
            from_env(&p),
            Some(("sk-env".into(), "BIGTEXT_TEST_KEY_VAR_XYZ"))
        );
        std::env::remove_var("BIGTEXT_TEST_KEY_VAR_XYZ");
    }

    /// Writes to the real keychain: `cargo test -- --ignored keychain`.
    #[test]
    #[ignore]
    fn keychain_round_trip() {
        let s = KeyStore {
            kind: Kind::Keychain,
            passphrase: None,
        };
        let acct = "bigtext-test-account";
        s.set(acct, "sk-test-keychain").unwrap();
        assert_eq!(s.get(acct).unwrap().as_deref(), Some("sk-test-keychain"));
        s.delete(acct).unwrap();
        assert_eq!(os::get(acct).unwrap(), None);
    }
}