second-brain-core 0.13.4

Core library for second-brain: SQLite storage with vector and lexical indexes, BGE embeddings, and hybrid retrieval
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
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
use std::collections::HashMap;
use std::env::VarError;
use std::fmt;
use std::fs;
use std::io::{self, ErrorKind, Read, Write};
use std::path::{Path, PathBuf};
use std::process::{Child, Command, ExitStatus, Stdio};
use std::sync::mpsc::{self, RecvTimeoutError};
use std::sync::{Arc, Mutex, MutexGuard, OnceLock, PoisonError};
use std::thread;
use std::time::{Duration, Instant};

use anyhow::{Context, Result, anyhow, bail, ensure};
use sha2::{Digest, Sha256};
use zeroize::Zeroizing;

use super::device::{create_private_dir, install_if_absent, sync_dir};
use super::hardware::{HardwareSource, SystemHardware, write_binding};
use super::store_key::replace_private_file;
use super::{DEVICE_KEY_FILE, DeviceKeys, KeyGuard};
use crate::sqlite_store::SqliteStore;

pub const SEALED_DEVICE_KEY_FILE: &str = "device.key.cred";
pub const KEY_STORE_ENV: &str = "SECOND_BRAIN_DEVICE_KEY_STORE";

const CREDENTIAL_NAME_ARG: &str = "--name=second-brain-device-key";
const CREDS_TIMEOUT: Duration = Duration::from_secs(30);
const CHILD_POLL: Duration = Duration::from_millis(10);
const PROBE_LEN: usize = 32;
const STDERR_SHOWN: usize = 400;

/// Seals secrets so that only this machine can open them again.
pub trait CredentialSealer: Send + Sync {
    fn seal(&self, plaintext: &[u8]) -> Result<Vec<u8>>;
    fn unseal(&self, sealed: &[u8]) -> Result<KeyGuard<Vec<u8>>>;
}

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum CredsCommand {
    Encrypt,
    Decrypt,
}

/// Seals with `systemd-creds` under the host key and the TPM, scoped to the
/// calling user unless it runs as root. Each call is killed after 30 s.
#[derive(Clone, Debug)]
pub struct SystemdCreds {
    program: PathBuf,
    user_scope: bool,
    timeout: Duration,
}

impl SystemdCreds {
    pub fn for_current_user() -> Self {
        Self::with_root(running_as_root())
    }

    fn with_root(is_root: bool) -> Self {
        Self {
            program: PathBuf::from("systemd-creds"),
            user_scope: !is_root,
            timeout: CREDS_TIMEOUT,
        }
    }

    fn args(&self, command: CredsCommand) -> Vec<&'static str> {
        let mut args = Vec::with_capacity(6);
        if self.user_scope {
            args.push("--user");
        }
        match command {
            CredsCommand::Encrypt => args.extend([
                "--with-key=host+tpm2",
                CREDENTIAL_NAME_ARG,
                "encrypt",
                "-",
                "-",
            ]),
            CredsCommand::Decrypt => {
                args.extend(["--newline=no", CREDENTIAL_NAME_ARG, "decrypt", "-", "-"])
            }
        }
        args
    }
}

impl CredentialSealer for SystemdCreds {
    fn seal(&self, plaintext: &[u8]) -> Result<Vec<u8>> {
        let sealed = run_bounded(
            &self.program,
            &self.args(CredsCommand::Encrypt),
            plaintext,
            self.timeout,
        )?;
        if sealed.is_empty() {
            bail!("{} encrypt wrote nothing", self.program.display());
        }
        Ok(sealed.to_vec())
    }

    fn unseal(&self, sealed: &[u8]) -> Result<KeyGuard<Vec<u8>>> {
        let mut plaintext = run_bounded(
            &self.program,
            &self.args(CredsCommand::Decrypt),
            sealed,
            self.timeout,
        )?;
        Ok(KeyGuard::new(std::mem::take(&mut *plaintext)))
    }
}

#[cfg(unix)]
fn running_as_root() -> bool {
    unsafe { libc::geteuid() == 0 }
}

#[cfg(not(unix))]
fn running_as_root() -> bool {
    false
}

#[derive(Clone)]
#[non_exhaustive]
pub enum KeyStorage {
    File,
    Sealed(Arc<dyn CredentialSealer>),
}

impl fmt::Debug for KeyStorage {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(self.name())
    }
}

impl KeyStorage {
    /// Picks the backend for creating keys: `KEY_STORE_ENV` when set to
    /// "file" or "tpm", otherwise sealed when a systemd-creds round trip
    /// works on this Linux host. Probes by running systemd-creds.
    pub fn detect() -> Self {
        let env = match std::env::var(KEY_STORE_ENV) {
            Ok(value) => Some(value),
            Err(VarError::NotPresent) => None,
            Err(VarError::NotUnicode(raw)) => {
                tracing::warn!(
                    "ignoring {KEY_STORE_ENV}={}; expected \"file\" or \"tpm\"",
                    raw.to_string_lossy()
                );
                None
            }
        };
        Self::detect_with(
            env.as_deref(),
            cfg!(target_os = "linux"),
            Arc::new(SystemdCreds::for_current_user()),
        )
    }

    /// Like `detect`, but a data dir that already holds a sealed key keeps
    /// the sealed backend without probing.
    pub fn detect_for(data_dir: &Path) -> Self {
        if data_dir.join(SEALED_DEVICE_KEY_FILE).exists() {
            return Self::Sealed(Arc::new(SystemdCreds::for_current_user()));
        }
        Self::detect()
    }

    pub fn detect_with(
        env: Option<&str>,
        linux: bool,
        candidate: Arc<dyn CredentialSealer>,
    ) -> Self {
        match env {
            Some("file") => return Self::File,
            Some("tpm") => return Self::Sealed(candidate),
            Some(other) => {
                tracing::warn!("ignoring {KEY_STORE_ENV}={other:?}; expected \"file\" or \"tpm\"")
            }
            None => {}
        }
        if !linux {
            tracing::info!(
                "keeping the device key in a file: sealing needs systemd-creds on Linux"
            );
            return Self::File;
        }
        match probe(candidate.as_ref()) {
            Ok(()) => Self::Sealed(candidate),
            Err(e) => {
                tracing::info!(
                    "keeping the device key in a file: systemd-creds cannot seal it here: {e:#}"
                );
                Self::File
            }
        }
    }

    pub fn name(&self) -> &'static str {
        match self {
            Self::File => "file",
            Self::Sealed(_) => "tpm",
        }
    }

    fn key_file(&self) -> &'static str {
        match self {
            Self::File => DEVICE_KEY_FILE,
            Self::Sealed(_) => SEALED_DEVICE_KEY_FILE,
        }
    }
}

fn probe(sealer: &dyn CredentialSealer) -> Result<()> {
    let sample = KeyGuard::<[u8; PROBE_LEN]>::random()?;
    let sealed = sealer.seal(sample.expose()).context("sealing a probe")?;
    let opened = sealer.unseal(&sealed).context("unsealing a probe")?;
    if opened.expose().as_slice() != sample.expose().as_slice() {
        bail!("an unsealed probe came back different");
    }
    Ok(())
}

/// Loads this device's keys from whichever key file `data_dir` holds,
/// unsealing `device.key.cred` with systemd-creds. Never probes or creates.
pub fn load_device_keys(data_dir: &Path) -> Result<Option<DeviceKeys>> {
    load_device_keys_with(data_dir, &SystemdCreds::for_current_user())
}

pub fn load_device_keys_in(data_dir: &Path, storage: &KeyStorage) -> Result<Option<DeviceKeys>> {
    match storage {
        KeyStorage::Sealed(sealer) => load_device_keys_with(data_dir, sealer.as_ref()),
        KeyStorage::File => load_device_keys(data_dir),
    }
}

/// When both key files exist, the plain file is left from an interrupted
/// migration: it is removed when both hold the same keys, used when the
/// sealed copy does not open, and an error when they differ.
pub fn load_device_keys_with(
    data_dir: &Path,
    sealer: &dyn CredentialSealer,
) -> Result<Option<DeviceKeys>> {
    let sealed_path = data_dir.join(SEALED_DEVICE_KEY_FILE);
    let plain_path = data_dir.join(DEVICE_KEY_FILE);
    let Some(sealed) = read_if_present(&sealed_path)? else {
        return DeviceKeys::load(&plain_path);
    };
    let keys = match open_sealed(&sealed_path, &sealed, sealer) {
        Ok(keys) => keys,
        Err(e) => {
            let Some(plain) = DeviceKeys::load(&plain_path)? else {
                return Err(e);
            };
            tracing::warn!(
                "using {} because the sealed copy beside it does not open: {e:#}",
                plain_path.display()
            );
            return Ok(Some(plain));
        }
    };
    if let Some(plain) = DeviceKeys::load(&plain_path)? {
        if !same_keys(&keys, &plain)? {
            bail!(
                "{} and {} hold different device keys; refusing to pick one",
                sealed_path.display(),
                plain_path.display()
            );
        }
        remove_plain_copy(data_dir, &plain_path)?;
    }
    Ok(Some(keys))
}

/// Loads this device's keys, generating them in `storage` on first start
/// and moving an existing plain key into sealed storage. Keys are never
/// regenerated once the store holds an envelope or a signed record for this
/// device. Returns true when the keys were generated by this call.
pub fn ensure_device_keys_in(
    store: &SqliteStore,
    data_dir: &Path,
    storage: &KeyStorage,
) -> Result<bool> {
    if let Some(keys) = load_device_keys_in(data_dir, storage)? {
        if let KeyStorage::Sealed(sealer) = storage
            && !data_dir.join(SEALED_DEVICE_KEY_FILE).exists()
            && let Err(e) = migrate_to_sealed(data_dir, &keys, sealer.as_ref())
        {
            tracing::warn!(
                "keeping {}: {e:#}",
                data_dir.join(DEVICE_KEY_FILE).display()
            );
        }
        return Ok(false);
    }
    let machine_id = store.machine_id();
    if store.device_record(machine_id)?.is_some()
        || !store.envelopes_for_machine(machine_id)?.is_empty()
    {
        bail!(
            "{} is missing but this store holds keys issued to this device; \
             restore the file from a backup or re-pair this device",
            data_dir.join(storage.key_file()).display()
        );
    }
    let created = create_in(data_dir, storage, &SystemHardware)?.is_some();
    if created {
        tracing::info!(
            "generated device keys in {} ({})",
            data_dir.display(),
            storage.name()
        );
    }
    Ok(created)
}

pub fn create_device_keys(data_dir: &Path, storage: &KeyStorage) -> Result<DeviceKeys> {
    create_device_keys_with(data_dir, storage, &SystemHardware)
}

pub(super) fn create_device_keys_with(
    data_dir: &Path,
    storage: &KeyStorage,
    source: &dyn HardwareSource,
) -> Result<DeviceKeys> {
    let occupied = || anyhow!("{} already holds a device key", data_dir.display());
    if has_device_key(data_dir) {
        return Err(occupied());
    }
    create_in(data_dir, storage, source)?.ok_or_else(occupied)
}

/// Replaces the device key in the form `data_dir` keeps it, so the next
/// load opens `keys`. A sealed copy beside a plain one is the copy the load
/// path could not open and fell back from, so it goes first: a crash
/// between the two steps leaves the plain key that opened the store.
pub(super) fn replace_device_keys(
    data_dir: &Path,
    storage: &KeyStorage,
    keys: &DeviceKeys,
) -> Result<()> {
    let sealed_path = data_dir.join(SEALED_DEVICE_KEY_FILE);
    let plain_path = data_dir.join(DEVICE_KEY_FILE);
    let secret = keys.to_secret_bytes()?;
    if plain_path.exists() {
        if sealed_path.exists() {
            remove_unopened_sealed_copy(data_dir, &sealed_path)?;
        }
        return replace_private_file(data_dir, DEVICE_KEY_FILE, secret.expose());
    }
    if !sealed_path.exists() {
        return replace_private_file(data_dir, DEVICE_KEY_FILE, secret.expose());
    }
    let sealer: Arc<dyn CredentialSealer> = match storage {
        KeyStorage::Sealed(sealer) => sealer.clone(),
        KeyStorage::File => Arc::new(SystemdCreds::for_current_user()),
    };
    let sealed = sealer
        .seal(secret.expose())
        .context("sealing the new device key")?;
    let opened = verify_sealed(sealer.as_ref(), &sealed, &secret)?;
    replace_private_file(data_dir, SEALED_DEVICE_KEY_FILE, &sealed)?;
    cache().insert(digest(&sealed), opened);
    Ok(())
}

fn remove_unopened_sealed_copy(data_dir: &Path, path: &Path) -> Result<()> {
    fs::remove_file(path).with_context(|| format!("removing {}", path.display()))?;
    tracing::info!(
        "removed {}, which does not open here, before replacing the device key",
        path.display()
    );
    sync_dir(data_dir)
}

fn verify_sealed(
    sealer: &dyn CredentialSealer,
    sealed: &[u8],
    secret: &KeyGuard<Vec<u8>>,
) -> Result<KeyGuard<Vec<u8>>> {
    let opened = sealer
        .unseal(sealed)
        .context("unsealing the new sealed device key")?;
    ensure!(
        opened.expose() == secret.expose(),
        "the new sealed device key unsealed to other bytes"
    );
    Ok(opened)
}

pub fn has_device_key(data_dir: &Path) -> bool {
    data_dir.join(DEVICE_KEY_FILE).exists() || data_dir.join(SEALED_DEVICE_KEY_FILE).exists()
}

fn create_in(
    data_dir: &Path,
    storage: &KeyStorage,
    source: &dyn HardwareSource,
) -> Result<Option<DeviceKeys>> {
    create_private_dir(data_dir)?;
    let keys = DeviceKeys::generate()?;
    let installed = match storage {
        KeyStorage::File => {
            let secret = keys.to_secret_bytes()?;
            install_if_absent(data_dir, &data_dir.join(DEVICE_KEY_FILE), secret.expose())?
        }
        KeyStorage::Sealed(sealer) => seal_into(data_dir, &keys, sealer.as_ref())?,
    };
    if installed {
        bind_to_hardware(data_dir, source);
    }
    Ok(installed.then_some(keys))
}

/// A binding that fails to write is recorded at the next start instead.
fn bind_to_hardware(data_dir: &Path, source: &dyn HardwareSource) {
    if let Err(e) = write_binding(data_dir, &source.read(data_dir)) {
        tracing::warn!("cannot record the hardware the device keys were made on: {e:#}");
    }
}

fn migrate_to_sealed(
    data_dir: &Path,
    keys: &DeviceKeys,
    sealer: &dyn CredentialSealer,
) -> Result<()> {
    if seal_into(data_dir, keys, sealer)? {
        remove_plain_copy(data_dir, &data_dir.join(DEVICE_KEY_FILE))?;
    }
    Ok(())
}

/// Installs the sealed key only if absent, and keeps it only once it
/// verifiably unseals to the same secret.
fn seal_into(data_dir: &Path, keys: &DeviceKeys, sealer: &dyn CredentialSealer) -> Result<bool> {
    let path = data_dir.join(SEALED_DEVICE_KEY_FILE);
    let secret = keys.to_secret_bytes()?;
    let sealed = sealer
        .seal(secret.expose())
        .context("sealing the device key")?;
    if !install_if_absent(data_dir, &path, &sealed)? {
        return Ok(false);
    }
    match verify_sealed(sealer, &sealed, &secret) {
        Ok(opened) => {
            cache().insert(digest(&sealed), opened);
            tracing::info!("sealed the device key into {}", path.display());
            Ok(true)
        }
        Err(e) => Err(remove_unverified(data_dir, &path, e)),
    }
}

fn remove_unverified(data_dir: &Path, path: &Path, error: anyhow::Error) -> anyhow::Error {
    match fs::remove_file(path)
        .map_err(anyhow::Error::from)
        .and_then(|()| sync_dir(data_dir))
    {
        Ok(()) => error,
        Err(e) => error.context(format!("also failed to remove {}: {e:#}", path.display())),
    }
}

fn remove_plain_copy(data_dir: &Path, path: &Path) -> Result<()> {
    match fs::remove_file(path) {
        Ok(()) => tracing::info!(
            "removed {} now that the device key is sealed",
            path.display()
        ),
        Err(e) if e.kind() == ErrorKind::NotFound => {}
        Err(e) => return Err(e).with_context(|| format!("removing {}", path.display())),
    }
    sync_dir(data_dir)
}

fn read_if_present(path: &Path) -> Result<Option<Vec<u8>>> {
    match fs::read(path) {
        Ok(bytes) => Ok(Some(bytes)),
        Err(e) if e.kind() == ErrorKind::NotFound => Ok(None),
        Err(e) => Err(e).with_context(|| format!("reading sealed device key {}", path.display())),
    }
}

fn open_sealed(path: &Path, sealed: &[u8], sealer: &dyn CredentialSealer) -> Result<DeviceKeys> {
    let corrupt = || format!("sealed device key {} is corrupt", path.display());
    let digest = digest(sealed);
    if let Some(secret) = cache().get(&digest) {
        return DeviceKeys::from_secret_bytes(secret.expose()).with_context(corrupt);
    }
    let secret = sealer.unseal(sealed).with_context(|| {
        format!(
            "cannot unseal {}; a sealed device key opens only on the hardware that sealed it",
            path.display()
        )
    })?;
    let keys = DeviceKeys::from_secret_bytes(secret.expose()).with_context(corrupt)?;
    cache().insert(digest, secret);
    Ok(keys)
}

fn same_keys(a: &DeviceKeys, b: &DeviceKeys) -> Result<bool> {
    Ok(a.to_secret_bytes()?.expose() == b.to_secret_bytes()?.expose())
}

fn digest(sealed: &[u8]) -> [u8; 32] {
    Sha256::digest(sealed).into()
}

type UnsealedCache = HashMap<[u8; 32], KeyGuard<Vec<u8>>>;

fn cache() -> MutexGuard<'static, UnsealedCache> {
    static UNSEALED: OnceLock<Mutex<UnsealedCache>> = OnceLock::new();
    UNSEALED
        .get_or_init(Mutex::default)
        .lock()
        .unwrap_or_else(PoisonError::into_inner)
}

pub(super) fn run_bounded(
    program: &Path,
    args: &[&str],
    input: &[u8],
    timeout: Duration,
) -> Result<Zeroizing<Vec<u8>>> {
    let shown = || format!("{} {}", program.display(), args.join(" "));
    let deadline = Instant::now() + timeout;
    let mut child = Command::new(program)
        .args(args)
        .stdin(Stdio::piped())
        .stdout(Stdio::piped())
        .stderr(Stdio::piped())
        .spawn()
        .with_context(|| format!("starting {}", shown()))?;
    let (Some(stdin), Some(stdout), Some(stderr)) =
        (child.stdin.take(), child.stdout.take(), child.stderr.take())
    else {
        return Err(anyhow!("{} started without pipes", shown()));
    };
    let written = write_in_background(stdin, Zeroizing::new(input.to_vec()));
    let output = read_in_background(stdout);
    let errors = read_in_background(stderr);
    let status = wait_until(&mut child, deadline, timeout).with_context(shown)?;
    let errors = receive(&errors, deadline, "stderr").with_context(shown)?;
    if !status.success() {
        bail!("{} exited with {status}: {}", shown(), excerpt(&errors));
    }
    receive(&written, deadline, "stdin").with_context(shown)?;
    receive(&output, deadline, "stdout").with_context(shown)
}

fn write_in_background(
    mut sink: impl Write + Send + 'static,
    input: Zeroizing<Vec<u8>>,
) -> mpsc::Receiver<io::Result<()>> {
    let (tx, rx) = mpsc::channel();
    thread::spawn(move || {
        let result = sink.write_all(&input);
        drop(sink);
        tx.send(result).ok();
    });
    rx
}

fn read_in_background(
    mut source: impl Read + Send + 'static,
) -> mpsc::Receiver<io::Result<Zeroizing<Vec<u8>>>> {
    let (tx, rx) = mpsc::channel();
    thread::spawn(move || {
        let mut buf = Zeroizing::new(Vec::with_capacity(4096));
        tx.send(source.read_to_end(&mut buf).map(|_| buf)).ok();
    });
    rx
}

fn wait_until(child: &mut Child, deadline: Instant, timeout: Duration) -> Result<ExitStatus> {
    loop {
        if let Some(status) = child.try_wait().context("waiting for the child")? {
            return Ok(status);
        }
        if Instant::now() >= deadline {
            child
                .kill()
                .context("killing the child after its timeout")?;
            child.wait().context("reaping the killed child")?;
            bail!("did not finish within {timeout:?}");
        }
        thread::sleep(CHILD_POLL);
    }
}

fn receive<T>(rx: &mpsc::Receiver<io::Result<T>>, deadline: Instant, stream: &str) -> Result<T> {
    match rx.recv_timeout(deadline.saturating_duration_since(Instant::now())) {
        Ok(result) => result.with_context(|| format!("passing {stream}")),
        Err(RecvTimeoutError::Timeout) => bail!("{stream} stayed open past the deadline"),
        Err(RecvTimeoutError::Disconnected) => bail!("the {stream} pipe thread stopped"),
    }
}

fn excerpt(stderr: &[u8]) -> String {
    let text = String::from_utf8_lossy(stderr);
    let text = text.trim();
    match text.char_indices().nth(STDERR_SHOWN) {
        Some((end, _)) => format!("{}...", &text[..end]),
        None => text.to_string(),
    }
}

#[cfg(test)]
mod tests {
    use std::os::unix::fs::PermissionsExt;
    use std::sync::atomic::{AtomicUsize, Ordering};

    use super::*;
    use crate::keys::{IdentityKey, IdentityTag, wrap};

    const FAKE_MAGIC: &[u8] = b"XOR";

    struct XorSealer {
        seal_mask: u8,
        open_mask: u8,
        seals: AtomicUsize,
        unseals: AtomicUsize,
    }

    impl XorSealer {
        fn new() -> Arc<Self> {
            Self::lying(0x5a, 0x5a)
        }

        fn lying(seal_mask: u8, open_mask: u8) -> Arc<Self> {
            Arc::new(Self {
                seal_mask,
                open_mask,
                seals: AtomicUsize::new(0),
                unseals: AtomicUsize::new(0),
            })
        }

        fn calls(&self) -> (usize, usize) {
            (
                self.seals.load(Ordering::SeqCst),
                self.unseals.load(Ordering::SeqCst),
            )
        }
    }

    impl CredentialSealer for XorSealer {
        fn seal(&self, plaintext: &[u8]) -> Result<Vec<u8>> {
            self.seals.fetch_add(1, Ordering::SeqCst);
            let mut out = FAKE_MAGIC.to_vec();
            out.extend(plaintext.iter().map(|b| b ^ self.seal_mask));
            Ok(out)
        }

        fn unseal(&self, sealed: &[u8]) -> Result<KeyGuard<Vec<u8>>> {
            self.unseals.fetch_add(1, Ordering::SeqCst);
            let body = sealed
                .strip_prefix(FAKE_MAGIC)
                .ok_or_else(|| anyhow!("not sealed by the fake"))?;
            Ok(KeyGuard::new(
                body.iter().map(|b| b ^ self.open_mask).collect(),
            ))
        }
    }

    struct FailingSealer {
        calls: AtomicUsize,
    }

    impl FailingSealer {
        fn new() -> Arc<Self> {
            Arc::new(Self {
                calls: AtomicUsize::new(0),
            })
        }
    }

    impl CredentialSealer for FailingSealer {
        fn seal(&self, _: &[u8]) -> Result<Vec<u8>> {
            self.calls.fetch_add(1, Ordering::SeqCst);
            bail!("no TPM")
        }

        fn unseal(&self, _: &[u8]) -> Result<KeyGuard<Vec<u8>>> {
            self.calls.fetch_add(1, Ordering::SeqCst);
            bail!("no TPM")
        }
    }

    fn public_parts(keys: &DeviceKeys) -> (String, [u8; 32]) {
        (
            keys.age_recipient().to_string(),
            keys.verifying_key().to_bytes(),
        )
    }

    fn names(dir: &Path) -> Vec<String> {
        let mut names: Vec<String> = fs::read_dir(dir)
            .unwrap()
            .map(|e| e.unwrap().file_name().into_string().unwrap())
            .collect();
        names.sort();
        names
    }

    fn mode(path: &Path) -> u32 {
        fs::metadata(path).unwrap().permissions().mode() & 0o777
    }

    fn write_plain(dir: &Path, keys: &DeviceKeys) {
        fs::write(
            dir.join(DEVICE_KEY_FILE),
            keys.to_secret_bytes().unwrap().expose(),
        )
        .unwrap();
    }

    fn write_sealed(dir: &Path, keys: &DeviceKeys, sealer: &dyn CredentialSealer) {
        let sealed = sealer
            .seal(keys.to_secret_bytes().unwrap().expose())
            .unwrap();
        fs::write(dir.join(SEALED_DEVICE_KEY_FILE), sealed).unwrap();
    }

    #[test]
    fn detection_follows_the_host() {
        enum Candidate {
            Works,
            FailsToSeal,
            OpensOtherBytes,
        }
        let cases = [
            ("env file", Some("file"), true, Candidate::Works, "file", 0),
            (
                "env tpm",
                Some("tpm"),
                false,
                Candidate::FailsToSeal,
                "tpm",
                0,
            ),
            (
                "env bogus probes",
                Some("tmp"),
                true,
                Candidate::Works,
                "tpm",
                1,
            ),
            (
                "env bogus off linux",
                Some("tmp"),
                false,
                Candidate::Works,
                "file",
                0,
            ),
            ("not linux", None, false, Candidate::Works, "file", 0),
            ("probe ok", None, true, Candidate::Works, "tpm", 1),
            (
                "probe fails to seal",
                None,
                true,
                Candidate::FailsToSeal,
                "file",
                1,
            ),
            (
                "probe opens other bytes",
                None,
                true,
                Candidate::OpensOtherBytes,
                "file",
                1,
            ),
        ];
        for (name, env, linux, candidate, expected, expected_seals) in cases {
            let (sealer, seals): (Arc<dyn CredentialSealer>, Box<dyn Fn() -> usize>) =
                match candidate {
                    Candidate::FailsToSeal => {
                        let fake = FailingSealer::new();
                        let counted = fake.clone();
                        (fake, Box::new(move || counted.calls.load(Ordering::SeqCst)))
                    }
                    Candidate::Works | Candidate::OpensOtherBytes => {
                        let fake = match candidate {
                            Candidate::Works => XorSealer::new(),
                            _ => XorSealer::lying(1, 2),
                        };
                        let counted = fake.clone();
                        (fake, Box::new(move || counted.calls().0))
                    }
                };
            let storage = KeyStorage::detect_with(env, linux, sealer);
            assert_eq!(storage.name(), expected, "{name}");
            assert_eq!(seals(), expected_seals, "{name}");
        }
    }

    #[test]
    fn an_existing_sealed_key_keeps_the_sealed_backend_without_probing() {
        let dir = tempfile::tempdir().unwrap();
        fs::write(dir.path().join(SEALED_DEVICE_KEY_FILE), b"sealed").unwrap();
        assert_eq!(KeyStorage::detect_for(dir.path()).name(), "tpm");
    }

    #[test]
    fn systemd_creds_is_user_scoped_unless_root() {
        let encrypt = [
            "--with-key=host+tpm2",
            "--name=second-brain-device-key",
            "encrypt",
            "-",
            "-",
        ];
        let decrypt = [
            "--newline=no",
            "--name=second-brain-device-key",
            "decrypt",
            "-",
            "-",
        ];
        let cases: [(bool, CredsCommand, &[&str]); 2] = [
            (false, CredsCommand::Encrypt, &encrypt),
            (false, CredsCommand::Decrypt, &decrypt),
        ];
        for (is_root, command, tail) in cases {
            let mut user = vec!["--user"];
            user.extend_from_slice(tail);
            assert_eq!(SystemdCreds::with_root(is_root).args(command), user);
            assert_eq!(SystemdCreds::with_root(!is_root).args(command), tail);
        }
    }

    #[test]
    fn sealed_creation_writes_only_a_private_cred_that_loads_back() {
        let dir = tempfile::tempdir().unwrap();
        let sealer = XorSealer::new();
        let storage = KeyStorage::Sealed(sealer.clone());

        let created = create_device_keys(dir.path(), &storage).unwrap();
        assert_eq!(names(dir.path()), [SEALED_DEVICE_KEY_FILE]);
        assert_eq!(mode(&dir.path().join(SEALED_DEVICE_KEY_FILE)), 0o600);
        let loaded = load_device_keys_with(dir.path(), sealer.as_ref())
            .unwrap()
            .unwrap();
        assert_eq!(public_parts(&loaded), public_parts(&created));

        let fresh = tempfile::tempdir().unwrap();
        let store = SqliteStore::in_memory("local".to_string()).unwrap();
        assert!(ensure_device_keys_in(&store, fresh.path(), &storage).unwrap());
        assert_eq!(names(fresh.path()), [SEALED_DEVICE_KEY_FILE]);
        assert!(!ensure_device_keys_in(&store, fresh.path(), &storage).unwrap());
    }

    #[test]
    fn an_existing_plain_key_migrates_to_the_sealed_file() {
        let dir = tempfile::tempdir().unwrap();
        let store = SqliteStore::in_memory("local".to_string()).unwrap();
        let (original, _) = DeviceKeys::load_or_create(&dir.path().join(DEVICE_KEY_FILE)).unwrap();
        let sealer = XorSealer::new();

        let storage = KeyStorage::Sealed(sealer.clone());
        assert!(!ensure_device_keys_in(&store, dir.path(), &storage).unwrap());
        assert_eq!(names(dir.path()), [SEALED_DEVICE_KEY_FILE]);
        assert_eq!(mode(&dir.path().join(SEALED_DEVICE_KEY_FILE)), 0o600);
        assert_eq!(sealer.calls(), (1, 1));
        let loaded = load_device_keys_with(dir.path(), sealer.as_ref())
            .unwrap()
            .unwrap();
        assert_eq!(public_parts(&loaded), public_parts(&original));
    }

    #[test]
    fn a_migration_that_does_not_open_keeps_the_plain_key() {
        let dir = tempfile::tempdir().unwrap();
        let store = SqliteStore::in_memory("local".to_string()).unwrap();
        let (original, _) = DeviceKeys::load_or_create(&dir.path().join(DEVICE_KEY_FILE)).unwrap();

        let storage = KeyStorage::Sealed(XorSealer::lying(1, 2));
        assert!(!ensure_device_keys_in(&store, dir.path(), &storage).unwrap());
        assert_eq!(names(dir.path()), [DEVICE_KEY_FILE]);
        let loaded = load_device_keys(dir.path()).unwrap().unwrap();
        assert_eq!(public_parts(&loaded), public_parts(&original));
    }

    #[test]
    fn an_unseal_failure_is_an_error_that_creates_nothing() {
        let dir = tempfile::tempdir().unwrap();
        let store = SqliteStore::in_memory("local".to_string()).unwrap();
        write_sealed(
            dir.path(),
            &DeviceKeys::generate().unwrap(),
            XorSealer::new().as_ref(),
        );
        let failing = FailingSealer::new();

        let err = format!(
            "{:#}",
            load_device_keys_with(dir.path(), failing.as_ref()).unwrap_err()
        );
        assert!(err.contains(SEALED_DEVICE_KEY_FILE), "{err}");
        assert!(err.contains("hardware that sealed it"), "{err}");

        let storage = KeyStorage::Sealed(failing);
        assert!(ensure_device_keys_in(&store, dir.path(), &storage).is_err());
        assert_eq!(names(dir.path()), [SEALED_DEVICE_KEY_FILE]);
    }

    #[test]
    fn both_files_with_the_same_keys_drop_the_plain_copy() {
        let dir = tempfile::tempdir().unwrap();
        let keys = DeviceKeys::generate().unwrap();
        let sealer = XorSealer::new();
        write_sealed(dir.path(), &keys, sealer.as_ref());
        write_plain(dir.path(), &keys);

        let loaded = load_device_keys_with(dir.path(), sealer.as_ref())
            .unwrap()
            .unwrap();
        assert_eq!(public_parts(&loaded), public_parts(&keys));
        assert_eq!(names(dir.path()), [SEALED_DEVICE_KEY_FILE]);
    }

    #[test]
    fn a_plain_key_beside_a_sealed_copy_that_does_not_open_is_used() {
        let dir = tempfile::tempdir().unwrap();
        let keys = DeviceKeys::generate().unwrap();
        write_sealed(dir.path(), &keys, XorSealer::new().as_ref());
        write_plain(dir.path(), &keys);

        let loaded = load_device_keys_with(dir.path(), FailingSealer::new().as_ref())
            .unwrap()
            .unwrap();
        assert_eq!(public_parts(&loaded), public_parts(&keys));
        assert_eq!(names(dir.path()), [DEVICE_KEY_FILE, SEALED_DEVICE_KEY_FILE]);
    }

    #[test]
    fn both_files_with_different_keys_are_refused() {
        let dir = tempfile::tempdir().unwrap();
        let sealer = XorSealer::new();
        write_sealed(
            dir.path(),
            &DeviceKeys::generate().unwrap(),
            sealer.as_ref(),
        );
        write_plain(dir.path(), &DeviceKeys::generate().unwrap());

        let err = format!(
            "{:#}",
            load_device_keys_with(dir.path(), sealer.as_ref()).unwrap_err()
        );
        assert!(err.contains("different device keys"), "{err}");
        assert_eq!(names(dir.path()), [DEVICE_KEY_FILE, SEALED_DEVICE_KEY_FILE]);
    }

    #[test]
    fn file_storage_never_calls_the_sealer() {
        let sealer = XorSealer::new();
        let storage = KeyStorage::detect_with(Some("file"), true, sealer.clone());
        assert_eq!(storage.name(), "file");

        let dir = tempfile::tempdir().unwrap();
        let store = SqliteStore::in_memory("local".to_string()).unwrap();
        assert!(ensure_device_keys_in(&store, dir.path(), &storage).unwrap());
        assert!(!ensure_device_keys_in(&store, dir.path(), &storage).unwrap());
        assert_eq!(names(dir.path()), [DEVICE_KEY_FILE]);
        assert_eq!(mode(&dir.path().join(DEVICE_KEY_FILE)), 0o600);
        assert_eq!(sealer.calls(), (0, 0));
    }

    #[test]
    fn a_second_load_reuses_the_unsealed_secret() {
        let dir = tempfile::tempdir().unwrap();
        let sealer = XorSealer::new();
        write_sealed(
            dir.path(),
            &DeviceKeys::generate().unwrap(),
            sealer.as_ref(),
        );

        let first = load_device_keys_with(dir.path(), sealer.as_ref())
            .unwrap()
            .unwrap();
        assert_eq!(sealer.calls(), (1, 1));
        let second = load_device_keys_with(dir.path(), sealer.as_ref())
            .unwrap()
            .unwrap();
        assert_eq!(sealer.calls(), (1, 1));
        assert_eq!(public_parts(&first), public_parts(&second));
    }

    #[test]
    fn a_lost_sealed_key_is_not_replaced_when_the_store_holds_this_devices_envelope() {
        let dir = tempfile::tempdir().unwrap();
        let store = SqliteStore::in_memory("local".to_string()).unwrap();
        let device = DeviceKeys::generate().unwrap();
        let key = IdentityKey::generate().unwrap();
        let tag = IdentityTag::migrated(&key.key_id());
        let envelope = wrap(&key, 1, &tag, &device.age_recipient(), Some("local".into())).unwrap();
        store.put_envelope(&envelope).unwrap();
        let sealer = XorSealer::new();

        let storage = KeyStorage::Sealed(sealer.clone());
        let err = format!(
            "{:#}",
            ensure_device_keys_in(&store, dir.path(), &storage).unwrap_err()
        );
        assert!(err.contains("re-pair"), "{err}");
        assert!(err.contains(SEALED_DEVICE_KEY_FILE), "{err}");
        assert!(names(dir.path()).is_empty());
        assert_eq!(sealer.calls(), (0, 0));
    }

    #[test]
    fn creating_keys_refuses_a_dir_that_holds_either_key_file() {
        for existing in [DEVICE_KEY_FILE, SEALED_DEVICE_KEY_FILE] {
            let dir = tempfile::tempdir().unwrap();
            fs::write(dir.path().join(existing), b"key").unwrap();
            assert!(has_device_key(dir.path()));
            for storage in [KeyStorage::File, KeyStorage::Sealed(XorSealer::new())] {
                let err = create_device_keys(dir.path(), &storage).unwrap_err();
                assert!(format!("{err:#}").contains("already holds"), "{err:#}");
            }
            assert_eq!(names(dir.path()), [existing]);
        }
        assert!(!has_device_key(tempfile::tempdir().unwrap().path()));
    }

    #[test]
    fn a_bounded_run_passes_stdin_through() {
        let out = run_bounded(
            Path::new("cat"),
            &[],
            b"sealed bytes",
            Duration::from_secs(10),
        )
        .unwrap();
        assert_eq!(out.as_slice(), b"sealed bytes");
    }

    #[test]
    fn a_bounded_run_reports_the_exit_status_and_stderr() {
        let err = run_bounded(
            Path::new("sh"),
            &["-c", "echo no TPM here >&2; exit 3"],
            b"",
            Duration::from_secs(10),
        )
        .unwrap_err();
        let shown = format!("{err:#}");
        assert!(shown.contains("no TPM here"), "{shown}");
        assert!(shown.contains('3'), "{shown}");
    }

    #[test]
    fn a_bounded_run_kills_a_hung_child_at_the_deadline() {
        let started = Instant::now();
        let err = run_bounded(
            Path::new("sh"),
            &["-c", "sleep 5"],
            b"",
            Duration::from_millis(200),
        )
        .unwrap_err();
        assert!(
            started.elapsed() < Duration::from_secs(4),
            "{:?}",
            started.elapsed()
        );
        assert!(format!("{err:#}").contains("did not finish"), "{err:#}");
    }

    #[test]
    fn a_missing_program_is_an_error() {
        let err = run_bounded(
            Path::new("/nonexistent/systemd-creds"),
            &[],
            b"",
            Duration::from_secs(10),
        )
        .unwrap_err();
        assert!(format!("{err:#}").contains("starting"), "{err:#}");
    }

    #[test]
    #[ignore = "seals with the host TPM through systemd-creds"]
    fn the_real_systemd_creds_seals_a_new_key_and_migrates_a_plain_one() {
        let real: Arc<dyn CredentialSealer> = Arc::new(SystemdCreds::for_current_user());
        let storage = KeyStorage::detect_with(None, true, real.clone());
        assert_eq!(
            storage.name(),
            "tpm",
            "systemd-creds cannot seal for this user"
        );

        let fresh = tempfile::tempdir().unwrap();
        let store = SqliteStore::in_memory("local".to_string()).unwrap();
        assert!(ensure_device_keys_in(&store, fresh.path(), &storage).unwrap());
        assert_eq!(names(fresh.path()), [SEALED_DEVICE_KEY_FILE]);
        let sealed = fs::read(fresh.path().join(SEALED_DEVICE_KEY_FILE)).unwrap();
        let opened = DeviceKeys::from_secret_bytes(real.unseal(&sealed).unwrap().expose()).unwrap();
        let loaded = load_device_keys(fresh.path()).unwrap().unwrap();
        assert_eq!(public_parts(&opened), public_parts(&loaded));

        let upgraded = tempfile::tempdir().unwrap();
        let (plain, _) =
            DeviceKeys::load_or_create(&upgraded.path().join(DEVICE_KEY_FILE)).unwrap();
        assert!(!ensure_device_keys_in(&store, upgraded.path(), &storage).unwrap());
        assert_eq!(names(upgraded.path()), [SEALED_DEVICE_KEY_FILE]);
        let sealed = fs::read(upgraded.path().join(SEALED_DEVICE_KEY_FILE)).unwrap();
        let opened = DeviceKeys::from_secret_bytes(real.unseal(&sealed).unwrap().expose()).unwrap();
        assert_eq!(public_parts(&opened), public_parts(&plain));
    }
}