use std::path::Path;
use age::x25519::Recipient;
use anyhow::{Context, Result, ensure};
use super::{
DeviceKeys, Envelope, Epoch, IdentityKey, IdentityTag, KeyStorage, open_device_store, wrap,
};
use crate::machine::MachineIdentity;
use crate::sqlite_store::SqliteStore;
const DB_FILE: &str = "brain.db";
#[non_exhaustive]
pub struct HeldEpoch {
pub identity: IdentityTag,
pub epoch: Epoch,
pub key: IdentityKey,
}
impl HeldEpoch {
pub fn new(identity: IdentityTag, epoch: Epoch, key: IdentityKey) -> Self {
Self {
identity,
epoch,
key,
}
}
}
pub fn every_held_epoch(store: &SqliteStore, device: &DeviceKeys) -> Result<Vec<HeldEpoch>> {
let recipient = device.age_recipient().to_string();
let mut held = Vec::new();
for envelope in store.envelopes_for_machine(store.machine_id())? {
if envelope.recipient != recipient {
continue;
}
match envelope.open(device.age_identity()) {
Ok(key) => held.push(HeldEpoch::new(envelope.identity_tag, envelope.epoch, key)),
Err(e) => tracing::warn!("skipping an envelope this device cannot open: {e:#}"),
}
}
Ok(held)
}
pub fn every_held_epoch_in(data_dir: &Path, storage: &KeyStorage) -> Result<Vec<HeldEpoch>> {
let db = data_dir.join(DB_FILE);
ensure!(
db.is_file(),
"{} holds no {DB_FILE}, so this device holds no key to restore with",
data_dir.display()
);
let device = super::load_device_keys_in(data_dir, storage)?.with_context(|| {
format!(
"{} holds no device key, so this device holds no key to restore with",
data_dir.display()
)
})?;
let machine = MachineIdentity::load(data_dir)?.with_context(|| {
format!(
"{} holds no machine.toml, so this device holds no key to restore with",
data_dir.display()
)
})?;
let opened = open_device_store(&db, data_dir, machine.id, storage)
.with_context(|| format!("opening {}", db.display()))?;
every_held_epoch(&opened.store, &device)
}
pub fn hand_over(held: &[HeldEpoch], recipient: &Recipient) -> Result<Vec<Envelope>> {
held.iter()
.map(|h| wrap(&h.key, h.epoch.number, &h.identity, recipient, None))
.collect()
}
pub fn open_handed(envelopes: &[Envelope], device: &DeviceKeys) -> Result<Vec<HeldEpoch>> {
envelopes
.iter()
.map(|e| {
let key = e.open(device.age_identity()).with_context(|| {
format!(
"opening the handed-over epoch {} of identity {}",
e.epoch.number,
e.identity_tag.as_str()
)
})?;
Ok(HeldEpoch::new(e.identity_tag.clone(), e.epoch, key))
})
.collect()
}
#[cfg(test)]
mod tests {
use super::*;
const NOW: i64 = 1_793_600_000_000_000;
fn epoch(number: u32, key: &IdentityKey) -> Epoch {
Epoch {
number,
key_id: key.key_id(),
}
}
#[test]
fn a_device_holds_the_epochs_of_every_identity_it_belonged_to() {
let store = SqliteStore::in_memory("own".into()).unwrap();
let device = DeviceKeys::generate().unwrap();
let other = DeviceKeys::generate().unwrap();
let old_key = IdentityKey::generate().unwrap();
let new_key = IdentityKey::generate().unwrap();
let old = IdentityTag::migrated(&old_key.key_id());
let new = IdentityTag::from("current".to_string());
let mine = device.age_recipient();
store
.put_keys_durably(
&old,
&[epoch(0, &old_key)],
&[
wrap(&old_key, 0, &old, &mine, Some("own".into())).unwrap(),
wrap(
&old_key,
0,
&old,
&other.age_recipient(),
Some("own".into()),
)
.unwrap(),
],
NOW,
)
.unwrap();
store
.put_keys_durably(
&new,
&[epoch(1, &new_key)],
&[
wrap(&new_key, 1, &new, &mine, Some("own".into())).unwrap(),
wrap(
&new_key,
1,
&new,
&other.age_recipient(),
Some("peer".into()),
)
.unwrap(),
],
NOW,
)
.unwrap();
let held = every_held_epoch(&store, &device).unwrap();
let mut found: Vec<(String, u32, [u8; 32])> = held
.iter()
.map(|h| {
(
h.identity.as_str().to_string(),
h.epoch.number,
*h.key.expose(),
)
})
.collect();
found.sort();
let mut expected = vec![
(old.as_str().to_string(), 0, *old_key.expose()),
(new.as_str().to_string(), 1, *new_key.expose()),
];
expected.sort();
assert_eq!(found, expected);
}
#[test]
fn handed_over_epochs_open_only_for_the_receiver() {
let key = IdentityKey::generate().unwrap();
let tag = IdentityTag::migrated(&key.key_id());
let held = vec![HeldEpoch::new(tag.clone(), epoch(0, &key), key)];
let receiver = DeviceKeys::generate().unwrap();
let stranger = DeviceKeys::generate().unwrap();
let envelopes = hand_over(&held, &receiver.age_recipient()).unwrap();
let opened = open_handed(&envelopes, &receiver).unwrap();
assert_eq!(opened.len(), 1);
assert_eq!(opened[0].identity, tag);
assert_eq!(opened[0].epoch, held[0].epoch);
assert_eq!(opened[0].key.expose(), held[0].key.expose());
assert!(open_handed(&envelopes, &stranger).is_err());
}
}