use std::path::{Path, PathBuf};
use serde::{Deserialize, Serialize};
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct HostId {
id: String,
created_as: Option<String>,
created_at: u64,
}
impl HostId {
pub fn as_str(&self) -> &str {
&self.id
}
pub fn created_at(&self) -> u64 {
self.created_at
}
pub fn looks_cloned(&self, current_hostname: Option<&str>) -> bool {
match (&self.created_as, current_hostname) {
(Some(created), Some(current)) => created != current,
_ => false,
}
}
pub fn rotate(hostname: Option<&str>) -> Self {
Self::generate(hostname)
}
fn generate(hostname: Option<&str>) -> Self {
Self {
id: random_hex_32(),
created_as: hostname.map(str::to_owned),
created_at: now_unix_seconds(),
}
}
pub fn load_or_create(path: &Path, hostname: Option<&str>) -> std::io::Result<(Self, bool)> {
if let Ok(text) = std::fs::read_to_string(path) {
if let Ok(existing) = toml::from_str::<HostId>(&text) {
return Ok((existing, false));
}
return Err(std::io::Error::new(
std::io::ErrorKind::InvalidData,
format!(
"{} exists but is not a readable host id; move it aside to issue a new one",
path.display()
),
));
}
let fresh = Self::generate(hostname);
if let Some(parent) = path.parent() {
std::fs::create_dir_all(parent)?;
}
let text = toml::to_string_pretty(&fresh)
.map_err(|e| std::io::Error::new(std::io::ErrorKind::InvalidData, e))?;
std::fs::write(path, text)?;
Ok((fresh, true))
}
}
fn random_hex_32() -> String {
let mut bytes = [0u8; 16];
fill_random(&mut bytes);
let mut out = String::with_capacity(32);
for b in bytes {
use std::fmt::Write as _;
let _ = write!(out, "{b:02x}");
}
out
}
#[cfg(unix)]
fn fill_random(buf: &mut [u8]) {
use std::io::Read as _;
if let Ok(mut f) = std::fs::File::open("/dev/urandom") {
if f.read_exact(buf).is_ok() {
return;
}
}
fill_random_fallback(buf);
}
#[cfg(windows)]
fn fill_random(buf: &mut [u8]) {
let ok = unsafe { windows::Win32::Security::Cryptography::ProcessPrng(buf) };
if ok.as_bool() {
return;
}
fill_random_fallback(buf);
}
#[cfg(not(any(unix, windows)))]
fn fill_random(buf: &mut [u8]) {
fill_random_fallback(buf);
}
fn fill_random_fallback(buf: &mut [u8]) {
let nanos = std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.map(|d| d.as_nanos() as u64)
.unwrap_or(0);
let stack_addr = &nanos as *const u64 as u64;
let boxed = Box::new(0u8);
let heap_addr = &*boxed as *const u8 as u64;
let mut state = nanos ^ stack_addr.rotate_left(17) ^ heap_addr.rotate_left(33);
for chunk in buf.chunks_mut(8) {
state = state.wrapping_add(0x9E37_79B9_7F4A_7C15);
let mut z = state;
z = (z ^ (z >> 30)).wrapping_mul(0xBF58_476D_1CE4_E5B9);
z = (z ^ (z >> 27)).wrapping_mul(0x94D0_49BB_1331_11EB);
z ^= z >> 31;
let bytes = z.to_le_bytes();
chunk.copy_from_slice(&bytes[..chunk.len()]);
}
}
fn now_unix_seconds() -> u64 {
std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.map(|d| d.as_secs())
.unwrap_or(0)
}
pub fn default_path() -> Option<PathBuf> {
#[cfg(windows)]
let base = std::env::var_os("APPDATA").map(PathBuf::from);
#[cfg(not(windows))]
let base = std::env::var_os("XDG_CONFIG_HOME")
.map(PathBuf::from)
.or_else(|| std::env::var_os("HOME").map(|h| PathBuf::from(h).join(".config")));
base.map(|b| b.join("ironmon").join("fleet_host_id.toml"))
}
#[cfg(test)]
mod tests {
use super::*;
fn temp_dir(tag: &str) -> PathBuf {
let p = std::env::temp_dir().join(format!("ironmon-hostid-{tag}-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&p);
std::fs::create_dir_all(&p).expect("temp dir");
p
}
#[test]
fn the_same_host_keeps_the_same_id_across_loads() {
let dir = temp_dir("stable");
let path = dir.join("id.toml");
let (first, created) = HostId::load_or_create(&path, Some("host-a")).expect("create");
assert!(created, "the first load must create it");
let (second, created_again) = HostId::load_or_create(&path, Some("host-a")).expect("load");
assert!(!created_again, "the second load must not mint a new one");
assert_eq!(first, second);
let _ = std::fs::remove_dir_all(&dir);
}
#[test]
fn two_hosts_get_different_ids() {
let a = HostId::rotate(Some("host-a"));
let b = HostId::rotate(Some("host-b"));
assert_ne!(a.as_str(), b.as_str());
assert_eq!(a.as_str().len(), 32, "{}", a.as_str());
assert!(a.as_str().chars().all(|c| c.is_ascii_hexdigit()));
}
#[test]
fn the_id_does_not_contain_the_hostname_that_made_it() {
let id = HostId::rotate(Some("workstation-01"));
assert!(
!id.as_str().contains("workstation"),
"the identifier must not be derived from anything describing the machine"
);
}
#[test]
fn a_different_hostname_reads_as_a_possible_clone() {
let id = HostId::rotate(Some("golden-image"));
assert!(id.looks_cloned(Some("host-42")));
assert!(!id.looks_cloned(Some("golden-image")));
assert!(!id.looks_cloned(None));
}
#[test]
fn rotating_yields_an_unrelated_id() {
let before = HostId::rotate(Some("host-a"));
let after = HostId::rotate(Some("host-a"));
assert_ne!(before.as_str(), after.as_str());
}
#[test]
fn a_corrupt_id_file_is_an_error_rather_than_a_new_identity() {
let dir = temp_dir("corrupt");
let path = dir.join("id.toml");
std::fs::write(&path, "this is not toml = = =").expect("write");
let err = HostId::load_or_create(&path, Some("host-a")).expect_err("must refuse");
assert_eq!(err.kind(), std::io::ErrorKind::InvalidData);
let _ = std::fs::remove_dir_all(&dir);
}
}