Skip to main content

hyprstream_core/auth/
device_challenge.rs

1//! Anonymous device enrollment — stateless HMAC challenge and Ed25519 verification.
2//!
3//! The challenge is `HMAC-SHA256(challenge_key, pubkey)`. It is deterministic:
4//! the same pubkey always produces the same challenge. Replay of a valid
5//! `(pubkey, signature)` pair is idempotent — it re-enrolls the same device,
6//! producing the same `DeviceRecord` upsert. This is analogous to PKCS#10 CSR
7//! signing in standard PKI, where the CA validates possession, not freshness.
8//!
9//! `challenge_key` is derived from the node signing key via HKDF so that:
10//! 1. It never overlaps with the JWT signing path.
11//! 2. It is safe to use as a challenge oracle (HMAC is secure under chosen-message attacks).
12
13use ed25519_dalek::{Signature, Verifier, VerifyingKey};
14use hmac::{Hmac, Mac};
15use sha2::Sha256;
16
17type HmacSha256 = Hmac<Sha256>;
18
19/// Derive the challenge key from the node signing key seed.
20///
21/// Returns the 32-byte HKDF expansion that serves as the HMAC-SHA256 key.
22pub fn derive_challenge_key(signing_key_bytes: &[u8; 32]) -> [u8; 32] {
23    use hkdf::Hkdf;
24    let hk = Hkdf::<Sha256>::new(None, signing_key_bytes);
25    let mut okm = [0u8; 32];
26    #[allow(clippy::expect_used)]
27    hk.expand(b"aegis-device-challenge-v1", &mut okm)
28        .expect("HKDF-SHA256 expand to 32 bytes cannot fail");
29    okm
30}
31
32/// Derive the cookie signing key from the node signing key seed.
33///
34/// Returns a 32-byte seed suitable for constructing an Ed25519 signing key.
35pub fn derive_cookie_key_seed(signing_key_bytes: &[u8; 32]) -> [u8; 32] {
36    use hkdf::Hkdf;
37    let hk = Hkdf::<Sha256>::new(None, signing_key_bytes);
38    let mut okm = [0u8; 32];
39    #[allow(clippy::expect_used)]
40    hk.expand(b"aegis-device-cookie-v1", &mut okm)
41        .expect("HKDF-SHA256 expand to 32 bytes cannot fail");
42    okm
43}
44
45/// Compute the challenge bytes the client must sign to prove device key possession.
46///
47/// `HMAC-SHA256(challenge_key, pubkey)` — stateless, deterministic per (key, pubkey) pair.
48pub fn device_challenge(challenge_key: &[u8; 32], pubkey: &[u8; 32]) -> [u8; 32] {
49    // new_from_slice only fails for keys larger than the block size; a 32-byte key is valid.
50    #[allow(clippy::expect_used)]
51    let mut mac =
52        HmacSha256::new_from_slice(challenge_key).expect("HMAC-SHA256 accepts 32-byte key");
53    mac.update(pubkey);
54    mac.finalize().into_bytes().into()
55}
56
57/// Verify that `signature` is a valid Ed25519 signature over `HMAC(challenge_key, pubkey)`.
58pub fn verify_device_enrollment(
59    challenge_key: &[u8; 32],
60    pubkey: &[u8; 32],
61    signature: &[u8; 64],
62) -> bool {
63    let challenge = device_challenge(challenge_key, pubkey);
64    let Ok(vk) = VerifyingKey::from_bytes(pubkey) else {
65        return false;
66    };
67    let sig = Signature::from_bytes(signature);
68    vk.verify(&challenge, &sig).is_ok()
69}
70
71/// Encode a `__Secure-VaultDevice` cookie value.
72///
73/// Format: `base64url( kid[8 ASCII bytes] || exp[8 bytes, big-endian i64] || pubkey[32 bytes] || sig[64 bytes] )`
74///
75/// `kid` identifies the rotation slot. `exp` is a Unix timestamp; the server
76/// rejects the cookie when `now >= exp` without touching the signature.
77/// The signed message covers `kid || exp || pubkey` so expiry cannot be forged.
78pub fn encode_vault_device_cookie(
79    cookie_signing_key: &ed25519_dalek::SigningKey,
80    kid: &str,
81    pubkey: &[u8; 32],
82    exp: i64,
83) -> String {
84    use base64::{engine::general_purpose::URL_SAFE_NO_PAD, Engine};
85    use ed25519_dalek::Signer;
86
87    assert_eq!(kid.len(), 8, "kid must be exactly 8 ASCII characters");
88    let kid_bytes = kid.as_bytes();
89    let exp_bytes = exp.to_be_bytes();
90
91    let mut msg = Vec::with_capacity(8 + 8 + 32);
92    msg.extend_from_slice(kid_bytes);
93    msg.extend_from_slice(&exp_bytes);
94    msg.extend_from_slice(pubkey);
95
96    let sig = cookie_signing_key.sign(&msg);
97
98    let mut payload = Vec::with_capacity(8 + 8 + 32 + 64);
99    payload.extend_from_slice(kid_bytes);
100    payload.extend_from_slice(&exp_bytes);
101    payload.extend_from_slice(pubkey);
102    payload.extend_from_slice(&sig.to_bytes());
103
104    URL_SAFE_NO_PAD.encode(&payload)
105}
106
107/// Compute the `kid` for a cookie signing key (first 4 bytes of SHA-256 → 8 hex chars).
108///
109/// 8 ASCII hex characters fit the cookie format's `kid[8]` field exactly.
110pub fn compute_kid(verifying_key_bytes: &[u8]) -> String {
111    use sha2::{Digest, Sha256};
112    let hash = Sha256::digest(verifying_key_bytes);
113    hex::encode(&hash[..4])
114}
115
116/// Verify a `__Secure-VaultDevice` cookie and return the device pubkey on success.
117///
118/// Returns `None` on malformation, signature failure, kid mismatch (key rotation),
119/// or expiry (`now >= exp`).
120pub fn verify_vault_device_cookie(
121    signing_key_bytes: &[u8; 32],
122    cookie_value: &str,
123) -> Option<[u8; 32]> {
124    use base64::{engine::general_purpose::URL_SAFE_NO_PAD, Engine};
125    use ed25519_dalek::{Signature, Verifier};
126
127    let raw = URL_SAFE_NO_PAD.decode(cookie_value).ok()?;
128    if raw.len() != 8 + 8 + 32 + 64 {
129        return None;
130    }
131    let kid_bytes = &raw[..8];
132    let exp = i64::from_be_bytes(raw[8..16].try_into().ok()?);
133    let mut pubkey_arr = [0u8; 32];
134    pubkey_arr.copy_from_slice(&raw[16..48]);
135    let mut sig_arr = [0u8; 64];
136    sig_arr.copy_from_slice(&raw[48..112]);
137
138    // Expiry check before any crypto work.
139    let now = chrono::Utc::now().timestamp();
140    if now >= exp {
141        return None;
142    }
143
144    let cookie_seed = derive_cookie_key_seed(signing_key_bytes);
145    let cookie_sk = ed25519_dalek::SigningKey::from_bytes(&cookie_seed);
146    let expected_kid = compute_kid(cookie_sk.verifying_key().as_bytes());
147
148    // kid mismatch → key rotation; client should silently re-enroll
149    if kid_bytes != expected_kid.as_bytes() {
150        return None;
151    }
152
153    let mut msg = Vec::with_capacity(8 + 8 + 32);
154    msg.extend_from_slice(kid_bytes);
155    msg.extend_from_slice(&raw[8..16]); // exp bytes
156    msg.extend_from_slice(&pubkey_arr);
157
158    let sig = Signature::from_bytes(&sig_arr);
159    cookie_sk.verifying_key().verify(&msg, &sig).ok()?;
160    Some(pubkey_arr)
161}
162
163#[cfg(test)]
164mod tests {
165    use super::*;
166
167    #[test]
168    fn challenge_is_deterministic() {
169        let key = [0u8; 32];
170        let pubkey = [1u8; 32];
171        let c1 = device_challenge(&key, &pubkey);
172        let c2 = device_challenge(&key, &pubkey);
173        assert_eq!(c1, c2);
174    }
175
176    #[test]
177    fn challenge_differs_by_pubkey() {
178        let key = [0u8; 32];
179        let c1 = device_challenge(&key, &[1u8; 32]);
180        let c2 = device_challenge(&key, &[2u8; 32]);
181        assert_ne!(c1, c2);
182    }
183
184    #[test]
185    fn verify_roundtrip() {
186        use ed25519_dalek::{Signer, SigningKey};
187        let mut rng = rand::rngs::OsRng;
188        let sk = SigningKey::generate(&mut rng);
189        let pubkey = sk.verifying_key().to_bytes();
190        let challenge_key = derive_challenge_key(&[42u8; 32]);
191        let challenge = device_challenge(&challenge_key, &pubkey);
192        let sig = sk.sign(&challenge).to_bytes();
193        assert!(verify_device_enrollment(&challenge_key, &pubkey, &sig));
194    }
195
196    #[test]
197    fn verify_bad_sig_fails() {
198        let challenge_key = derive_challenge_key(&[0u8; 32]);
199        let pubkey = [0u8; 32];
200        let bad_sig = [0u8; 64];
201        assert!(!verify_device_enrollment(&challenge_key, &pubkey, &bad_sig));
202    }
203
204    #[test]
205    fn cookie_roundtrip() {
206        use ed25519_dalek::SigningKey;
207        let sk_bytes = [7u8; 32];
208        let pubkey = [1u8; 32];
209        let exp = chrono::Utc::now().timestamp() + 86400;
210
211        let cookie_seed = derive_cookie_key_seed(&sk_bytes);
212        let cookie_sk = SigningKey::from_bytes(&cookie_seed);
213        let kid = compute_kid(cookie_sk.verifying_key().as_bytes());
214        assert_eq!(kid.len(), 8, "kid must be 8 ASCII hex chars");
215
216        let cookie_val = encode_vault_device_cookie(&cookie_sk, &kid, &pubkey, exp);
217        let recovered = verify_vault_device_cookie(&sk_bytes, &cookie_val);
218        assert_eq!(recovered, Some(pubkey));
219    }
220
221    #[test]
222    fn cookie_expired_fails() {
223        use ed25519_dalek::SigningKey;
224        let sk_bytes = [7u8; 32];
225        let pubkey = [1u8; 32];
226        let exp = chrono::Utc::now().timestamp() - 1; // already expired
227
228        let cookie_seed = derive_cookie_key_seed(&sk_bytes);
229        let cookie_sk = SigningKey::from_bytes(&cookie_seed);
230        let kid = compute_kid(cookie_sk.verifying_key().as_bytes());
231        let cookie_val = encode_vault_device_cookie(&cookie_sk, &kid, &pubkey, exp);
232        assert!(verify_vault_device_cookie(&sk_bytes, &cookie_val).is_none());
233    }
234
235    #[test]
236    fn cookie_bad_sig_fails() {
237        use ed25519_dalek::SigningKey;
238        let sk_bytes = [7u8; 32];
239        let pubkey = [1u8; 32];
240        let exp = chrono::Utc::now().timestamp() + 86400;
241
242        let cookie_seed = derive_cookie_key_seed(&sk_bytes);
243        let cookie_sk = SigningKey::from_bytes(&cookie_seed);
244        let kid = compute_kid(cookie_sk.verifying_key().as_bytes());
245        let mut cookie_val = encode_vault_device_cookie(&cookie_sk, &kid, &pubkey, exp);
246        // Corrupt the last character to invalidate the signature
247        if let Some(last) = cookie_val.pop() {
248            cookie_val.push(if last == 'A' { 'B' } else { 'A' });
249        }
250        assert!(verify_vault_device_cookie(&sk_bytes, &cookie_val).is_none());
251    }
252}