use std::fmt;
use std::path::Path;
use anyhow::{Context, Result};
use super::hardware::{HardwareId, HardwareSource, SystemHardware, read_binding, write_binding};
use super::storage::{has_device_key, replace_device_keys};
use super::store_key::write_store_key_to;
use super::{
DEVICE_PUB_FILE, DeviceKeys, KeyStorage, NEXT_STORE_KEY_FILE, STORE_KEY_FILE,
load_device_keys_in, publish_device_pub, read_store_key,
};
use crate::machine::MachineIdentity;
use crate::write_queue;
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub enum HardwareCheck {
NoKeys,
Bound,
Recorded,
Unreadable,
Reminted {
previous_machine_id: Option<String>,
machine_id: String,
},
}
impl HardwareCheck {
pub fn name(&self) -> &'static str {
match self {
Self::NoKeys => "no-keys",
Self::Bound => "bound",
Self::Recorded => "recorded",
Self::Unreadable => "unreadable",
Self::Reminted { .. } => "reminted",
}
}
}
#[derive(Debug)]
pub struct RemintFailed;
impl fmt::Display for RemintFailed {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str("the device keys were made on other hardware and replacing them failed")
}
}
pub fn check_hardware(
data_dir: &Path,
config_dir: &Path,
storage: &KeyStorage,
) -> Result<HardwareCheck> {
check_hardware_with(data_dir, config_dir, storage, &SystemHardware)
}
pub fn check_hardware_with(
data_dir: &Path,
config_dir: &Path,
storage: &KeyStorage,
source: &dyn HardwareSource,
) -> Result<HardwareCheck> {
let Some(device) = load_device_keys_in(data_dir, storage)? else {
return Ok(HardwareCheck::NoKeys);
};
let current = source.read(data_dir);
let Some(recorded) = read_binding(data_dir)? else {
if current.is_empty() {
return Ok(HardwareCheck::Unreadable);
}
write_binding(data_dir, ¤t)?;
return Ok(HardwareCheck::Recorded);
};
match recorded.matches(¤t) {
None => Ok(HardwareCheck::Unreadable),
Some(true) => {
let refreshed = recorded.refreshed(¤t);
if refreshed != recorded {
write_binding(data_dir, &refreshed)?;
}
Ok(HardwareCheck::Bound)
}
Some(false) => {
remint(data_dir, config_dir, storage, &device, ¤t).context(RemintFailed)
}
}
}
pub fn binding_after_creation(data_dir: &Path) -> Result<HardwareCheck> {
if !has_device_key(data_dir) {
return Ok(HardwareCheck::NoKeys);
}
Ok(match read_binding(data_dir)? {
Some(id) if !id.is_empty() => HardwareCheck::Recorded,
_ => HardwareCheck::Unreadable,
})
}
fn remint(
data_dir: &Path,
config_dir: &Path,
storage: &KeyStorage,
device: &DeviceKeys,
current: &HardwareId,
) -> Result<HardwareCheck> {
let previous_machine_id = match MachineIdentity::load(config_dir) {
Ok(machine) => machine.map(|m| m.id),
Err(e) => {
tracing::warn!("cannot read the machine id being replaced: {e:#}");
None
}
};
swap_device_keys(data_dir, storage, device)?;
let machine = MachineIdentity::mint(config_dir)?;
write_binding(data_dir, current)?;
Ok(HardwareCheck::Reminted {
previous_machine_id,
machine_id: machine.id,
})
}
fn swap_device_keys(data_dir: &Path, storage: &KeyStorage, old: &DeviceKeys) -> Result<DeviceKeys> {
let fresh = DeviceKeys::generate()?;
seal_to_both(data_dir, old, &fresh)?;
replace_device_keys(data_dir, storage, &fresh)?;
settle_on(data_dir, old, &fresh)?;
Ok(fresh)
}
fn seal_to_both(data_dir: &Path, old: &DeviceKeys, fresh: &DeviceKeys) -> Result<()> {
match std::fs::remove_file(data_dir.join(DEVICE_PUB_FILE)) {
Ok(()) => {}
Err(e) if e.kind() == std::io::ErrorKind::NotFound => {}
Err(e) => return Err(e).context("withdrawing the device recipient"),
}
rewrap_store_keys(data_dir, old, &[old, fresh])?;
write_queue::reseal_dir(
&data_dir.join(write_queue::DIR_NAME),
old.age_identity(),
&[old.age_recipient(), fresh.age_recipient()],
)?;
Ok(())
}
fn settle_on(data_dir: &Path, old: &DeviceKeys, fresh: &DeviceKeys) -> Result<()> {
rewrap_store_keys(data_dir, fresh, &[fresh])?;
publish_device_pub(data_dir, fresh)?;
write_queue::reseal_dir(
&data_dir.join(write_queue::DIR_NAME),
old.age_identity(),
&[fresh.age_recipient()],
)?;
Ok(())
}
fn rewrap_store_keys(data_dir: &Path, reader: &DeviceKeys, devices: &[&DeviceKeys]) -> Result<()> {
for name in [STORE_KEY_FILE, NEXT_STORE_KEY_FILE] {
if let Some(key) = read_store_key(&data_dir.join(name), reader)? {
write_store_key_to(data_dir, name, &key, devices)?;
}
}
Ok(())
}
#[cfg(test)]
mod tests {
use std::fs;
use std::sync::Arc;
use anyhow::anyhow;
use super::*;
use crate::keys::hardware::{HARDWARE_BINDING_FILE, HardwareId, read_binding, write_binding};
use crate::keys::storage::create_device_keys_with;
use crate::keys::{
CredentialSealer, DEVICE_KEY_FILE, DeviceKeys, DeviceRecord, KeyGuard, NEXT_STORE_KEY_FILE,
SEALED_DEVICE_KEY_FILE, STORE_KEY_FILE, StoreKey, admit_device, found_identity,
load_device_keys_in, read_store_key, write_store_key,
};
use crate::machine::MachineIdentity;
use crate::sqlite_store::SqliteStore;
const NOW: i64 = 1_793_600_000_000_000;
struct Fixed(HardwareId);
impl HardwareSource for Fixed {
fn read(&self, _data_dir: &Path) -> HardwareId {
self.0.clone()
}
}
fn hw(lines: &[&str]) -> Fixed {
Fixed(HardwareId::parse(&lines.join("\n")))
}
struct Device {
dir: tempfile::TempDir,
machine: MachineIdentity,
keys: DeviceKeys,
store_key: StoreKey,
}
impl Device {
fn path(&self) -> &Path {
self.dir.path()
}
fn check(&self, source: &Fixed) -> HardwareCheck {
check_hardware_with(self.path(), self.path(), &KeyStorage::File, source).unwrap()
}
fn machine_id(&self) -> String {
MachineIdentity::load_or_create(self.path()).unwrap().id
}
fn keys_now(&self) -> DeviceKeys {
load_device_keys_in(self.path(), &KeyStorage::File)
.unwrap()
.unwrap()
}
}
fn device_on(source: &Fixed) -> Device {
let dir = tempfile::tempdir().unwrap();
let machine = MachineIdentity::load_or_create(dir.path()).unwrap();
let keys = create_device_keys_with(dir.path(), &KeyStorage::File, source).unwrap();
let store_key = StoreKey::generate().unwrap();
write_store_key(dir.path(), STORE_KEY_FILE, &store_key, &keys).unwrap();
Device {
dir,
machine,
keys,
store_key,
}
}
fn same_keys(a: &DeviceKeys, b: &DeviceKeys) -> bool {
a.verifying_key() == b.verifying_key()
&& a.age_recipient().to_string() == b.age_recipient().to_string()
&& a.ssh_public_key() == b.ssh_public_key()
}
fn record_for(machine_id: &str, keys: &DeviceKeys, tag: &str) -> DeviceRecord {
DeviceRecord {
machine_id: machine_id.to_string(),
identity_tag: tag.to_string(),
version: 1,
name: "laptop".into(),
age_recipient: keys.age_recipient().to_string(),
ssh_public_key: keys.ssh_public_key(),
signing_public_key: keys.verifying_key().to_bytes(),
recovery_fingerprints: Vec::new(),
ssh_login: Some("user".into()),
ssh_port: Some(22),
ssh_host_key: None,
}
}
#[test]
fn keys_made_during_this_start_report_the_hardware_they_were_bound_to() {
let none = tempfile::tempdir().unwrap();
assert_eq!(
binding_after_creation(none.path()).unwrap(),
HardwareCheck::NoKeys
);
let left_behind = tempfile::tempdir().unwrap();
write_binding(left_behind.path(), &HardwareId::parse("disk:A")).unwrap();
assert_eq!(
binding_after_creation(left_behind.path()).unwrap(),
HardwareCheck::NoKeys
);
let device = device_on(&hw(&["disk:A"]));
assert_eq!(
binding_after_creation(device.path()).unwrap(),
HardwareCheck::Recorded
);
let unreadable = tempfile::tempdir().unwrap();
create_device_keys_with(unreadable.path(), &KeyStorage::File, &hw(&[])).unwrap();
assert_eq!(
binding_after_creation(unreadable.path()).unwrap(),
HardwareCheck::Unreadable
);
}
#[test]
fn device_keys_record_the_hardware_id_at_creation() {
let device = device_on(&hw(&["disk:A", "by-id:nvme-X"]));
assert_eq!(
read_binding(device.path()).unwrap(),
Some(HardwareId::parse("disk:A\nby-id:nvme-X"))
);
let dir = tempfile::tempdir().unwrap();
write_binding(dir.path(), &HardwareId::parse("disk:left-behind")).unwrap();
create_device_keys_with(dir.path(), &KeyStorage::File, &hw(&[])).unwrap();
assert_eq!(
read_binding(dir.path()).unwrap(),
None,
"keys made where no id reads carry no stale binding"
);
}
#[test]
fn a_start_on_the_same_hardware_keeps_the_keys_and_machine_id() {
let device = device_on(&hw(&["disk:A"]));
let key_file = fs::read(device.path().join(DEVICE_KEY_FILE)).unwrap();
assert_eq!(device.check(&hw(&["disk:A"])), HardwareCheck::Bound);
assert_eq!(device.machine_id(), device.machine.id);
assert_eq!(
fs::read(device.path().join(DEVICE_KEY_FILE)).unwrap(),
key_file
);
}
#[test]
fn a_binding_follows_array_members_replaced_one_at_a_time() {
let device = device_on(&hw(&["disk:A", "disk:B"]));
assert_eq!(
device.check(&hw(&["disk:B", "disk:C"])),
HardwareCheck::Bound
);
assert_eq!(
device.check(&hw(&["disk:C", "disk:D"])),
HardwareCheck::Bound
);
assert_eq!(device.machine_id(), device.machine.id);
}
#[test]
fn keys_made_before_the_binding_record_this_hardware_at_their_next_start() {
let dir = tempfile::tempdir().unwrap();
let machine = MachineIdentity::load_or_create(dir.path()).unwrap();
DeviceKeys::load_or_create(&dir.path().join(DEVICE_KEY_FILE)).unwrap();
let check = |source: &Fixed| {
check_hardware_with(dir.path(), dir.path(), &KeyStorage::File, source).unwrap()
};
assert_eq!(check(&hw(&[])), HardwareCheck::Unreadable);
assert!(!dir.path().join(HARDWARE_BINDING_FILE).exists());
assert_eq!(check(&hw(&["disk:A"])), HardwareCheck::Recorded);
assert_eq!(check(&hw(&["disk:A"])), HardwareCheck::Bound);
assert_eq!(
MachineIdentity::load_or_create(dir.path()).unwrap().id,
machine.id
);
}
#[test]
fn without_device_keys_there_is_nothing_to_check() {
let dir = tempfile::tempdir().unwrap();
let check =
check_hardware_with(dir.path(), dir.path(), &KeyStorage::File, &hw(&["disk:A"]));
assert_eq!(check.unwrap(), HardwareCheck::NoKeys);
assert_eq!(fs::read_dir(dir.path()).unwrap().count(), 0);
}
#[test]
fn an_unreadable_id_disables_the_check_and_is_never_a_mismatch() {
let device = device_on(&hw(&["disk:A"]));
let key_file = fs::read(device.path().join(DEVICE_KEY_FILE)).unwrap();
for source in [hw(&[]), hw(&["devicetree:P"]), hw(&["platform:U"])] {
assert_eq!(device.check(&source), HardwareCheck::Unreadable);
}
assert_eq!(device.machine_id(), device.machine.id);
assert_eq!(
fs::read(device.path().join(DEVICE_KEY_FILE)).unwrap(),
key_file
);
assert_eq!(
read_binding(device.path()).unwrap(),
Some(HardwareId::parse("disk:A"))
);
}
#[test]
fn a_mismatch_mints_a_new_machine_id_and_device_keys_and_keeps_the_store_key() {
let device = device_on(&hw(&["disk:A"]));
let check = device.check(&hw(&["disk:B"]));
let now = device.machine_id();
assert_ne!(now, device.machine.id);
assert_eq!(
check,
HardwareCheck::Reminted {
previous_machine_id: Some(device.machine.id.clone()),
machine_id: now.clone(),
}
);
let keys = device.keys_now();
assert!(!same_keys(&keys, &device.keys));
let store_key = read_store_key(&device.path().join(STORE_KEY_FILE), &keys)
.unwrap()
.unwrap();
assert_eq!(store_key.expose(), device.store_key.expose());
assert!(
read_store_key(&device.path().join(STORE_KEY_FILE), &device.keys).is_err(),
"the original's device key no longer opens the copy's store key"
);
assert_eq!(
read_binding(device.path()).unwrap(),
Some(HardwareId::parse("disk:B"))
);
assert_eq!(device.check(&hw(&["disk:B"])), HardwareCheck::Bound);
assert_eq!(device.machine_id(), now);
}
#[test]
fn a_reminted_copy_has_no_identity_and_pairs_where_the_copy_was_refused() {
let device = device_on(&hw(&["disk:A"]));
let original = SqliteStore::in_memory(device.machine.id.clone()).unwrap();
let tag = found_identity(&original, &device.keys, "desk", &[], NOW)
.unwrap()
.tag;
let db = device.path().join("brain.db");
let copy = SqliteStore::open(&db, device.machine.id.clone()).unwrap();
found_identity(©, &device.keys, "desk", &[], NOW).unwrap();
drop(copy);
let refused = admit_device(
&original,
&device.keys,
record_for(&device.machine.id, &device.keys, tag.as_str()),
);
assert!(
format!("{:#}", refused.unwrap_err()).contains("is a copy"),
"an unreminted copy is the original to its peers"
);
let HardwareCheck::Reminted { machine_id, .. } = device.check(&hw(&["disk:B"])) else {
panic!("a copy on other hardware is reminted");
};
let copy = SqliteStore::open(&db, machine_id.clone()).unwrap();
assert!(copy.envelopes_for_machine(&machine_id).unwrap().is_empty());
assert!(copy.device_record(&machine_id).unwrap().is_none());
assert!(
copy.device_record(&device.machine.id).unwrap().is_some(),
"the copy keeps what it held"
);
let keys = device.keys_now();
admit_device(
&original,
&device.keys,
record_for(&machine_id, &keys, tag.as_str()),
)
.unwrap();
}
fn queued_forget() -> write_queue::Entry {
write_queue::Entry {
tool: "forget".to_string(),
method: "DELETE".to_string(),
path: "/v1/memory/m-1".to_string(),
query: Some("hard=false&reason=wrong".to_string()),
body: None,
}
}
fn queue_sealed(device: &Device, entry: &write_queue::Entry) -> std::path::PathBuf {
let queue = device.path().join(write_queue::DIR_NAME);
fs::create_dir_all(&queue).unwrap();
let path = queue.join(write_queue::entry_name(1, true));
let sealed = entry
.to_sealed_file(&[device.keys.age_recipient()])
.unwrap();
fs::write(&path, sealed).unwrap();
publish_device_pub(device.path(), &device.keys).unwrap();
path
}
#[test]
fn a_remint_stopped_right_after_the_key_swap_leaves_queued_writes_readable() {
let device = device_on(&hw(&["disk:A"]));
let entry = queued_forget();
let path = queue_sealed(&device, &entry);
let fresh = DeviceKeys::generate().unwrap();
super::seal_to_both(device.path(), &device.keys, &fresh).unwrap();
assert!(!device.path().join(DEVICE_PUB_FILE).exists());
replace_device_keys(device.path(), &KeyStorage::File, &fresh).unwrap();
let keys = device.keys_now();
assert!(same_keys(&keys, &fresh));
let opened = write_queue::open(&fs::read(&path).unwrap(), Some(keys.age_identity()));
assert_eq!(opened.unwrap(), entry);
assert!(matches!(
device.check(&hw(&["disk:B"])),
HardwareCheck::Reminted { .. }
));
let keys = device.keys_now();
let opened = write_queue::open(&fs::read(&path).unwrap(), Some(keys.age_identity()));
assert_eq!(opened.unwrap(), entry);
}
#[test]
fn a_write_sealed_to_the_old_key_during_the_swap_is_resealed_when_it_settles() {
let device = device_on(&hw(&["disk:A"]));
let fresh = DeviceKeys::generate().unwrap();
super::seal_to_both(device.path(), &device.keys, &fresh).unwrap();
replace_device_keys(device.path(), &KeyStorage::File, &fresh).unwrap();
let entry = queued_forget();
let late = queue_sealed(&device, &entry);
super::settle_on(device.path(), &device.keys, &fresh).unwrap();
let bytes = fs::read(&late).unwrap();
let opened = write_queue::open(&bytes, Some(fresh.age_identity()));
assert_eq!(opened.unwrap(), entry);
assert!(write_queue::open(&bytes, Some(device.keys.age_identity())).is_err());
assert_eq!(
fs::read_to_string(device.path().join(DEVICE_PUB_FILE)).unwrap(),
format!("{}\n", fresh.age_recipient())
);
}
#[test]
fn writes_queued_under_the_old_key_replay_with_the_reminted_one() {
let device = device_on(&hw(&["disk:A"]));
let entry = queued_forget();
let path = queue_sealed(&device, &entry);
assert!(matches!(
device.check(&hw(&["disk:B"])),
HardwareCheck::Reminted { .. }
));
let keys = device.keys_now();
let bytes = fs::read(&path).unwrap();
let opened = write_queue::open(&bytes, Some(keys.age_identity())).unwrap();
assert_eq!(opened, entry);
assert!(write_queue::open(&bytes, Some(device.keys.age_identity())).is_err());
assert_eq!(
fs::read_to_string(device.path().join(DEVICE_PUB_FILE)).unwrap(),
format!("{}\n", keys.age_recipient())
);
}
#[test]
fn a_remint_cut_short_after_the_key_swap_finishes_at_the_next_start() {
let device = device_on(&hw(&["disk:A"]));
super::swap_device_keys(device.path(), &KeyStorage::File, &device.keys).unwrap();
assert_eq!(device.machine_id(), device.machine.id);
assert!(matches!(
device.check(&hw(&["disk:B"])),
HardwareCheck::Reminted { .. }
));
assert_ne!(device.machine_id(), device.machine.id);
let store_key = read_store_key(&device.path().join(STORE_KEY_FILE), &device.keys_now())
.unwrap()
.unwrap();
assert_eq!(store_key.expose(), device.store_key.expose());
}
#[test]
fn a_remint_that_fails_is_marked_so_the_daemon_stops_and_the_next_start_finishes_it() {
let device = device_on(&hw(&["disk:A"]));
let blocker = device.path().join("not-a-dir");
fs::write(&blocker, "").unwrap();
let err = check_hardware_with(
device.path(),
&blocker.join("config"),
&KeyStorage::File,
&hw(&["disk:B"]),
)
.unwrap_err();
assert!(err.downcast_ref::<RemintFailed>().is_some(), "{err:#}");
assert_eq!(
read_binding(device.path()).unwrap(),
Some(HardwareId::parse("disk:A"))
);
assert!(matches!(
device.check(&hw(&["disk:B"])),
HardwareCheck::Reminted { .. }
));
assert_ne!(device.machine_id(), device.machine.id);
let store_key = read_store_key(&device.path().join(STORE_KEY_FILE), &device.keys_now())
.unwrap()
.unwrap();
assert_eq!(store_key.expose(), device.store_key.expose());
}
#[test]
fn a_pending_rotation_key_is_rewrapped_with_the_store_key() {
let device = device_on(&hw(&["disk:A"]));
let next = StoreKey::generate().unwrap();
write_store_key(device.path(), NEXT_STORE_KEY_FILE, &next, &device.keys).unwrap();
assert!(matches!(
device.check(&hw(&["disk:B"])),
HardwareCheck::Reminted { .. }
));
let keys = device.keys_now();
let opened = read_store_key(&device.path().join(NEXT_STORE_KEY_FILE), &keys)
.unwrap()
.unwrap();
assert_eq!(opened.expose(), next.expose());
assert!(read_store_key(&device.path().join(NEXT_STORE_KEY_FILE), &device.keys).is_err());
}
#[test]
fn a_sealed_copy_that_does_not_open_beside_the_plain_key_is_replaced_by_a_plain_key() {
let device = device_on(&hw(&["disk:A"]));
fs::write(
device.path().join(SEALED_DEVICE_KEY_FILE),
b"sealed on the original",
)
.unwrap();
let storage = KeyStorage::Sealed(Arc::new(XorSealer));
let check =
check_hardware_with(device.path(), device.path(), &storage, &hw(&["disk:B"])).unwrap();
assert!(matches!(check, HardwareCheck::Reminted { .. }));
assert!(!device.path().join(SEALED_DEVICE_KEY_FILE).exists());
let keys = load_device_keys_in(device.path(), &storage)
.unwrap()
.unwrap();
assert!(!same_keys(&keys, &device.keys));
let store_key = read_store_key(&device.path().join(STORE_KEY_FILE), &keys)
.unwrap()
.unwrap();
assert_eq!(store_key.expose(), device.store_key.expose());
}
const FAKE_MAGIC: &[u8] = b"XOR";
struct XorSealer;
impl CredentialSealer for XorSealer {
fn seal(&self, plaintext: &[u8]) -> Result<Vec<u8>> {
let mut out = FAKE_MAGIC.to_vec();
out.extend(plaintext.iter().map(|b| b ^ 0x5a));
Ok(out)
}
fn unseal(&self, sealed: &[u8]) -> Result<KeyGuard<Vec<u8>>> {
let body = sealed
.strip_prefix(FAKE_MAGIC)
.ok_or_else(|| anyhow!("not sealed by the fake"))?;
Ok(KeyGuard::new(body.iter().map(|b| b ^ 0x5a).collect()))
}
}
#[test]
fn a_sealed_device_key_is_replaced_in_sealed_storage() {
let dir = tempfile::tempdir().unwrap();
let storage = KeyStorage::Sealed(Arc::new(XorSealer));
let old = create_device_keys_with(dir.path(), &storage, &hw(&["disk:A"])).unwrap();
assert!(dir.path().join(SEALED_DEVICE_KEY_FILE).exists());
let check = check_hardware_with(dir.path(), dir.path(), &storage, &hw(&["disk:B"]));
assert!(matches!(check.unwrap(), HardwareCheck::Reminted { .. }));
assert!(dir.path().join(SEALED_DEVICE_KEY_FILE).exists());
assert!(!dir.path().join(DEVICE_KEY_FILE).exists());
let keys = load_device_keys_in(dir.path(), &storage).unwrap().unwrap();
assert!(!same_keys(&keys, &old));
}
#[cfg(feature = "encryption")]
#[test]
fn an_encrypted_copy_opens_its_store_under_the_new_keys() {
use crate::keys::open_device_store;
use crate::schema::{Memory, MemoryType};
use crate::store::Store;
let dir = tempfile::tempdir().unwrap();
let db = dir.path().join("brain.db");
let machine = MachineIdentity::load_or_create(dir.path()).unwrap();
let opened =
open_device_store(&db, dir.path(), machine.id.clone(), &KeyStorage::File).unwrap();
let memory = Memory::new(
"kept across the remint".to_string(),
MemoryType::Semantic,
"test".to_string(),
String::new(),
);
opened.store.store_memory(&memory).unwrap();
drop(opened);
write_binding(dir.path(), &HardwareId::parse("disk:A")).unwrap();
let check =
check_hardware_with(dir.path(), dir.path(), &KeyStorage::File, &hw(&["disk:B"]));
let HardwareCheck::Reminted { machine_id, .. } = check.unwrap() else {
panic!("expected a remint");
};
let reopened = open_device_store(&db, dir.path(), machine_id, &KeyStorage::File).unwrap();
assert!(reopened.store.get_memory(memory.id).unwrap().is_some());
}
}