feat: persist opaque device anchors

This commit is contained in:
Kevin Yue committed 2026-09-29 20:42:27 +08:00
1 parent ba1a70f3ce
commit 91c480c274
6 files changed
+337 -31

No files matched your search

+63 -22
View File
@@ -1,15 +1,50 @@
//! Neutral device-anchor transport model and Linux collection.
//! Neutral device-anchor transport model and deterministic derivation.
use base64::{Engine, engine::general_purpose::URL_SAFE_NO_PAD};
use serde::{Deserialize, Serialize};
use std::fmt;
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
#[serde(try_from = "u8", into = "u8")]
pub enum AnchorSource {
LinuxMac,
LinuxRandom,
UnixMac,
UnixRandom,
MacosIokit,
}
impl From<AnchorSource> for u8 {
fn from(source: AnchorSource) -> Self {
match source {
AnchorSource::UnixMac => 1,
AnchorSource::UnixRandom => 2,
AnchorSource::MacosIokit => 3,
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct InvalidAnchorSource(u8);
impl fmt::Display for InvalidAnchorSource {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(formatter, "unsupported device anchor source {}", self.0)
}
}
impl std::error::Error for InvalidAnchorSource {}
impl TryFrom<u8> for AnchorSource {
type Error = InvalidAnchorSource;
fn try_from(value: u8) -> Result<Self, Self::Error> {
match value {
1 => Ok(Self::UnixMac),
2 => Ok(Self::UnixRandom),
3 => Ok(Self::MacosIokit),
value => Err(InvalidAnchorSource(value)),
}
}
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct DeviceAnchor {
@@ -26,8 +61,8 @@ impl DeviceAnchor {
pub fn derive(source: AnchorSource, seed: impl AsRef<[u8]>) -> Self {
let domain = match source {
AnchorSource::LinuxMac => b"gp-device-anchor:v1:linux-mac:".as_slice(),
AnchorSource::LinuxRandom => b"gp-device-anchor:v1:linux-random:".as_slice(),
AnchorSource::UnixMac => b"gp-device-anchor:v1:unix-mac:".as_slice(),
AnchorSource::UnixRandom => b"gp-device-anchor:v1:unix-random:".as_slice(),
AnchorSource::MacosIokit => b"gp-device-anchor:v1:macos-platform-uuid:".as_slice(),
};
let mut input = domain.to_vec();
@@ -39,30 +74,36 @@ impl DeviceAnchor {
}
}
#[cfg(unix)]
pub fn collect_unix() -> anyhow::Result<DeviceAnchor> {
if let Some(mac) = mac_address::get_mac_address()? {
let bytes = mac.bytes();
if bytes != [0; 6] && bytes[0] & 1 == 0 {
return Ok(DeviceAnchor::derive(AnchorSource::LinuxMac, bytes));
}
}
let mut random = [0_u8; 32];
getrandom::fill(&mut random).map_err(|_| anyhow::anyhow!("cannot initialize device anchor"))?;
Ok(DeviceAnchor::derive(AnchorSource::LinuxRandom, random))
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn hashes_are_domain_separated_and_canonical() {
let mac = DeviceAnchor::derive(AnchorSource::LinuxMac, [0, 17, 34, 51, 68, 85]);
fn hashes_original_seed_order_with_stable_domain_separation() {
let mac = DeviceAnchor::derive(AnchorSource::UnixMac, [0, 17, 34, 51, 68, 85]);
assert!(mac.validate());
assert_eq!(mac.hardware_id, "UWDOx4AVJEuCAYfJBaPioyGtRfAkJBhMYSi8LuFsE1A");
assert_ne!(
mac.hardware_id,
DeviceAnchor::derive(AnchorSource::LinuxRandom, [0, 17, 34, 51, 68, 85]).hardware_id
DeviceAnchor::derive(AnchorSource::UnixMac, [85, 68, 51, 34, 17, 0]).hardware_id
);
assert_ne!(
mac.hardware_id,
DeviceAnchor::derive(AnchorSource::UnixRandom, [0, 17, 34, 51, 68, 85]).hardware_id
);
}
#[test]
fn source_uses_stable_numeric_json_codes() {
assert_eq!(serde_json::to_string(&AnchorSource::UnixMac).unwrap(), "1");
assert_eq!(serde_json::to_string(&AnchorSource::UnixRandom).unwrap(), "2");
assert_eq!(serde_json::to_string(&AnchorSource::MacosIokit).unwrap(), "3");
assert_eq!(
serde_json::from_str::<AnchorSource>("1").unwrap(),
AnchorSource::UnixMac
);
assert!(serde_json::from_str::<AnchorSource>("0").is_err());
assert!(serde_json::from_str::<AnchorSource>("4").is_err());
assert!(serde_json::from_str::<AnchorSource>(r#""unix_mac""#).is_err());
}
}
@@ -189,13 +189,35 @@ mod tests {
fn credential_round_trips_a_validated_device_anchor() {
let anchor = DeviceAnchor {
hardware_id: general_purpose::URL_SAFE_NO_PAD.encode([1_u8; 32]),
source: crate::device_anchor::AnchorSource::LinuxMac,
source: crate::device_anchor::AnchorSource::UnixMac,
};
let credential = SessionCredential::generate(Uuid::new_v4(), "2.6.5")
.unwrap()
.with_device_anchor(anchor.clone())
.unwrap();
let decoded = SessionCredential::decode_frame(&credential.encode_frame().unwrap()).unwrap();
let frame = credential.encode_frame().unwrap();
let payload: serde_json::Value = serde_json::from_slice(&frame[2..]).unwrap();
assert_eq!(payload["device_anchor"]["source"], 1);
let decoded = SessionCredential::decode_frame(&frame).unwrap();
assert_eq!(decoded.device_anchor(), Some(&anchor));
}
#[test]
fn credential_rejects_reserved_and_unknown_anchor_sources() {
let credential = SessionCredential::generate(Uuid::new_v4(), "2.6.5").unwrap();
let frame = credential.encode_frame().unwrap();
let mut payload: serde_json::Value = serde_json::from_slice(&frame[2..]).unwrap();
let hardware_id = general_purpose::URL_SAFE_NO_PAD.encode([1_u8; 32]);
for source in [0, 4] {
payload["device_anchor"] = serde_json::json!({
"hardware_id": hardware_id,
"source": source
});
let bytes = serde_json::to_vec(&payload).unwrap();
let mut invalid_frame = (bytes.len() as u16).to_be_bytes().to_vec();
invalid_frame.extend_from_slice(&bytes);
assert!(SessionCredential::decode_frame(&invalid_frame).is_err());
}
}
}