Skip to main content

second_brain_core/keys/
clone_check.rs

1use std::fmt;
2use std::path::Path;
3
4use anyhow::{Context, Result};
5
6use super::hardware::{HardwareId, HardwareSource, SystemHardware, read_binding, write_binding};
7use super::storage::replace_device_keys;
8use super::store_key::write_store_key_to;
9use super::{
10    DEVICE_PUB_FILE, DeviceKeys, KeyStorage, NEXT_STORE_KEY_FILE, STORE_KEY_FILE,
11    load_device_keys_in, publish_device_pub, read_store_key,
12};
13use crate::machine::MachineIdentity;
14use crate::write_queue;
15
16#[derive(Debug, Clone, PartialEq, Eq)]
17#[non_exhaustive]
18pub enum HardwareCheck {
19    /// No device keys yet; they are bound when they are created.
20    NoKeys,
21    Bound,
22    /// The keys predate the binding, so this hardware was recorded now.
23    Recorded,
24    /// No hardware id can be compared here, so the check is off. Never a
25    /// mismatch.
26    Unreadable,
27    /// The data dir was made on other hardware (a clone, or a copy restored
28    /// by hand), so this device now has a new machine id and new device keys
29    /// and has to be paired.
30    Reminted {
31        previous_machine_id: Option<String>,
32        machine_id: String,
33    },
34}
35
36impl HardwareCheck {
37    pub fn name(&self) -> &'static str {
38        match self {
39            Self::NoKeys => "no-keys",
40            Self::Bound => "bound",
41            Self::Recorded => "recorded",
42            Self::Unreadable => "unreadable",
43            Self::Reminted { .. } => "reminted",
44        }
45    }
46}
47
48/// Marks an error from a remint that had begun: the data dir is known to
49/// come from other hardware, so the daemon must not run under the machine
50/// id it carries. The next start redoes the remint.
51#[derive(Debug)]
52pub struct RemintFailed;
53
54impl fmt::Display for RemintFailed {
55    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
56        f.write_str("the device keys were made on other hardware and replacing them failed")
57    }
58}
59
60/// Compares the hardware the device keys in `data_dir` were made on with
61/// this hardware. On a mismatch it mints new device keys, re-wraps the
62/// store key to them and writes a new machine id into `config_dir`; the
63/// daemon must run it before it opens the store or reads the machine id.
64pub fn check_hardware(
65    data_dir: &Path,
66    config_dir: &Path,
67    storage: &KeyStorage,
68) -> Result<HardwareCheck> {
69    check_hardware_with(data_dir, config_dir, storage, &SystemHardware)
70}
71
72pub fn check_hardware_with(
73    data_dir: &Path,
74    config_dir: &Path,
75    storage: &KeyStorage,
76    source: &dyn HardwareSource,
77) -> Result<HardwareCheck> {
78    let Some(device) = load_device_keys_in(data_dir, storage)? else {
79        return Ok(HardwareCheck::NoKeys);
80    };
81    let current = source.read(data_dir);
82    let Some(recorded) = read_binding(data_dir)? else {
83        if current.is_empty() {
84            return Ok(HardwareCheck::Unreadable);
85        }
86        write_binding(data_dir, &current)?;
87        return Ok(HardwareCheck::Recorded);
88    };
89    match recorded.matches(&current) {
90        None => Ok(HardwareCheck::Unreadable),
91        Some(true) => {
92            let refreshed = recorded.refreshed(&current);
93            if refreshed != recorded {
94                write_binding(data_dir, &refreshed)?;
95            }
96            Ok(HardwareCheck::Bound)
97        }
98        Some(false) => {
99            remint(data_dir, config_dir, storage, &device, &current).context(RemintFailed)
100        }
101    }
102}
103
104/// The binding is written last: until it is, every start finds the
105/// mismatch again and redoes the remint from whatever key is in place.
106fn remint(
107    data_dir: &Path,
108    config_dir: &Path,
109    storage: &KeyStorage,
110    device: &DeviceKeys,
111    current: &HardwareId,
112) -> Result<HardwareCheck> {
113    let previous_machine_id = match MachineIdentity::load(config_dir) {
114        Ok(machine) => machine.map(|m| m.id),
115        Err(e) => {
116            tracing::warn!("cannot read the machine id being replaced: {e:#}");
117            None
118        }
119    };
120    swap_device_keys(data_dir, storage, device)?;
121    let machine = MachineIdentity::mint(config_dir)?;
122    write_binding(data_dir, current)?;
123    Ok(HardwareCheck::Reminted {
124        previous_machine_id,
125        machine_id: machine.id,
126    })
127}
128
129/// The store key and queued writes open with the device key on disk after
130/// every step, so a swap cut short anywhere leaves them readable.
131fn swap_device_keys(data_dir: &Path, storage: &KeyStorage, old: &DeviceKeys) -> Result<DeviceKeys> {
132    let fresh = DeviceKeys::generate()?;
133    seal_to_both(data_dir, old, &fresh)?;
134    replace_device_keys(data_dir, storage, &fresh)?;
135    settle_on(data_dir, old, &fresh)?;
136    Ok(fresh)
137}
138
139/// `device.pub` is withdrawn first, so writes queued during the swap stay
140/// plaintext rather than sealed to a key about to go.
141fn seal_to_both(data_dir: &Path, old: &DeviceKeys, fresh: &DeviceKeys) -> Result<()> {
142    match std::fs::remove_file(data_dir.join(DEVICE_PUB_FILE)) {
143        Ok(()) => {}
144        Err(e) if e.kind() == std::io::ErrorKind::NotFound => {}
145        Err(e) => return Err(e).context("withdrawing the device recipient"),
146    }
147    rewrap_store_keys(data_dir, old, &[old, fresh])?;
148    write_queue::reseal_dir(
149        &data_dir.join(write_queue::DIR_NAME),
150        old.age_identity(),
151        &[old.age_recipient(), fresh.age_recipient()],
152    )?;
153    Ok(())
154}
155
156/// The last reseal catches a write sealed to the old `device.pub` by a
157/// writer that read it before it was withdrawn.
158fn settle_on(data_dir: &Path, old: &DeviceKeys, fresh: &DeviceKeys) -> Result<()> {
159    rewrap_store_keys(data_dir, fresh, &[fresh])?;
160    publish_device_pub(data_dir, fresh)?;
161    write_queue::reseal_dir(
162        &data_dir.join(write_queue::DIR_NAME),
163        old.age_identity(),
164        &[fresh.age_recipient()],
165    )?;
166    Ok(())
167}
168
169fn rewrap_store_keys(data_dir: &Path, reader: &DeviceKeys, devices: &[&DeviceKeys]) -> Result<()> {
170    for name in [STORE_KEY_FILE, NEXT_STORE_KEY_FILE] {
171        if let Some(key) = read_store_key(&data_dir.join(name), reader)? {
172            write_store_key_to(data_dir, name, &key, devices)?;
173        }
174    }
175    Ok(())
176}
177
178#[cfg(test)]
179mod tests {
180    use std::fs;
181    use std::sync::Arc;
182
183    use anyhow::anyhow;
184
185    use super::*;
186    use crate::keys::hardware::{HARDWARE_BINDING_FILE, HardwareId, read_binding, write_binding};
187    use crate::keys::storage::create_device_keys_with;
188    use crate::keys::{
189        CredentialSealer, DEVICE_KEY_FILE, DeviceKeys, DeviceRecord, KeyGuard, NEXT_STORE_KEY_FILE,
190        SEALED_DEVICE_KEY_FILE, STORE_KEY_FILE, StoreKey, admit_device, found_identity,
191        load_device_keys_in, read_store_key, write_store_key,
192    };
193    use crate::machine::MachineIdentity;
194    use crate::sqlite_store::SqliteStore;
195
196    const NOW: i64 = 1_793_600_000_000_000;
197
198    struct Fixed(HardwareId);
199
200    impl HardwareSource for Fixed {
201        fn read(&self, _data_dir: &Path) -> HardwareId {
202            self.0.clone()
203        }
204    }
205
206    fn hw(lines: &[&str]) -> Fixed {
207        Fixed(HardwareId::parse(&lines.join("\n")))
208    }
209
210    struct Device {
211        dir: tempfile::TempDir,
212        machine: MachineIdentity,
213        keys: DeviceKeys,
214        store_key: StoreKey,
215    }
216
217    impl Device {
218        fn path(&self) -> &Path {
219            self.dir.path()
220        }
221
222        fn check(&self, source: &Fixed) -> HardwareCheck {
223            check_hardware_with(self.path(), self.path(), &KeyStorage::File, source).unwrap()
224        }
225
226        fn machine_id(&self) -> String {
227            MachineIdentity::load_or_create(self.path()).unwrap().id
228        }
229
230        fn keys_now(&self) -> DeviceKeys {
231            load_device_keys_in(self.path(), &KeyStorage::File)
232                .unwrap()
233                .unwrap()
234        }
235    }
236
237    fn device_on(source: &Fixed) -> Device {
238        let dir = tempfile::tempdir().unwrap();
239        let machine = MachineIdentity::load_or_create(dir.path()).unwrap();
240        let keys = create_device_keys_with(dir.path(), &KeyStorage::File, source).unwrap();
241        let store_key = StoreKey::generate().unwrap();
242        write_store_key(dir.path(), STORE_KEY_FILE, &store_key, &keys).unwrap();
243        Device {
244            dir,
245            machine,
246            keys,
247            store_key,
248        }
249    }
250
251    fn same_keys(a: &DeviceKeys, b: &DeviceKeys) -> bool {
252        a.verifying_key() == b.verifying_key()
253            && a.age_recipient().to_string() == b.age_recipient().to_string()
254            && a.ssh_public_key() == b.ssh_public_key()
255    }
256
257    fn record_for(machine_id: &str, keys: &DeviceKeys, tag: &str) -> DeviceRecord {
258        DeviceRecord {
259            machine_id: machine_id.to_string(),
260            identity_tag: tag.to_string(),
261            version: 1,
262            name: "laptop".into(),
263            age_recipient: keys.age_recipient().to_string(),
264            ssh_public_key: keys.ssh_public_key(),
265            signing_public_key: keys.verifying_key().to_bytes(),
266            recovery_fingerprints: Vec::new(),
267            ssh_login: Some("user".into()),
268            ssh_port: Some(22),
269            ssh_host_key: None,
270        }
271    }
272
273    #[test]
274    fn device_keys_record_the_hardware_id_at_creation() {
275        let device = device_on(&hw(&["disk:A", "by-id:nvme-X"]));
276        assert_eq!(
277            read_binding(device.path()).unwrap(),
278            Some(HardwareId::parse("disk:A\nby-id:nvme-X"))
279        );
280
281        let dir = tempfile::tempdir().unwrap();
282        write_binding(dir.path(), &HardwareId::parse("disk:left-behind")).unwrap();
283        create_device_keys_with(dir.path(), &KeyStorage::File, &hw(&[])).unwrap();
284        assert_eq!(
285            read_binding(dir.path()).unwrap(),
286            None,
287            "keys made where no id reads carry no stale binding"
288        );
289    }
290
291    #[test]
292    fn a_start_on_the_same_hardware_keeps_the_keys_and_machine_id() {
293        let device = device_on(&hw(&["disk:A"]));
294        let key_file = fs::read(device.path().join(DEVICE_KEY_FILE)).unwrap();
295        assert_eq!(device.check(&hw(&["disk:A"])), HardwareCheck::Bound);
296        assert_eq!(device.machine_id(), device.machine.id);
297        assert_eq!(
298            fs::read(device.path().join(DEVICE_KEY_FILE)).unwrap(),
299            key_file
300        );
301    }
302
303    #[test]
304    fn a_binding_follows_array_members_replaced_one_at_a_time() {
305        let device = device_on(&hw(&["disk:A", "disk:B"]));
306        assert_eq!(
307            device.check(&hw(&["disk:B", "disk:C"])),
308            HardwareCheck::Bound
309        );
310        assert_eq!(
311            device.check(&hw(&["disk:C", "disk:D"])),
312            HardwareCheck::Bound
313        );
314        assert_eq!(device.machine_id(), device.machine.id);
315    }
316
317    #[test]
318    fn keys_made_before_the_binding_record_this_hardware_at_their_next_start() {
319        let dir = tempfile::tempdir().unwrap();
320        let machine = MachineIdentity::load_or_create(dir.path()).unwrap();
321        DeviceKeys::load_or_create(&dir.path().join(DEVICE_KEY_FILE)).unwrap();
322        let check = |source: &Fixed| {
323            check_hardware_with(dir.path(), dir.path(), &KeyStorage::File, source).unwrap()
324        };
325        assert_eq!(check(&hw(&[])), HardwareCheck::Unreadable);
326        assert!(!dir.path().join(HARDWARE_BINDING_FILE).exists());
327        assert_eq!(check(&hw(&["disk:A"])), HardwareCheck::Recorded);
328        assert_eq!(check(&hw(&["disk:A"])), HardwareCheck::Bound);
329        assert_eq!(
330            MachineIdentity::load_or_create(dir.path()).unwrap().id,
331            machine.id
332        );
333    }
334
335    #[test]
336    fn without_device_keys_there_is_nothing_to_check() {
337        let dir = tempfile::tempdir().unwrap();
338        let check =
339            check_hardware_with(dir.path(), dir.path(), &KeyStorage::File, &hw(&["disk:A"]));
340        assert_eq!(check.unwrap(), HardwareCheck::NoKeys);
341        assert_eq!(fs::read_dir(dir.path()).unwrap().count(), 0);
342    }
343
344    #[test]
345    fn an_unreadable_id_disables_the_check_and_is_never_a_mismatch() {
346        let device = device_on(&hw(&["disk:A"]));
347        let key_file = fs::read(device.path().join(DEVICE_KEY_FILE)).unwrap();
348        for source in [hw(&[]), hw(&["devicetree:P"]), hw(&["platform:U"])] {
349            assert_eq!(device.check(&source), HardwareCheck::Unreadable);
350        }
351        assert_eq!(device.machine_id(), device.machine.id);
352        assert_eq!(
353            fs::read(device.path().join(DEVICE_KEY_FILE)).unwrap(),
354            key_file
355        );
356        assert_eq!(
357            read_binding(device.path()).unwrap(),
358            Some(HardwareId::parse("disk:A"))
359        );
360    }
361
362    #[test]
363    fn a_mismatch_mints_a_new_machine_id_and_device_keys_and_keeps_the_store_key() {
364        let device = device_on(&hw(&["disk:A"]));
365        let check = device.check(&hw(&["disk:B"]));
366
367        let now = device.machine_id();
368        assert_ne!(now, device.machine.id);
369        assert_eq!(
370            check,
371            HardwareCheck::Reminted {
372                previous_machine_id: Some(device.machine.id.clone()),
373                machine_id: now.clone(),
374            }
375        );
376        let keys = device.keys_now();
377        assert!(!same_keys(&keys, &device.keys));
378        let store_key = read_store_key(&device.path().join(STORE_KEY_FILE), &keys)
379            .unwrap()
380            .unwrap();
381        assert_eq!(store_key.expose(), device.store_key.expose());
382        assert!(
383            read_store_key(&device.path().join(STORE_KEY_FILE), &device.keys).is_err(),
384            "the original's device key no longer opens the copy's store key"
385        );
386        assert_eq!(
387            read_binding(device.path()).unwrap(),
388            Some(HardwareId::parse("disk:B"))
389        );
390        assert_eq!(device.check(&hw(&["disk:B"])), HardwareCheck::Bound);
391        assert_eq!(device.machine_id(), now);
392    }
393
394    #[test]
395    fn a_reminted_copy_has_no_identity_and_pairs_where_the_copy_was_refused() {
396        let device = device_on(&hw(&["disk:A"]));
397        let original = SqliteStore::in_memory(device.machine.id.clone()).unwrap();
398        let tag = found_identity(&original, &device.keys, "desk", &[], NOW)
399            .unwrap()
400            .tag;
401        let db = device.path().join("brain.db");
402        let copy = SqliteStore::open(&db, device.machine.id.clone()).unwrap();
403        found_identity(&copy, &device.keys, "desk", &[], NOW).unwrap();
404        drop(copy);
405
406        let refused = admit_device(
407            &original,
408            &device.keys,
409            record_for(&device.machine.id, &device.keys, tag.as_str()),
410        );
411        assert!(
412            format!("{:#}", refused.unwrap_err()).contains("is a copy"),
413            "an unreminted copy is the original to its peers"
414        );
415
416        let HardwareCheck::Reminted { machine_id, .. } = device.check(&hw(&["disk:B"])) else {
417            panic!("a copy on other hardware is reminted");
418        };
419        let copy = SqliteStore::open(&db, machine_id.clone()).unwrap();
420        assert!(copy.envelopes_for_machine(&machine_id).unwrap().is_empty());
421        assert!(copy.device_record(&machine_id).unwrap().is_none());
422        assert!(
423            copy.device_record(&device.machine.id).unwrap().is_some(),
424            "the copy keeps what it held"
425        );
426
427        let keys = device.keys_now();
428        admit_device(
429            &original,
430            &device.keys,
431            record_for(&machine_id, &keys, tag.as_str()),
432        )
433        .unwrap();
434    }
435
436    fn queued_forget() -> write_queue::Entry {
437        write_queue::Entry {
438            tool: "forget".to_string(),
439            method: "DELETE".to_string(),
440            path: "/v1/memory/m-1".to_string(),
441            query: Some("hard=false&reason=wrong".to_string()),
442            body: None,
443        }
444    }
445
446    /// Queues `entry` sealed to the device's current key; returns its path.
447    fn queue_sealed(device: &Device, entry: &write_queue::Entry) -> std::path::PathBuf {
448        let queue = device.path().join(write_queue::DIR_NAME);
449        fs::create_dir_all(&queue).unwrap();
450        let path = queue.join(write_queue::entry_name(1, true));
451        let sealed = entry
452            .to_sealed_file(&[device.keys.age_recipient()])
453            .unwrap();
454        fs::write(&path, sealed).unwrap();
455        publish_device_pub(device.path(), &device.keys).unwrap();
456        path
457    }
458
459    #[test]
460    fn a_remint_stopped_right_after_the_key_swap_leaves_queued_writes_readable() {
461        let device = device_on(&hw(&["disk:A"]));
462        let entry = queued_forget();
463        let path = queue_sealed(&device, &entry);
464        let fresh = DeviceKeys::generate().unwrap();
465
466        super::seal_to_both(device.path(), &device.keys, &fresh).unwrap();
467        assert!(!device.path().join(DEVICE_PUB_FILE).exists());
468        replace_device_keys(device.path(), &KeyStorage::File, &fresh).unwrap();
469        let keys = device.keys_now();
470        assert!(same_keys(&keys, &fresh));
471        let opened = write_queue::open(&fs::read(&path).unwrap(), Some(keys.age_identity()));
472        assert_eq!(opened.unwrap(), entry);
473
474        assert!(matches!(
475            device.check(&hw(&["disk:B"])),
476            HardwareCheck::Reminted { .. }
477        ));
478        let keys = device.keys_now();
479        let opened = write_queue::open(&fs::read(&path).unwrap(), Some(keys.age_identity()));
480        assert_eq!(opened.unwrap(), entry);
481    }
482
483    #[test]
484    fn a_write_sealed_to_the_old_key_during_the_swap_is_resealed_when_it_settles() {
485        let device = device_on(&hw(&["disk:A"]));
486        let fresh = DeviceKeys::generate().unwrap();
487        super::seal_to_both(device.path(), &device.keys, &fresh).unwrap();
488        replace_device_keys(device.path(), &KeyStorage::File, &fresh).unwrap();
489        let entry = queued_forget();
490        let late = queue_sealed(&device, &entry);
491
492        super::settle_on(device.path(), &device.keys, &fresh).unwrap();
493        let bytes = fs::read(&late).unwrap();
494        let opened = write_queue::open(&bytes, Some(fresh.age_identity()));
495        assert_eq!(opened.unwrap(), entry);
496        assert!(write_queue::open(&bytes, Some(device.keys.age_identity())).is_err());
497        assert_eq!(
498            fs::read_to_string(device.path().join(DEVICE_PUB_FILE)).unwrap(),
499            format!("{}\n", fresh.age_recipient())
500        );
501    }
502
503    #[test]
504    fn writes_queued_under_the_old_key_replay_with_the_reminted_one() {
505        let device = device_on(&hw(&["disk:A"]));
506        let entry = queued_forget();
507        let path = queue_sealed(&device, &entry);
508
509        assert!(matches!(
510            device.check(&hw(&["disk:B"])),
511            HardwareCheck::Reminted { .. }
512        ));
513        let keys = device.keys_now();
514        let bytes = fs::read(&path).unwrap();
515        let opened = write_queue::open(&bytes, Some(keys.age_identity())).unwrap();
516        assert_eq!(opened, entry);
517        assert!(write_queue::open(&bytes, Some(device.keys.age_identity())).is_err());
518        assert_eq!(
519            fs::read_to_string(device.path().join(DEVICE_PUB_FILE)).unwrap(),
520            format!("{}\n", keys.age_recipient())
521        );
522    }
523
524    #[test]
525    fn a_remint_cut_short_after_the_key_swap_finishes_at_the_next_start() {
526        let device = device_on(&hw(&["disk:A"]));
527        super::swap_device_keys(device.path(), &KeyStorage::File, &device.keys).unwrap();
528        assert_eq!(device.machine_id(), device.machine.id);
529
530        assert!(matches!(
531            device.check(&hw(&["disk:B"])),
532            HardwareCheck::Reminted { .. }
533        ));
534        assert_ne!(device.machine_id(), device.machine.id);
535        let store_key = read_store_key(&device.path().join(STORE_KEY_FILE), &device.keys_now())
536            .unwrap()
537            .unwrap();
538        assert_eq!(store_key.expose(), device.store_key.expose());
539    }
540
541    #[test]
542    fn a_remint_that_fails_is_marked_so_the_daemon_stops_and_the_next_start_finishes_it() {
543        let device = device_on(&hw(&["disk:A"]));
544        let blocker = device.path().join("not-a-dir");
545        fs::write(&blocker, "").unwrap();
546        let err = check_hardware_with(
547            device.path(),
548            &blocker.join("config"),
549            &KeyStorage::File,
550            &hw(&["disk:B"]),
551        )
552        .unwrap_err();
553        assert!(err.downcast_ref::<RemintFailed>().is_some(), "{err:#}");
554        assert_eq!(
555            read_binding(device.path()).unwrap(),
556            Some(HardwareId::parse("disk:A"))
557        );
558
559        assert!(matches!(
560            device.check(&hw(&["disk:B"])),
561            HardwareCheck::Reminted { .. }
562        ));
563        assert_ne!(device.machine_id(), device.machine.id);
564        let store_key = read_store_key(&device.path().join(STORE_KEY_FILE), &device.keys_now())
565            .unwrap()
566            .unwrap();
567        assert_eq!(store_key.expose(), device.store_key.expose());
568    }
569
570    #[test]
571    fn a_pending_rotation_key_is_rewrapped_with_the_store_key() {
572        let device = device_on(&hw(&["disk:A"]));
573        let next = StoreKey::generate().unwrap();
574        write_store_key(device.path(), NEXT_STORE_KEY_FILE, &next, &device.keys).unwrap();
575        assert!(matches!(
576            device.check(&hw(&["disk:B"])),
577            HardwareCheck::Reminted { .. }
578        ));
579        let keys = device.keys_now();
580        let opened = read_store_key(&device.path().join(NEXT_STORE_KEY_FILE), &keys)
581            .unwrap()
582            .unwrap();
583        assert_eq!(opened.expose(), next.expose());
584        assert!(read_store_key(&device.path().join(NEXT_STORE_KEY_FILE), &device.keys).is_err());
585    }
586
587    #[test]
588    fn a_sealed_copy_that_does_not_open_beside_the_plain_key_is_replaced_by_a_plain_key() {
589        let device = device_on(&hw(&["disk:A"]));
590        fs::write(
591            device.path().join(SEALED_DEVICE_KEY_FILE),
592            b"sealed on the original",
593        )
594        .unwrap();
595        let storage = KeyStorage::Sealed(Arc::new(XorSealer));
596        let check =
597            check_hardware_with(device.path(), device.path(), &storage, &hw(&["disk:B"])).unwrap();
598        assert!(matches!(check, HardwareCheck::Reminted { .. }));
599        assert!(!device.path().join(SEALED_DEVICE_KEY_FILE).exists());
600        let keys = load_device_keys_in(device.path(), &storage)
601            .unwrap()
602            .unwrap();
603        assert!(!same_keys(&keys, &device.keys));
604        let store_key = read_store_key(&device.path().join(STORE_KEY_FILE), &keys)
605            .unwrap()
606            .unwrap();
607        assert_eq!(store_key.expose(), device.store_key.expose());
608    }
609
610    const FAKE_MAGIC: &[u8] = b"XOR";
611
612    struct XorSealer;
613
614    impl CredentialSealer for XorSealer {
615        fn seal(&self, plaintext: &[u8]) -> Result<Vec<u8>> {
616            let mut out = FAKE_MAGIC.to_vec();
617            out.extend(plaintext.iter().map(|b| b ^ 0x5a));
618            Ok(out)
619        }
620
621        fn unseal(&self, sealed: &[u8]) -> Result<KeyGuard<Vec<u8>>> {
622            let body = sealed
623                .strip_prefix(FAKE_MAGIC)
624                .ok_or_else(|| anyhow!("not sealed by the fake"))?;
625            Ok(KeyGuard::new(body.iter().map(|b| b ^ 0x5a).collect()))
626        }
627    }
628
629    #[test]
630    fn a_sealed_device_key_is_replaced_in_sealed_storage() {
631        let dir = tempfile::tempdir().unwrap();
632        let storage = KeyStorage::Sealed(Arc::new(XorSealer));
633        let old = create_device_keys_with(dir.path(), &storage, &hw(&["disk:A"])).unwrap();
634        assert!(dir.path().join(SEALED_DEVICE_KEY_FILE).exists());
635
636        let check = check_hardware_with(dir.path(), dir.path(), &storage, &hw(&["disk:B"]));
637        assert!(matches!(check.unwrap(), HardwareCheck::Reminted { .. }));
638        assert!(dir.path().join(SEALED_DEVICE_KEY_FILE).exists());
639        assert!(!dir.path().join(DEVICE_KEY_FILE).exists());
640        let keys = load_device_keys_in(dir.path(), &storage).unwrap().unwrap();
641        assert!(!same_keys(&keys, &old));
642    }
643
644    #[cfg(feature = "encryption")]
645    #[test]
646    fn an_encrypted_copy_opens_its_store_under_the_new_keys() {
647        use crate::keys::open_device_store;
648        use crate::schema::{Memory, MemoryType};
649        use crate::store::Store;
650
651        let dir = tempfile::tempdir().unwrap();
652        let db = dir.path().join("brain.db");
653        let machine = MachineIdentity::load_or_create(dir.path()).unwrap();
654        let opened =
655            open_device_store(&db, dir.path(), machine.id.clone(), &KeyStorage::File).unwrap();
656        let memory = Memory::new(
657            "kept across the remint".to_string(),
658            MemoryType::Semantic,
659            "test".to_string(),
660            String::new(),
661        );
662        opened.store.store_memory(&memory).unwrap();
663        drop(opened);
664        write_binding(dir.path(), &HardwareId::parse("disk:A")).unwrap();
665
666        let check =
667            check_hardware_with(dir.path(), dir.path(), &KeyStorage::File, &hw(&["disk:B"]));
668        let HardwareCheck::Reminted { machine_id, .. } = check.unwrap() else {
669            panic!("expected a remint");
670        };
671        let reopened = open_device_store(&db, dir.path(), machine_id, &KeyStorage::File).unwrap();
672        assert!(reopened.store.get_memory(memory.id).unwrap().is_some());
673    }
674}