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