Skip to main content

second_brain_core/keys/
storage.rs

1use std::collections::HashMap;
2use std::env::VarError;
3use std::fmt;
4use std::fs;
5use std::io::{self, ErrorKind, Read, Write};
6use std::path::{Path, PathBuf};
7use std::process::{Child, Command, ExitStatus, Stdio};
8use std::sync::mpsc::{self, RecvTimeoutError};
9use std::sync::{Arc, Mutex, MutexGuard, OnceLock, PoisonError};
10use std::thread;
11use std::time::{Duration, Instant};
12
13use anyhow::{Context, Result, anyhow, bail, ensure};
14use sha2::{Digest, Sha256};
15use zeroize::Zeroizing;
16
17use super::device::{create_private_dir, install_if_absent, sync_dir};
18use super::hardware::{HardwareSource, SystemHardware, write_binding};
19use super::store_key::replace_private_file;
20use super::{DEVICE_KEY_FILE, DeviceKeys, KeyGuard};
21use crate::sqlite_store::SqliteStore;
22
23pub const SEALED_DEVICE_KEY_FILE: &str = "device.key.cred";
24pub const KEY_STORE_ENV: &str = "SECOND_BRAIN_DEVICE_KEY_STORE";
25
26const CREDENTIAL_NAME_ARG: &str = "--name=second-brain-device-key";
27const CREDS_TIMEOUT: Duration = Duration::from_secs(30);
28const CHILD_POLL: Duration = Duration::from_millis(10);
29const PROBE_LEN: usize = 32;
30const STDERR_SHOWN: usize = 400;
31
32/// Seals secrets so that only this machine can open them again.
33pub trait CredentialSealer: Send + Sync {
34    fn seal(&self, plaintext: &[u8]) -> Result<Vec<u8>>;
35    fn unseal(&self, sealed: &[u8]) -> Result<KeyGuard<Vec<u8>>>;
36}
37
38#[derive(Clone, Copy, Debug, PartialEq, Eq)]
39enum CredsCommand {
40    Encrypt,
41    Decrypt,
42}
43
44/// Seals with `systemd-creds` under the host key and the TPM, scoped to the
45/// calling user unless it runs as root. Each call is killed after 30 s.
46#[derive(Clone, Debug)]
47pub struct SystemdCreds {
48    program: PathBuf,
49    user_scope: bool,
50    timeout: Duration,
51}
52
53impl SystemdCreds {
54    pub fn for_current_user() -> Self {
55        Self::with_root(running_as_root())
56    }
57
58    fn with_root(is_root: bool) -> Self {
59        Self {
60            program: PathBuf::from("systemd-creds"),
61            user_scope: !is_root,
62            timeout: CREDS_TIMEOUT,
63        }
64    }
65
66    fn args(&self, command: CredsCommand) -> Vec<&'static str> {
67        let mut args = Vec::with_capacity(6);
68        if self.user_scope {
69            args.push("--user");
70        }
71        match command {
72            CredsCommand::Encrypt => args.extend([
73                "--with-key=host+tpm2",
74                CREDENTIAL_NAME_ARG,
75                "encrypt",
76                "-",
77                "-",
78            ]),
79            CredsCommand::Decrypt => {
80                args.extend(["--newline=no", CREDENTIAL_NAME_ARG, "decrypt", "-", "-"])
81            }
82        }
83        args
84    }
85}
86
87impl CredentialSealer for SystemdCreds {
88    fn seal(&self, plaintext: &[u8]) -> Result<Vec<u8>> {
89        let sealed = run_bounded(
90            &self.program,
91            &self.args(CredsCommand::Encrypt),
92            plaintext,
93            self.timeout,
94        )?;
95        if sealed.is_empty() {
96            bail!("{} encrypt wrote nothing", self.program.display());
97        }
98        Ok(sealed.to_vec())
99    }
100
101    fn unseal(&self, sealed: &[u8]) -> Result<KeyGuard<Vec<u8>>> {
102        let mut plaintext = run_bounded(
103            &self.program,
104            &self.args(CredsCommand::Decrypt),
105            sealed,
106            self.timeout,
107        )?;
108        Ok(KeyGuard::new(std::mem::take(&mut *plaintext)))
109    }
110}
111
112#[cfg(unix)]
113fn running_as_root() -> bool {
114    unsafe { libc::geteuid() == 0 }
115}
116
117#[cfg(not(unix))]
118fn running_as_root() -> bool {
119    false
120}
121
122#[derive(Clone)]
123#[non_exhaustive]
124pub enum KeyStorage {
125    File,
126    Sealed(Arc<dyn CredentialSealer>),
127}
128
129impl fmt::Debug for KeyStorage {
130    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
131        f.write_str(self.name())
132    }
133}
134
135impl KeyStorage {
136    /// Picks the backend for creating keys: `KEY_STORE_ENV` when set to
137    /// "file" or "tpm", otherwise sealed when a systemd-creds round trip
138    /// works on this Linux host. Probes by running systemd-creds.
139    pub fn detect() -> Self {
140        let env = match std::env::var(KEY_STORE_ENV) {
141            Ok(value) => Some(value),
142            Err(VarError::NotPresent) => None,
143            Err(VarError::NotUnicode(raw)) => {
144                tracing::warn!(
145                    "ignoring {KEY_STORE_ENV}={}; expected \"file\" or \"tpm\"",
146                    raw.to_string_lossy()
147                );
148                None
149            }
150        };
151        Self::detect_with(
152            env.as_deref(),
153            cfg!(target_os = "linux"),
154            Arc::new(SystemdCreds::for_current_user()),
155        )
156    }
157
158    /// Like `detect`, but a data dir that already holds a sealed key keeps
159    /// the sealed backend without probing.
160    pub fn detect_for(data_dir: &Path) -> Self {
161        if data_dir.join(SEALED_DEVICE_KEY_FILE).exists() {
162            return Self::Sealed(Arc::new(SystemdCreds::for_current_user()));
163        }
164        Self::detect()
165    }
166
167    pub fn detect_with(
168        env: Option<&str>,
169        linux: bool,
170        candidate: Arc<dyn CredentialSealer>,
171    ) -> Self {
172        match env {
173            Some("file") => return Self::File,
174            Some("tpm") => return Self::Sealed(candidate),
175            Some(other) => {
176                tracing::warn!("ignoring {KEY_STORE_ENV}={other:?}; expected \"file\" or \"tpm\"")
177            }
178            None => {}
179        }
180        if !linux {
181            tracing::info!(
182                "keeping the device key in a file: sealing needs systemd-creds on Linux"
183            );
184            return Self::File;
185        }
186        match probe(candidate.as_ref()) {
187            Ok(()) => Self::Sealed(candidate),
188            Err(e) => {
189                tracing::info!(
190                    "keeping the device key in a file: systemd-creds cannot seal it here: {e:#}"
191                );
192                Self::File
193            }
194        }
195    }
196
197    pub fn name(&self) -> &'static str {
198        match self {
199            Self::File => "file",
200            Self::Sealed(_) => "tpm",
201        }
202    }
203
204    fn key_file(&self) -> &'static str {
205        match self {
206            Self::File => DEVICE_KEY_FILE,
207            Self::Sealed(_) => SEALED_DEVICE_KEY_FILE,
208        }
209    }
210}
211
212fn probe(sealer: &dyn CredentialSealer) -> Result<()> {
213    let sample = KeyGuard::<[u8; PROBE_LEN]>::random()?;
214    let sealed = sealer.seal(sample.expose()).context("sealing a probe")?;
215    let opened = sealer.unseal(&sealed).context("unsealing a probe")?;
216    if opened.expose().as_slice() != sample.expose().as_slice() {
217        bail!("an unsealed probe came back different");
218    }
219    Ok(())
220}
221
222/// Loads this device's keys from whichever key file `data_dir` holds,
223/// unsealing `device.key.cred` with systemd-creds. Never probes or creates.
224pub fn load_device_keys(data_dir: &Path) -> Result<Option<DeviceKeys>> {
225    load_device_keys_with(data_dir, &SystemdCreds::for_current_user())
226}
227
228pub fn load_device_keys_in(data_dir: &Path, storage: &KeyStorage) -> Result<Option<DeviceKeys>> {
229    match storage {
230        KeyStorage::Sealed(sealer) => load_device_keys_with(data_dir, sealer.as_ref()),
231        KeyStorage::File => load_device_keys(data_dir),
232    }
233}
234
235/// When both key files exist, the plain file is left from an interrupted
236/// migration: it is removed when both hold the same keys, used when the
237/// sealed copy does not open, and an error when they differ.
238pub fn load_device_keys_with(
239    data_dir: &Path,
240    sealer: &dyn CredentialSealer,
241) -> Result<Option<DeviceKeys>> {
242    let sealed_path = data_dir.join(SEALED_DEVICE_KEY_FILE);
243    let plain_path = data_dir.join(DEVICE_KEY_FILE);
244    let Some(sealed) = read_if_present(&sealed_path)? else {
245        return DeviceKeys::load(&plain_path);
246    };
247    let keys = match open_sealed(&sealed_path, &sealed, sealer) {
248        Ok(keys) => keys,
249        Err(e) => {
250            let Some(plain) = DeviceKeys::load(&plain_path)? else {
251                return Err(e);
252            };
253            tracing::warn!(
254                "using {} because the sealed copy beside it does not open: {e:#}",
255                plain_path.display()
256            );
257            return Ok(Some(plain));
258        }
259    };
260    if let Some(plain) = DeviceKeys::load(&plain_path)? {
261        if !same_keys(&keys, &plain)? {
262            bail!(
263                "{} and {} hold different device keys; refusing to pick one",
264                sealed_path.display(),
265                plain_path.display()
266            );
267        }
268        remove_plain_copy(data_dir, &plain_path)?;
269    }
270    Ok(Some(keys))
271}
272
273/// Loads this device's keys, generating them in `storage` on first start
274/// and moving an existing plain key into sealed storage. Keys are never
275/// regenerated once the store holds an envelope or a signed record for this
276/// device. Returns true when the keys were generated by this call.
277pub fn ensure_device_keys_in(
278    store: &SqliteStore,
279    data_dir: &Path,
280    storage: &KeyStorage,
281) -> Result<bool> {
282    if let Some(keys) = load_device_keys_in(data_dir, storage)? {
283        if let KeyStorage::Sealed(sealer) = storage
284            && !data_dir.join(SEALED_DEVICE_KEY_FILE).exists()
285            && let Err(e) = migrate_to_sealed(data_dir, &keys, sealer.as_ref())
286        {
287            tracing::warn!(
288                "keeping {}: {e:#}",
289                data_dir.join(DEVICE_KEY_FILE).display()
290            );
291        }
292        return Ok(false);
293    }
294    let machine_id = store.machine_id();
295    if store.device_record(machine_id)?.is_some()
296        || !store.envelopes_for_machine(machine_id)?.is_empty()
297    {
298        bail!(
299            "{} is missing but this store holds keys issued to this device; \
300             restore the file from a backup or re-pair this device",
301            data_dir.join(storage.key_file()).display()
302        );
303    }
304    let created = create_in(data_dir, storage, &SystemHardware)?.is_some();
305    if created {
306        tracing::info!(
307            "generated device keys in {} ({})",
308            data_dir.display(),
309            storage.name()
310        );
311    }
312    Ok(created)
313}
314
315pub fn create_device_keys(data_dir: &Path, storage: &KeyStorage) -> Result<DeviceKeys> {
316    create_device_keys_with(data_dir, storage, &SystemHardware)
317}
318
319pub(super) fn create_device_keys_with(
320    data_dir: &Path,
321    storage: &KeyStorage,
322    source: &dyn HardwareSource,
323) -> Result<DeviceKeys> {
324    let occupied = || anyhow!("{} already holds a device key", data_dir.display());
325    if has_device_key(data_dir) {
326        return Err(occupied());
327    }
328    create_in(data_dir, storage, source)?.ok_or_else(occupied)
329}
330
331/// Replaces the device key in the form `data_dir` keeps it, so the next
332/// load opens `keys`. A sealed copy beside a plain one is the copy the load
333/// path could not open and fell back from, so it goes first: a crash
334/// between the two steps leaves the plain key that opened the store.
335pub(super) fn replace_device_keys(
336    data_dir: &Path,
337    storage: &KeyStorage,
338    keys: &DeviceKeys,
339) -> Result<()> {
340    let sealed_path = data_dir.join(SEALED_DEVICE_KEY_FILE);
341    let plain_path = data_dir.join(DEVICE_KEY_FILE);
342    let secret = keys.to_secret_bytes()?;
343    if plain_path.exists() {
344        if sealed_path.exists() {
345            remove_unopened_sealed_copy(data_dir, &sealed_path)?;
346        }
347        return replace_private_file(data_dir, DEVICE_KEY_FILE, secret.expose());
348    }
349    if !sealed_path.exists() {
350        return replace_private_file(data_dir, DEVICE_KEY_FILE, secret.expose());
351    }
352    let sealer: Arc<dyn CredentialSealer> = match storage {
353        KeyStorage::Sealed(sealer) => sealer.clone(),
354        KeyStorage::File => Arc::new(SystemdCreds::for_current_user()),
355    };
356    let sealed = sealer
357        .seal(secret.expose())
358        .context("sealing the new device key")?;
359    let opened = verify_sealed(sealer.as_ref(), &sealed, &secret)?;
360    replace_private_file(data_dir, SEALED_DEVICE_KEY_FILE, &sealed)?;
361    cache().insert(digest(&sealed), opened);
362    Ok(())
363}
364
365fn remove_unopened_sealed_copy(data_dir: &Path, path: &Path) -> Result<()> {
366    fs::remove_file(path).with_context(|| format!("removing {}", path.display()))?;
367    tracing::info!(
368        "removed {}, which does not open here, before replacing the device key",
369        path.display()
370    );
371    sync_dir(data_dir)
372}
373
374fn verify_sealed(
375    sealer: &dyn CredentialSealer,
376    sealed: &[u8],
377    secret: &KeyGuard<Vec<u8>>,
378) -> Result<KeyGuard<Vec<u8>>> {
379    let opened = sealer
380        .unseal(sealed)
381        .context("unsealing the new sealed device key")?;
382    ensure!(
383        opened.expose() == secret.expose(),
384        "the new sealed device key unsealed to other bytes"
385    );
386    Ok(opened)
387}
388
389pub fn has_device_key(data_dir: &Path) -> bool {
390    data_dir.join(DEVICE_KEY_FILE).exists() || data_dir.join(SEALED_DEVICE_KEY_FILE).exists()
391}
392
393fn create_in(
394    data_dir: &Path,
395    storage: &KeyStorage,
396    source: &dyn HardwareSource,
397) -> Result<Option<DeviceKeys>> {
398    create_private_dir(data_dir)?;
399    let keys = DeviceKeys::generate()?;
400    let installed = match storage {
401        KeyStorage::File => {
402            let secret = keys.to_secret_bytes()?;
403            install_if_absent(data_dir, &data_dir.join(DEVICE_KEY_FILE), secret.expose())?
404        }
405        KeyStorage::Sealed(sealer) => seal_into(data_dir, &keys, sealer.as_ref())?,
406    };
407    if installed {
408        bind_to_hardware(data_dir, source);
409    }
410    Ok(installed.then_some(keys))
411}
412
413/// A binding that fails to write is recorded at the next start instead.
414fn bind_to_hardware(data_dir: &Path, source: &dyn HardwareSource) {
415    if let Err(e) = write_binding(data_dir, &source.read(data_dir)) {
416        tracing::warn!("cannot record the hardware the device keys were made on: {e:#}");
417    }
418}
419
420fn migrate_to_sealed(
421    data_dir: &Path,
422    keys: &DeviceKeys,
423    sealer: &dyn CredentialSealer,
424) -> Result<()> {
425    if seal_into(data_dir, keys, sealer)? {
426        remove_plain_copy(data_dir, &data_dir.join(DEVICE_KEY_FILE))?;
427    }
428    Ok(())
429}
430
431/// Installs the sealed key only if absent, and keeps it only once it
432/// verifiably unseals to the same secret.
433fn seal_into(data_dir: &Path, keys: &DeviceKeys, sealer: &dyn CredentialSealer) -> Result<bool> {
434    let path = data_dir.join(SEALED_DEVICE_KEY_FILE);
435    let secret = keys.to_secret_bytes()?;
436    let sealed = sealer
437        .seal(secret.expose())
438        .context("sealing the device key")?;
439    if !install_if_absent(data_dir, &path, &sealed)? {
440        return Ok(false);
441    }
442    match verify_sealed(sealer, &sealed, &secret) {
443        Ok(opened) => {
444            cache().insert(digest(&sealed), opened);
445            tracing::info!("sealed the device key into {}", path.display());
446            Ok(true)
447        }
448        Err(e) => Err(remove_unverified(data_dir, &path, e)),
449    }
450}
451
452fn remove_unverified(data_dir: &Path, path: &Path, error: anyhow::Error) -> anyhow::Error {
453    match fs::remove_file(path)
454        .map_err(anyhow::Error::from)
455        .and_then(|()| sync_dir(data_dir))
456    {
457        Ok(()) => error,
458        Err(e) => error.context(format!("also failed to remove {}: {e:#}", path.display())),
459    }
460}
461
462fn remove_plain_copy(data_dir: &Path, path: &Path) -> Result<()> {
463    match fs::remove_file(path) {
464        Ok(()) => tracing::info!(
465            "removed {} now that the device key is sealed",
466            path.display()
467        ),
468        Err(e) if e.kind() == ErrorKind::NotFound => {}
469        Err(e) => return Err(e).with_context(|| format!("removing {}", path.display())),
470    }
471    sync_dir(data_dir)
472}
473
474fn read_if_present(path: &Path) -> Result<Option<Vec<u8>>> {
475    match fs::read(path) {
476        Ok(bytes) => Ok(Some(bytes)),
477        Err(e) if e.kind() == ErrorKind::NotFound => Ok(None),
478        Err(e) => Err(e).with_context(|| format!("reading sealed device key {}", path.display())),
479    }
480}
481
482fn open_sealed(path: &Path, sealed: &[u8], sealer: &dyn CredentialSealer) -> Result<DeviceKeys> {
483    let corrupt = || format!("sealed device key {} is corrupt", path.display());
484    let digest = digest(sealed);
485    if let Some(secret) = cache().get(&digest) {
486        return DeviceKeys::from_secret_bytes(secret.expose()).with_context(corrupt);
487    }
488    let secret = sealer.unseal(sealed).with_context(|| {
489        format!(
490            "cannot unseal {}; a sealed device key opens only on the hardware that sealed it",
491            path.display()
492        )
493    })?;
494    let keys = DeviceKeys::from_secret_bytes(secret.expose()).with_context(corrupt)?;
495    cache().insert(digest, secret);
496    Ok(keys)
497}
498
499fn same_keys(a: &DeviceKeys, b: &DeviceKeys) -> Result<bool> {
500    Ok(a.to_secret_bytes()?.expose() == b.to_secret_bytes()?.expose())
501}
502
503fn digest(sealed: &[u8]) -> [u8; 32] {
504    Sha256::digest(sealed).into()
505}
506
507type UnsealedCache = HashMap<[u8; 32], KeyGuard<Vec<u8>>>;
508
509fn cache() -> MutexGuard<'static, UnsealedCache> {
510    static UNSEALED: OnceLock<Mutex<UnsealedCache>> = OnceLock::new();
511    UNSEALED
512        .get_or_init(Mutex::default)
513        .lock()
514        .unwrap_or_else(PoisonError::into_inner)
515}
516
517pub(super) fn run_bounded(
518    program: &Path,
519    args: &[&str],
520    input: &[u8],
521    timeout: Duration,
522) -> Result<Zeroizing<Vec<u8>>> {
523    let shown = || format!("{} {}", program.display(), args.join(" "));
524    let deadline = Instant::now() + timeout;
525    let mut child = Command::new(program)
526        .args(args)
527        .stdin(Stdio::piped())
528        .stdout(Stdio::piped())
529        .stderr(Stdio::piped())
530        .spawn()
531        .with_context(|| format!("starting {}", shown()))?;
532    let (Some(stdin), Some(stdout), Some(stderr)) =
533        (child.stdin.take(), child.stdout.take(), child.stderr.take())
534    else {
535        return Err(anyhow!("{} started without pipes", shown()));
536    };
537    let written = write_in_background(stdin, Zeroizing::new(input.to_vec()));
538    let output = read_in_background(stdout);
539    let errors = read_in_background(stderr);
540    let status = wait_until(&mut child, deadline, timeout).with_context(shown)?;
541    let errors = receive(&errors, deadline, "stderr").with_context(shown)?;
542    if !status.success() {
543        bail!("{} exited with {status}: {}", shown(), excerpt(&errors));
544    }
545    receive(&written, deadline, "stdin").with_context(shown)?;
546    receive(&output, deadline, "stdout").with_context(shown)
547}
548
549fn write_in_background(
550    mut sink: impl Write + Send + 'static,
551    input: Zeroizing<Vec<u8>>,
552) -> mpsc::Receiver<io::Result<()>> {
553    let (tx, rx) = mpsc::channel();
554    thread::spawn(move || {
555        let result = sink.write_all(&input);
556        drop(sink);
557        tx.send(result).ok();
558    });
559    rx
560}
561
562fn read_in_background(
563    mut source: impl Read + Send + 'static,
564) -> mpsc::Receiver<io::Result<Zeroizing<Vec<u8>>>> {
565    let (tx, rx) = mpsc::channel();
566    thread::spawn(move || {
567        let mut buf = Zeroizing::new(Vec::with_capacity(4096));
568        tx.send(source.read_to_end(&mut buf).map(|_| buf)).ok();
569    });
570    rx
571}
572
573fn wait_until(child: &mut Child, deadline: Instant, timeout: Duration) -> Result<ExitStatus> {
574    loop {
575        if let Some(status) = child.try_wait().context("waiting for the child")? {
576            return Ok(status);
577        }
578        if Instant::now() >= deadline {
579            child
580                .kill()
581                .context("killing the child after its timeout")?;
582            child.wait().context("reaping the killed child")?;
583            bail!("did not finish within {timeout:?}");
584        }
585        thread::sleep(CHILD_POLL);
586    }
587}
588
589fn receive<T>(rx: &mpsc::Receiver<io::Result<T>>, deadline: Instant, stream: &str) -> Result<T> {
590    match rx.recv_timeout(deadline.saturating_duration_since(Instant::now())) {
591        Ok(result) => result.with_context(|| format!("passing {stream}")),
592        Err(RecvTimeoutError::Timeout) => bail!("{stream} stayed open past the deadline"),
593        Err(RecvTimeoutError::Disconnected) => bail!("the {stream} pipe thread stopped"),
594    }
595}
596
597fn excerpt(stderr: &[u8]) -> String {
598    let text = String::from_utf8_lossy(stderr);
599    let text = text.trim();
600    match text.char_indices().nth(STDERR_SHOWN) {
601        Some((end, _)) => format!("{}...", &text[..end]),
602        None => text.to_string(),
603    }
604}
605
606#[cfg(test)]
607mod tests {
608    use std::os::unix::fs::PermissionsExt;
609    use std::sync::atomic::{AtomicUsize, Ordering};
610
611    use super::*;
612    use crate::keys::{IdentityKey, IdentityTag, wrap};
613
614    const FAKE_MAGIC: &[u8] = b"XOR";
615
616    struct XorSealer {
617        seal_mask: u8,
618        open_mask: u8,
619        seals: AtomicUsize,
620        unseals: AtomicUsize,
621    }
622
623    impl XorSealer {
624        fn new() -> Arc<Self> {
625            Self::lying(0x5a, 0x5a)
626        }
627
628        fn lying(seal_mask: u8, open_mask: u8) -> Arc<Self> {
629            Arc::new(Self {
630                seal_mask,
631                open_mask,
632                seals: AtomicUsize::new(0),
633                unseals: AtomicUsize::new(0),
634            })
635        }
636
637        fn calls(&self) -> (usize, usize) {
638            (
639                self.seals.load(Ordering::SeqCst),
640                self.unseals.load(Ordering::SeqCst),
641            )
642        }
643    }
644
645    impl CredentialSealer for XorSealer {
646        fn seal(&self, plaintext: &[u8]) -> Result<Vec<u8>> {
647            self.seals.fetch_add(1, Ordering::SeqCst);
648            let mut out = FAKE_MAGIC.to_vec();
649            out.extend(plaintext.iter().map(|b| b ^ self.seal_mask));
650            Ok(out)
651        }
652
653        fn unseal(&self, sealed: &[u8]) -> Result<KeyGuard<Vec<u8>>> {
654            self.unseals.fetch_add(1, Ordering::SeqCst);
655            let body = sealed
656                .strip_prefix(FAKE_MAGIC)
657                .ok_or_else(|| anyhow!("not sealed by the fake"))?;
658            Ok(KeyGuard::new(
659                body.iter().map(|b| b ^ self.open_mask).collect(),
660            ))
661        }
662    }
663
664    struct FailingSealer {
665        calls: AtomicUsize,
666    }
667
668    impl FailingSealer {
669        fn new() -> Arc<Self> {
670            Arc::new(Self {
671                calls: AtomicUsize::new(0),
672            })
673        }
674    }
675
676    impl CredentialSealer for FailingSealer {
677        fn seal(&self, _: &[u8]) -> Result<Vec<u8>> {
678            self.calls.fetch_add(1, Ordering::SeqCst);
679            bail!("no TPM")
680        }
681
682        fn unseal(&self, _: &[u8]) -> Result<KeyGuard<Vec<u8>>> {
683            self.calls.fetch_add(1, Ordering::SeqCst);
684            bail!("no TPM")
685        }
686    }
687
688    fn public_parts(keys: &DeviceKeys) -> (String, [u8; 32]) {
689        (
690            keys.age_recipient().to_string(),
691            keys.verifying_key().to_bytes(),
692        )
693    }
694
695    fn names(dir: &Path) -> Vec<String> {
696        let mut names: Vec<String> = fs::read_dir(dir)
697            .unwrap()
698            .map(|e| e.unwrap().file_name().into_string().unwrap())
699            .collect();
700        names.sort();
701        names
702    }
703
704    fn mode(path: &Path) -> u32 {
705        fs::metadata(path).unwrap().permissions().mode() & 0o777
706    }
707
708    fn write_plain(dir: &Path, keys: &DeviceKeys) {
709        fs::write(
710            dir.join(DEVICE_KEY_FILE),
711            keys.to_secret_bytes().unwrap().expose(),
712        )
713        .unwrap();
714    }
715
716    fn write_sealed(dir: &Path, keys: &DeviceKeys, sealer: &dyn CredentialSealer) {
717        let sealed = sealer
718            .seal(keys.to_secret_bytes().unwrap().expose())
719            .unwrap();
720        fs::write(dir.join(SEALED_DEVICE_KEY_FILE), sealed).unwrap();
721    }
722
723    #[test]
724    fn detection_follows_the_host() {
725        enum Candidate {
726            Works,
727            FailsToSeal,
728            OpensOtherBytes,
729        }
730        let cases = [
731            ("env file", Some("file"), true, Candidate::Works, "file", 0),
732            (
733                "env tpm",
734                Some("tpm"),
735                false,
736                Candidate::FailsToSeal,
737                "tpm",
738                0,
739            ),
740            (
741                "env bogus probes",
742                Some("tmp"),
743                true,
744                Candidate::Works,
745                "tpm",
746                1,
747            ),
748            (
749                "env bogus off linux",
750                Some("tmp"),
751                false,
752                Candidate::Works,
753                "file",
754                0,
755            ),
756            ("not linux", None, false, Candidate::Works, "file", 0),
757            ("probe ok", None, true, Candidate::Works, "tpm", 1),
758            (
759                "probe fails to seal",
760                None,
761                true,
762                Candidate::FailsToSeal,
763                "file",
764                1,
765            ),
766            (
767                "probe opens other bytes",
768                None,
769                true,
770                Candidate::OpensOtherBytes,
771                "file",
772                1,
773            ),
774        ];
775        for (name, env, linux, candidate, expected, expected_seals) in cases {
776            let (sealer, seals): (Arc<dyn CredentialSealer>, Box<dyn Fn() -> usize>) =
777                match candidate {
778                    Candidate::FailsToSeal => {
779                        let fake = FailingSealer::new();
780                        let counted = fake.clone();
781                        (fake, Box::new(move || counted.calls.load(Ordering::SeqCst)))
782                    }
783                    Candidate::Works | Candidate::OpensOtherBytes => {
784                        let fake = match candidate {
785                            Candidate::Works => XorSealer::new(),
786                            _ => XorSealer::lying(1, 2),
787                        };
788                        let counted = fake.clone();
789                        (fake, Box::new(move || counted.calls().0))
790                    }
791                };
792            let storage = KeyStorage::detect_with(env, linux, sealer);
793            assert_eq!(storage.name(), expected, "{name}");
794            assert_eq!(seals(), expected_seals, "{name}");
795        }
796    }
797
798    #[test]
799    fn an_existing_sealed_key_keeps_the_sealed_backend_without_probing() {
800        let dir = tempfile::tempdir().unwrap();
801        fs::write(dir.path().join(SEALED_DEVICE_KEY_FILE), b"sealed").unwrap();
802        assert_eq!(KeyStorage::detect_for(dir.path()).name(), "tpm");
803    }
804
805    #[test]
806    fn systemd_creds_is_user_scoped_unless_root() {
807        let encrypt = [
808            "--with-key=host+tpm2",
809            "--name=second-brain-device-key",
810            "encrypt",
811            "-",
812            "-",
813        ];
814        let decrypt = [
815            "--newline=no",
816            "--name=second-brain-device-key",
817            "decrypt",
818            "-",
819            "-",
820        ];
821        let cases: [(bool, CredsCommand, &[&str]); 2] = [
822            (false, CredsCommand::Encrypt, &encrypt),
823            (false, CredsCommand::Decrypt, &decrypt),
824        ];
825        for (is_root, command, tail) in cases {
826            let mut user = vec!["--user"];
827            user.extend_from_slice(tail);
828            assert_eq!(SystemdCreds::with_root(is_root).args(command), user);
829            assert_eq!(SystemdCreds::with_root(!is_root).args(command), tail);
830        }
831    }
832
833    #[test]
834    fn sealed_creation_writes_only_a_private_cred_that_loads_back() {
835        let dir = tempfile::tempdir().unwrap();
836        let sealer = XorSealer::new();
837        let storage = KeyStorage::Sealed(sealer.clone());
838
839        let created = create_device_keys(dir.path(), &storage).unwrap();
840        assert_eq!(names(dir.path()), [SEALED_DEVICE_KEY_FILE]);
841        assert_eq!(mode(&dir.path().join(SEALED_DEVICE_KEY_FILE)), 0o600);
842        let loaded = load_device_keys_with(dir.path(), sealer.as_ref())
843            .unwrap()
844            .unwrap();
845        assert_eq!(public_parts(&loaded), public_parts(&created));
846
847        let fresh = tempfile::tempdir().unwrap();
848        let store = SqliteStore::in_memory("local".to_string()).unwrap();
849        assert!(ensure_device_keys_in(&store, fresh.path(), &storage).unwrap());
850        assert_eq!(names(fresh.path()), [SEALED_DEVICE_KEY_FILE]);
851        assert!(!ensure_device_keys_in(&store, fresh.path(), &storage).unwrap());
852    }
853
854    #[test]
855    fn an_existing_plain_key_migrates_to_the_sealed_file() {
856        let dir = tempfile::tempdir().unwrap();
857        let store = SqliteStore::in_memory("local".to_string()).unwrap();
858        let (original, _) = DeviceKeys::load_or_create(&dir.path().join(DEVICE_KEY_FILE)).unwrap();
859        let sealer = XorSealer::new();
860
861        let storage = KeyStorage::Sealed(sealer.clone());
862        assert!(!ensure_device_keys_in(&store, dir.path(), &storage).unwrap());
863        assert_eq!(names(dir.path()), [SEALED_DEVICE_KEY_FILE]);
864        assert_eq!(mode(&dir.path().join(SEALED_DEVICE_KEY_FILE)), 0o600);
865        assert_eq!(sealer.calls(), (1, 1));
866        let loaded = load_device_keys_with(dir.path(), sealer.as_ref())
867            .unwrap()
868            .unwrap();
869        assert_eq!(public_parts(&loaded), public_parts(&original));
870    }
871
872    #[test]
873    fn a_migration_that_does_not_open_keeps_the_plain_key() {
874        let dir = tempfile::tempdir().unwrap();
875        let store = SqliteStore::in_memory("local".to_string()).unwrap();
876        let (original, _) = DeviceKeys::load_or_create(&dir.path().join(DEVICE_KEY_FILE)).unwrap();
877
878        let storage = KeyStorage::Sealed(XorSealer::lying(1, 2));
879        assert!(!ensure_device_keys_in(&store, dir.path(), &storage).unwrap());
880        assert_eq!(names(dir.path()), [DEVICE_KEY_FILE]);
881        let loaded = load_device_keys(dir.path()).unwrap().unwrap();
882        assert_eq!(public_parts(&loaded), public_parts(&original));
883    }
884
885    #[test]
886    fn an_unseal_failure_is_an_error_that_creates_nothing() {
887        let dir = tempfile::tempdir().unwrap();
888        let store = SqliteStore::in_memory("local".to_string()).unwrap();
889        write_sealed(
890            dir.path(),
891            &DeviceKeys::generate().unwrap(),
892            XorSealer::new().as_ref(),
893        );
894        let failing = FailingSealer::new();
895
896        let err = format!(
897            "{:#}",
898            load_device_keys_with(dir.path(), failing.as_ref()).unwrap_err()
899        );
900        assert!(err.contains(SEALED_DEVICE_KEY_FILE), "{err}");
901        assert!(err.contains("hardware that sealed it"), "{err}");
902
903        let storage = KeyStorage::Sealed(failing);
904        assert!(ensure_device_keys_in(&store, dir.path(), &storage).is_err());
905        assert_eq!(names(dir.path()), [SEALED_DEVICE_KEY_FILE]);
906    }
907
908    #[test]
909    fn both_files_with_the_same_keys_drop_the_plain_copy() {
910        let dir = tempfile::tempdir().unwrap();
911        let keys = DeviceKeys::generate().unwrap();
912        let sealer = XorSealer::new();
913        write_sealed(dir.path(), &keys, sealer.as_ref());
914        write_plain(dir.path(), &keys);
915
916        let loaded = load_device_keys_with(dir.path(), sealer.as_ref())
917            .unwrap()
918            .unwrap();
919        assert_eq!(public_parts(&loaded), public_parts(&keys));
920        assert_eq!(names(dir.path()), [SEALED_DEVICE_KEY_FILE]);
921    }
922
923    #[test]
924    fn a_plain_key_beside_a_sealed_copy_that_does_not_open_is_used() {
925        let dir = tempfile::tempdir().unwrap();
926        let keys = DeviceKeys::generate().unwrap();
927        write_sealed(dir.path(), &keys, XorSealer::new().as_ref());
928        write_plain(dir.path(), &keys);
929
930        let loaded = load_device_keys_with(dir.path(), FailingSealer::new().as_ref())
931            .unwrap()
932            .unwrap();
933        assert_eq!(public_parts(&loaded), public_parts(&keys));
934        assert_eq!(names(dir.path()), [DEVICE_KEY_FILE, SEALED_DEVICE_KEY_FILE]);
935    }
936
937    #[test]
938    fn both_files_with_different_keys_are_refused() {
939        let dir = tempfile::tempdir().unwrap();
940        let sealer = XorSealer::new();
941        write_sealed(
942            dir.path(),
943            &DeviceKeys::generate().unwrap(),
944            sealer.as_ref(),
945        );
946        write_plain(dir.path(), &DeviceKeys::generate().unwrap());
947
948        let err = format!(
949            "{:#}",
950            load_device_keys_with(dir.path(), sealer.as_ref()).unwrap_err()
951        );
952        assert!(err.contains("different device keys"), "{err}");
953        assert_eq!(names(dir.path()), [DEVICE_KEY_FILE, SEALED_DEVICE_KEY_FILE]);
954    }
955
956    #[test]
957    fn file_storage_never_calls_the_sealer() {
958        let sealer = XorSealer::new();
959        let storage = KeyStorage::detect_with(Some("file"), true, sealer.clone());
960        assert_eq!(storage.name(), "file");
961
962        let dir = tempfile::tempdir().unwrap();
963        let store = SqliteStore::in_memory("local".to_string()).unwrap();
964        assert!(ensure_device_keys_in(&store, dir.path(), &storage).unwrap());
965        assert!(!ensure_device_keys_in(&store, dir.path(), &storage).unwrap());
966        assert_eq!(names(dir.path()), [DEVICE_KEY_FILE]);
967        assert_eq!(mode(&dir.path().join(DEVICE_KEY_FILE)), 0o600);
968        assert_eq!(sealer.calls(), (0, 0));
969    }
970
971    #[test]
972    fn a_second_load_reuses_the_unsealed_secret() {
973        let dir = tempfile::tempdir().unwrap();
974        let sealer = XorSealer::new();
975        write_sealed(
976            dir.path(),
977            &DeviceKeys::generate().unwrap(),
978            sealer.as_ref(),
979        );
980
981        let first = load_device_keys_with(dir.path(), sealer.as_ref())
982            .unwrap()
983            .unwrap();
984        assert_eq!(sealer.calls(), (1, 1));
985        let second = load_device_keys_with(dir.path(), sealer.as_ref())
986            .unwrap()
987            .unwrap();
988        assert_eq!(sealer.calls(), (1, 1));
989        assert_eq!(public_parts(&first), public_parts(&second));
990    }
991
992    #[test]
993    fn a_lost_sealed_key_is_not_replaced_when_the_store_holds_this_devices_envelope() {
994        let dir = tempfile::tempdir().unwrap();
995        let store = SqliteStore::in_memory("local".to_string()).unwrap();
996        let device = DeviceKeys::generate().unwrap();
997        let key = IdentityKey::generate().unwrap();
998        let tag = IdentityTag::migrated(&key.key_id());
999        let envelope = wrap(&key, 1, &tag, &device.age_recipient(), Some("local".into())).unwrap();
1000        store.put_envelope(&envelope).unwrap();
1001        let sealer = XorSealer::new();
1002
1003        let storage = KeyStorage::Sealed(sealer.clone());
1004        let err = format!(
1005            "{:#}",
1006            ensure_device_keys_in(&store, dir.path(), &storage).unwrap_err()
1007        );
1008        assert!(err.contains("re-pair"), "{err}");
1009        assert!(err.contains(SEALED_DEVICE_KEY_FILE), "{err}");
1010        assert!(names(dir.path()).is_empty());
1011        assert_eq!(sealer.calls(), (0, 0));
1012    }
1013
1014    #[test]
1015    fn creating_keys_refuses_a_dir_that_holds_either_key_file() {
1016        for existing in [DEVICE_KEY_FILE, SEALED_DEVICE_KEY_FILE] {
1017            let dir = tempfile::tempdir().unwrap();
1018            fs::write(dir.path().join(existing), b"key").unwrap();
1019            assert!(has_device_key(dir.path()));
1020            for storage in [KeyStorage::File, KeyStorage::Sealed(XorSealer::new())] {
1021                let err = create_device_keys(dir.path(), &storage).unwrap_err();
1022                assert!(format!("{err:#}").contains("already holds"), "{err:#}");
1023            }
1024            assert_eq!(names(dir.path()), [existing]);
1025        }
1026        assert!(!has_device_key(tempfile::tempdir().unwrap().path()));
1027    }
1028
1029    #[test]
1030    fn a_bounded_run_passes_stdin_through() {
1031        let out = run_bounded(
1032            Path::new("cat"),
1033            &[],
1034            b"sealed bytes",
1035            Duration::from_secs(10),
1036        )
1037        .unwrap();
1038        assert_eq!(out.as_slice(), b"sealed bytes");
1039    }
1040
1041    #[test]
1042    fn a_bounded_run_reports_the_exit_status_and_stderr() {
1043        let err = run_bounded(
1044            Path::new("sh"),
1045            &["-c", "echo no TPM here >&2; exit 3"],
1046            b"",
1047            Duration::from_secs(10),
1048        )
1049        .unwrap_err();
1050        let shown = format!("{err:#}");
1051        assert!(shown.contains("no TPM here"), "{shown}");
1052        assert!(shown.contains('3'), "{shown}");
1053    }
1054
1055    #[test]
1056    fn a_bounded_run_kills_a_hung_child_at_the_deadline() {
1057        let started = Instant::now();
1058        let err = run_bounded(
1059            Path::new("sh"),
1060            &["-c", "sleep 5"],
1061            b"",
1062            Duration::from_millis(200),
1063        )
1064        .unwrap_err();
1065        assert!(
1066            started.elapsed() < Duration::from_secs(4),
1067            "{:?}",
1068            started.elapsed()
1069        );
1070        assert!(format!("{err:#}").contains("did not finish"), "{err:#}");
1071    }
1072
1073    #[test]
1074    fn a_missing_program_is_an_error() {
1075        let err = run_bounded(
1076            Path::new("/nonexistent/systemd-creds"),
1077            &[],
1078            b"",
1079            Duration::from_secs(10),
1080        )
1081        .unwrap_err();
1082        assert!(format!("{err:#}").contains("starting"), "{err:#}");
1083    }
1084
1085    #[test]
1086    #[ignore = "seals with the host TPM through systemd-creds"]
1087    fn the_real_systemd_creds_seals_a_new_key_and_migrates_a_plain_one() {
1088        let real: Arc<dyn CredentialSealer> = Arc::new(SystemdCreds::for_current_user());
1089        let storage = KeyStorage::detect_with(None, true, real.clone());
1090        assert_eq!(
1091            storage.name(),
1092            "tpm",
1093            "systemd-creds cannot seal for this user"
1094        );
1095
1096        let fresh = tempfile::tempdir().unwrap();
1097        let store = SqliteStore::in_memory("local".to_string()).unwrap();
1098        assert!(ensure_device_keys_in(&store, fresh.path(), &storage).unwrap());
1099        assert_eq!(names(fresh.path()), [SEALED_DEVICE_KEY_FILE]);
1100        let sealed = fs::read(fresh.path().join(SEALED_DEVICE_KEY_FILE)).unwrap();
1101        let opened = DeviceKeys::from_secret_bytes(real.unseal(&sealed).unwrap().expose()).unwrap();
1102        let loaded = load_device_keys(fresh.path()).unwrap().unwrap();
1103        assert_eq!(public_parts(&opened), public_parts(&loaded));
1104
1105        let upgraded = tempfile::tempdir().unwrap();
1106        let (plain, _) =
1107            DeviceKeys::load_or_create(&upgraded.path().join(DEVICE_KEY_FILE)).unwrap();
1108        assert!(!ensure_device_keys_in(&store, upgraded.path(), &storage).unwrap());
1109        assert_eq!(names(upgraded.path()), [SEALED_DEVICE_KEY_FILE]);
1110        let sealed = fs::read(upgraded.path().join(SEALED_DEVICE_KEY_FILE)).unwrap();
1111        let opened = DeviceKeys::from_secret_bytes(real.unseal(&sealed).unwrap().expose()).unwrap();
1112        assert_eq!(public_parts(&opened), public_parts(&plain));
1113    }
1114}