mod aside;
mod clone_check;
mod device;
mod device_pub;
mod founding;
mod guard;
mod handover;
mod hardware;
mod identity;
mod pairing;
mod peer_view;
mod record;
mod recovery;
mod restore;
mod retirement;
mod revocation;
mod routes;
mod storage;
mod store_key;
mod store_lifecycle;
mod subkey;
mod tables;
mod wiring;
use std::path::Path;
use anyhow::Result;
pub use aside::{
ASIDE_RETENTION_MICROS, MovedAside, move_aside_for_pairing, moved_aside_dirs, open_moved_aside,
remove_expired_asides,
};
pub use clone_check::{
HardwareCheck, RemintFailed, binding_after_creation, check_hardware, check_hardware_with,
};
pub use device::{DEVICE_KEY_FILE, DeviceKeys};
pub use device_pub::{DEVICE_PUB_FILE, publish_device_pub};
pub use founding::{Founded, found_identity};
pub use guard::KeyGuard;
pub use handover::{HeldEpoch, every_held_epoch, every_held_epoch_in, hand_over, open_handed};
pub use hardware::{
HARDWARE_BINDING_FILE, HardwareId, HardwareSource, SystemHardware, read_binding, write_binding,
};
pub use identity::{Envelope, Epoch, IdentityKey, IdentityTag, KeyId, newest_epoch, wrap};
pub use pairing::{
PriorIdentity, admit_device, check_own_paired_row, listed_signing_key, take_own_paired_row,
take_paired_rows, valid_host_key,
};
pub use peer_view::PeerView;
pub use record::{DeviceRecord, RecordSignature, SignedRecord, check_update};
pub use recovery::{RecoveryPhrase, recovery_fingerprint, wrap_for_recovery};
pub use restore::{
BackupKeys, BackupRestore, RestoreRequest, Restored, check_backup, restore_backup,
restore_backup_with,
};
pub use retirement::{Retirement, SignedRetirement, valid_fingerprint};
pub use revocation::{EpochCause, Revocation, SignedRevocation, revoked_by};
pub use routes::{DeviceRoute, LegacyRoute, valid_address, valid_login, valid_machine_id};
pub use storage::{
CredentialSealer, KEY_STORE_ENV, KeyStorage, SEALED_DEVICE_KEY_FILE, SystemdCreds,
create_device_keys, ensure_device_keys_in, has_device_key, load_device_keys,
load_device_keys_in, load_device_keys_with,
};
pub use store_key::{
NEXT_STORE_KEY_FILE, STORE_KEY_FILE, StoreKey, WRAPPED_STORE_KEY_FILE, WrapRefresh,
read_store_key, refresh_wrapped_store_key, store_in_data_dir, store_key_for,
unwrap_store_key_with_epochs, unwrap_store_key_with_phrase, write_store_key,
};
pub use store_lifecycle::{
DeviceStore, StoreEncryption, encrypt_store, open_device_store, refresh_store_key_wrap,
rotate_store_key,
};
pub use subkey::{Subkey, derive_subkey};
pub(crate) use tables::identity_tag_of;
pub use tables::{StoredDeviceRecord, StoredEpoch};
use crate::sqlite_store::SqliteStore;
pub(crate) fn hex(bytes: &[u8]) -> String {
bytes.iter().map(|b| format!("{b:02x}")).collect()
}
pub(crate) fn unhex<const N: usize>(text: &str) -> Option<[u8; N]> {
let digits = text.as_bytes();
if digits.len() != N * 2 {
return None;
}
let mut out = [0u8; N];
for (byte, pair) in out.iter_mut().zip(digits.chunks_exact(2)) {
let high = char::from(pair[0]).to_digit(16)?;
let low = char::from(pair[1]).to_digit(16)?;
*byte = u8::try_from((high << 4) | low).ok()?;
}
Some(out)
}
pub fn ensure_device_keys(store: &SqliteStore, data_dir: &Path) -> Result<bool> {
ensure_device_keys_in(store, data_dir, &KeyStorage::File)
}
#[cfg(test)]
mod tests {
use super::*;
use crate::keys::identity::wrap;
#[test]
fn device_keys_are_generated_once() {
let dir = tempfile::tempdir().unwrap();
let store = SqliteStore::in_memory("local".to_string()).unwrap();
assert!(ensure_device_keys(&store, dir.path()).unwrap());
let first = std::fs::read(dir.path().join(DEVICE_KEY_FILE)).unwrap();
assert!(!ensure_device_keys(&store, dir.path()).unwrap());
let second = std::fs::read(dir.path().join(DEVICE_KEY_FILE)).unwrap();
assert_eq!(first, second);
}
#[test]
fn a_lost_key_file_is_not_replaced_when_the_store_holds_this_devices_envelope() {
let dir = tempfile::tempdir().unwrap();
let store = SqliteStore::in_memory("local".to_string()).unwrap();
let device = DeviceKeys::generate().unwrap();
let key = IdentityKey::generate().unwrap();
let tag = IdentityTag::migrated(&key.key_id());
let envelope = wrap(&key, 1, &tag, &device.age_recipient(), Some("local".into())).unwrap();
store.put_envelope(&envelope).unwrap();
let err = format!("{:#}", ensure_device_keys(&store, dir.path()).unwrap_err());
assert!(err.contains("re-pair"), "{err}");
assert!(!dir.path().join(DEVICE_KEY_FILE).exists());
}
#[test]
fn a_lost_key_file_is_not_replaced_when_the_store_holds_this_devices_record() {
let dir = tempfile::tempdir().unwrap();
let store = SqliteStore::in_memory("local".to_string()).unwrap();
let device = DeviceKeys::generate().unwrap();
let record = DeviceRecord {
machine_id: "local".into(),
identity_tag: "f-tag".into(),
version: 1,
name: "local".into(),
age_recipient: device.age_recipient().to_string(),
ssh_public_key: device.ssh_public_key(),
signing_public_key: device.verifying_key().to_bytes(),
recovery_fingerprints: Vec::new(),
ssh_login: None,
ssh_port: None,
ssh_host_key: None,
};
let signed = record.sign("local", device.signing_key());
store
.insert_first_device_record(&signed, "local", &device.verifying_key())
.unwrap();
assert!(ensure_device_keys(&store, dir.path()).is_err());
assert!(!dir.path().join(DEVICE_KEY_FILE).exists());
}
}