OXYGENHUB

Coverage / crates/oxy-core/src/identity.rs 95.5%

489 of 512 lines run, 88 of 133 functions · run #250 on main · run missed

1
//! Identities and composite Ed25519 + ML-DSA-65 signatures (spec §14.2, §14.3).
2
//!
3
//! Both halves sign the same message, which binds the composite `KeyId`, and
4
//! verification requires both. A signature with either half missing, wrong,
5
//! or made for a different KeyId is invalid.
6
7
use crate::cbor::{self, Value};
8
use crate::hash::{hash_object, KeyId, ObjectRef, ObjectType};
9
use crate::objects::{
10
    array, bytes, check_version, field, oref, text, uint, ObjectError, FORMAT_VERSION,
11
};
12
use ed25519_dalek::ed25519::signature::Signer as _;
13
use ed25519_dalek::{
14
    Signature as EdSignature, SigningKey as EdSigningKey, VerifyingKey as EdVerifyingKey,
15
};
16
use ml_dsa::{
17
    EncodedSignature, EncodedVerifyingKey, MlDsa65, Seed, Signature as MlSignature,
18
    SigningKey as MlSigningKey, VerifyingKey as MlVerifyingKey,
19
};
20
use rand::RngCore;
21
22
pub const ED25519_PK_LEN: usize = 32;
23
pub const MLDSA65_PK_LEN: usize = 1952;
24
pub const ED25519_SIG_LEN: usize = 64;
25
pub const MLDSA65_SIG_LEN: usize = 3309;
26
/// `alg` value for Ed25519 + ML-DSA-65.
27
pub const ALG_COMPOSITE: u64 = 1;
28
29
/// What a delegate may do on the delegator's behalf (spec §14.2): a set of
30
/// `changes` (sign individual changes), `seal` (seal batches of them) and
31
/// `refs` (reference and tag attestations). An agent gets `changes` alone,
32
/// so it can never move a reference, whatever its owner may do.
33
#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
34
pub struct Scope(u8);
35
36
impl Scope {
37
    pub const NONE: Scope = Scope(0);
38
    pub const CHANGES: Scope = Scope(1);
39
    pub const REFS: Scope = Scope(2);
40
    pub const SEAL: Scope = Scope(4);
41
    /// Everything: what a delegate could do before scopes existed.
42
    pub const ALL: Scope = Scope(7);
43
    const NAMES: [(Scope, &'static str); 3] = [
44
        (Scope::CHANGES, "changes"),
45
        (Scope::REFS, "refs"),
46
        (Scope::SEAL, "seal"),
47
    ];
48
49593×
    pub fn has(self, other: Scope) -> bool {
50593×
        self.0 & other.0 == other.0
51593×
    }
5213×
    pub fn is_empty(self) -> bool {
5313×
        self.0 == 0
5413×
    }
55
    /// The names in the set, in the order they are written.
56182×
    pub fn names(self) -> Vec<&'static str> {
57182×
        Self::NAMES
58182×
            .iter()
59546×
            .filter(|(s, _)| self.has(*s))
60182×
            .map(|(_, n)| *n)
61182×
            .collect()
62182×
    }
63420×
    fn named(name: &str) -> Option<Scope> {
64420×
        Self::NAMES
65420×
            .iter()
66755×
            .find(|(_, n)| *n == name)
67420×
            .map(|(s, _)| *s)
68420×
    }
69
    /// `changes,refs` (also with spaces); `all` is every scope.
704×
    pub fn parse(s: &str) -> Result<Scope, String> {
714×
        let mut out = Scope::NONE;
725×
        for part in s.split(',').map(str::trim).filter(|p| !p.is_empty()) {
734×
            if part == "all" {
741×
                return Ok(Scope::ALL);
753×
            }
763×
            match Self::named(part) {
772×
                Some(sc) => out = out | sc,
781×
                None => return Err(format!("unknown scope {part:?}: use changes, refs or seal")),
79
            }
80
        }
812×
        if out.is_empty() {
821×
            return Err("a delegate needs at least one scope: changes, refs or seal".into());
831×
        }
841×
        Ok(out)
854×
    }
86
}
87
88
impl std::ops::BitOr for Scope {
89
    type Output = Scope;
90425×
    fn bitor(self, rhs: Scope) -> Scope {
91425×
        Scope(self.0 | rhs.0)
92425×
    }
93
}
94
95
impl std::fmt::Display for Scope {
9611×
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
9711×
        f.write_str(&self.names().join(","))
9811×
    }
99
}
100
101
impl std::fmt::Debug for Scope {
1020×
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1030×
        write!(f, "Scope({self})")
1040×
    }
105
}
106
107
/// A key allowed to act for an identity, within `scope`, until `expires`
108
/// (wall milliseconds; `None` for as long as the delegation stands).
109
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
110
pub struct Delegate {
111
    pub key: KeyId,
112
    pub scope: Scope,
113
    pub expires: Option<u64>,
114
}
115
116
impl Delegate {
117
    /// A delegate with every scope and no expiry of its own.
1184×
    pub fn full(key: KeyId) -> Delegate {
1194×
        Delegate {
1204×
            key,
1214×
            scope: Scope::ALL,
1224×
            expires: None,
1234×
        }
1244×
    }
125
    /// Whether the delegation covers `scope` at `at_ms`.
12628×
    pub fn allows(&self, scope: Scope, at_ms: u64) -> bool {
12728×
        self.scope.has(scope) && !self.expires.is_some_and(|e| at_ms > e)
12828×
    }
129171×
    fn to_value(self) -> Value {
130171×
        Value::map([
131171×
            (0, Value::Bytes(self.key.0.to_vec())),
132
            (
133
                1,
134
                Value::Array(
135171×
                    self.scope
136171×
                        .names()
137171×
                        .into_iter()
138400×
                        .map(|n| Value::Text(n.to_string()))
139171×
                        .collect(),
140
                ),
141
            ),
142171×
            (2, self.expires.map(Value::Uint).unwrap_or(Value::Null)),
143
        ])
144171×
    }
145
    /// An entry, or a bare KeyId as identities carried before scopes
146
    /// existed, which meant every scope.
147187×
    fn from_value(v: &Value) -> Result<Delegate, ObjectError> {
148187×
        if let Value::Bytes(_) = v {
1491×
            return Ok(Delegate::full(oref(v, "delegate")?));
150186×
        }
151186×
        let m = v
152186×
            .as_map()
153186×
            .ok_or_else(|| ObjectError::Schema("delegate: expected map".into()))?;
154186×
        let key = oref(field(m, 0, "delegate key")?, "delegate key")?;
155186×
        let mut scope = Scope::NONE;
156417×
        for n in array(field(m, 1, "delegate scope")?, "delegate scope")? {
157417×
            let n = text(n, "delegate scope")?;
158417×
            scope = scope
159417×
                | Scope::named(n)
160417×
                    .ok_or_else(|| ObjectError::Schema(format!("delegate: unknown scope {n:?}")))?;
161
        }
162186×
        let expires = match field(m, 2, "delegate expires")? {
163186×
            v if v.is_null() => None,
1645×
            v => Some(uint(v, "delegate expires")?),
165
        };
166186×
        Ok(Delegate {
167186×
            key,
168186×
            scope,
169186×
            expires,
170186×
        })
171187×
    }
172
}
173
174
#[derive(Clone, Debug, PartialEq, Eq)]
175
pub struct Identity {
176
    pub ed25519_pk: [u8; ED25519_PK_LEN],
177
    pub mldsa65_pk: Vec<u8>,
178
    pub name: String,
179
    pub email: String,
180
    pub created: u64,
181
    pub expires: Option<u64>,
182
    pub previous: Option<KeyId>,
183
    pub delegates: Vec<Delegate>,
184
}
185
186
/// Sorted by key, one entry per key.
1871429×
fn tidy(mut delegates: Vec<Delegate>) -> Vec<Delegate> {
1881429×
    delegates.sort_by_key(|d| d.key);
1891429×
    delegates.dedup_by(|a, b| a.key == b.key);
1901429×
    delegates
1911429×
}
192
193
impl Identity {
194
    /// The delegation to `key`, if any.
19557×
    pub fn delegate(&self, key: &KeyId) -> Option<&Delegate> {
19657×
        self.delegates.iter().find(|d| d.key == *key)
19757×
    }
198
    /// Whether `key` may act for this identity within `scope` at `at_ms`.
19914×
    pub fn delegates_to(&self, key: &KeyId, scope: Scope, at_ms: u64) -> bool {
20014×
        self.delegate(key).is_some_and(|d| d.allows(scope, at_ms))
20114×
    }
2021382×
    pub fn to_value(&self) -> Value {
2031382×
        Value::map([
2041382×
            (0, Value::Uint(FORMAT_VERSION)),
2051382×
            (1, Value::Bytes(self.ed25519_pk.to_vec())),
2061382×
            (2, Value::Bytes(self.mldsa65_pk.clone())),
2071382×
            (3, Value::Text(self.name.clone())),
2081382×
            (4, Value::Text(self.email.clone())),
2091382×
            (5, Value::Uint(self.created)),
2101382×
            (6, self.expires.map(Value::Uint).unwrap_or(Value::Null)),
211
            (
212
                7,
2131382×
                self.previous
2141382×
                    .map(|p| Value::Bytes(p.0.to_vec()))
2151382×
                    .unwrap_or(Value::Null),
216
            ),
217
            (
218
                8,
2191382×
                Value::Array(self.delegates.iter().map(|d| d.to_value()).collect()),
220
            ),
221
        ])
2221382×
    }
2231381×
    pub fn encode(&self) -> Vec<u8> {
2241381×
        cbor::encode(&self.to_value())
2251381×
    }
226724×
    pub fn hash(&self) -> KeyId {
227724×
        hash_object(ObjectType::Identity, &self.encode())
228724×
    }
2291417×
    pub fn decode(b: &[u8]) -> Result<Identity, ObjectError> {
2301417×
        let v = cbor::decode(b)?;
2311417×
        let m = v
2321417×
            .as_map()
2331417×
            .ok_or_else(|| ObjectError::Schema("identity: expected map".into()))?;
2341417×
        check_version(m)?;
2351417×
        let ed = bytes(field(m, 1, "ed25519_pk")?, "ed25519_pk")?;
2361417×
        let ml = bytes(field(m, 2, "mldsa65_pk")?, "mldsa65_pk")?;
2371417×
        if ed.len() != ED25519_PK_LEN || ml.len() != MLDSA65_PK_LEN {
2380×
            return Err(ObjectError::Schema(
2390×
                "identity: wrong public key length".into(),
2400×
            ));
2411417×
        }
2421417×
        let opt_u = |v: &Value| -> Result<Option<u64>, ObjectError> {
2431417×
            if v.is_null() {
2441413×
                Ok(None)
245
            } else {
2464×
                uint(v, "expires").map(Some)
247
            }
2481417×
        };
2491417×
        let opt_r = |v: &Value| -> Result<Option<KeyId>, ObjectError> {
2501417×
            if v.is_null() {
2511018×
                Ok(None)
252
            } else {
253399×
                oref(v, "previous").map(Some)
254
            }
2551417×
        };
2561417×
        let delegates = tidy(
2571417×
            array(field(m, 8, "delegates")?, "delegates")?
2581417×
                .iter()
2591417×
                .map(Delegate::from_value)
2601417×
                .collect::<Result<Vec<_>, _>>()?,
261
        );
262
        Ok(Identity {
2631417×
            ed25519_pk: ed.try_into().unwrap(),
2641417×
            mldsa65_pk: ml.to_vec(),
2651417×
            name: text(field(m, 3, "name")?, "name")?.to_owned(),
2661417×
            email: text(field(m, 4, "email")?, "email")?.to_owned(),
2671417×
            created: uint(field(m, 5, "created")?, "created")?,
2681417×
            expires: opt_u(field(m, 6, "expires")?)?,
2691417×
            previous: opt_r(field(m, 7, "previous")?)?,
2701417×
            delegates,
271
        })
2721417×
    }
273
274
    /// Whether the identity is past its expiry at `now_ms`.
275213×
    pub fn is_expired_at(&self, now_ms: u64) -> bool {
276213×
        self.expires.is_some_and(|e| now_ms > e)
277213×
    }
278
279
    /// A successor identity with the same keys, `previous` set to this
280
    /// identity's KeyId, and the given delegates and expiry (spec §14.2).
28112×
    pub fn successor(
28212×
        &self,
28312×
        delegates: Vec<Delegate>,
28412×
        expires: Option<u64>,
28512×
        created: u64,
28612×
    ) -> Identity {
28712×
        Identity {
28812×
            previous: Some(self.hash()),
28912×
            delegates: tidy(delegates),
29012×
            expires,
29112×
            created,
29212×
            ..self.clone()
29312×
        }
29412×
    }
295
296427×
    fn ed_key(&self) -> Result<EdVerifyingKey, VerifyError> {
297427×
        EdVerifyingKey::from_bytes(&self.ed25519_pk).map_err(|_| VerifyError::BadKey)
298427×
    }
299419×
    fn ml_key(&self) -> Result<MlVerifyingKey<MlDsa65>, VerifyError> {
300419×
        let enc = EncodedVerifyingKey::<MlDsa65>::try_from(self.mldsa65_pk.as_slice())
301419×
            .map_err(|_| VerifyError::BadKey)?;
302419×
        Ok(MlVerifyingKey::decode(&enc))
303419×
    }
304
}
305
306
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
307
pub enum Domain {
308
    Change,
309
    Attest,
310
    Policy,
311
    /// A server-issued challenge, proving possession of a key to a host
312
    /// (hub spec §5.3, §5.4). Never a stored object.
313
    Challenge,
314
}
315
316
impl Domain {
317678×
    pub fn name(self) -> &'static str {
318678×
        match self {
319147×
            Domain::Change => "change",
320428×
            Domain::Attest => "attest",
321100×
            Domain::Policy => "policy",
3223×
            Domain::Challenge => "challenge",
323
        }
324678×
    }
325
}
326
327
/// `"oxy1 sig " || domain || 0x00 || KeyId || target` (spec §14.3).
328678×
pub fn signing_message(domain: Domain, key: &KeyId, target: &ObjectRef) -> Vec<u8> {
329678×
    let mut m = Vec::with_capacity(80);
330678×
    m.extend_from_slice(b"oxy1 sig ");
331678×
    m.extend_from_slice(domain.name().as_bytes());
332678×
    m.push(0);
333678×
    m.extend_from_slice(&key.0);
334678×
    m.extend_from_slice(&target.0);
335678×
    m
336678×
}
337
338
#[derive(Clone, PartialEq, Eq)]
339
pub struct Signature {
340
    pub key: KeyId,
341
    pub ed: [u8; ED25519_SIG_LEN],
342
    pub ml: Vec<u8>,
343
}
344
345
impl std::fmt::Debug for Signature {
3460×
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
3470×
        write!(f, "Signature(key {:?})", self.key)
3480×
    }
349
}
350
351
impl Signature {
352498×
    pub fn to_value(&self) -> Value {
353498×
        Value::map([
354498×
            (0, Value::Bytes(self.key.0.to_vec())),
355498×
            (1, Value::Uint(ALG_COMPOSITE)),
356498×
            (2, Value::Bytes(self.ed.to_vec())),
357498×
            (3, Value::Bytes(self.ml.clone())),
358498×
        ])
359498×
    }
3601234×
    pub fn from_value(v: &Value) -> Result<Signature, ObjectError> {
3611234×
        let m = v
3621234×
            .as_map()
3631234×
            .ok_or_else(|| ObjectError::Schema("signature: expected map".into()))?;
3641234×
        let alg = uint(field(m, 1, "alg")?, "alg")?;
3651234×
        if alg != ALG_COMPOSITE {
3660×
            return Err(ObjectError::Schema(format!(
3670×
                "unknown signature algorithm {alg}"
3680×
            )));
3691234×
        }
3701234×
        let ed = bytes(field(m, 2, "ed")?, "ed")?;
3711234×
        let ml = bytes(field(m, 3, "ml")?, "ml")?;
3721234×
        if ed.len() != ED25519_SIG_LEN || ml.len() != MLDSA65_SIG_LEN {
3731×
            return Err(ObjectError::Schema("signature: wrong length".into()));
3741233×
        }
375
        Ok(Signature {
3761233×
            key: oref(field(m, 0, "key")?, "key")?,
3771233×
            ed: ed.try_into().unwrap(),
3781233×
            ml: ml.to_vec(),
379
        })
3801234×
    }
381463×
    pub fn encode_list(sigs: &[Signature]) -> Vec<u8> {
382463×
        cbor::encode(&Value::Array(sigs.iter().map(|s| s.to_value()).collect()))
383463×
    }
3841183×
    pub fn decode_list(b: &[u8]) -> Result<Vec<Signature>, ObjectError> {
3851183×
        let v = cbor::decode(b)?;
3861183×
        array(&v, "signatures")?
3871183×
            .iter()
3881183×
            .map(Signature::from_value)
3891183×
            .collect()
3901183×
    }
391
}
392
393
#[derive(Clone, Copy, Debug, PartialEq, Eq, thiserror::Error)]
394
pub enum VerifyError {
395
    #[error("signature names a different key than the identity")]
396
    KeyMismatch,
397
    #[error("identity holds a malformed public key")]
398
    BadKey,
399
    #[error("Ed25519 signature invalid")]
400
    Ed25519,
401
    #[error("ML-DSA-65 signature invalid")]
402
    MlDsa,
403
    #[error("a challenge is at least 16 bytes")]
404
    ShortChallenge,
405
}
406
407
/// Verify a composite signature by `identity` over `target` (spec §14.3).
408428×
pub fn verify(
409428×
    identity: &Identity,
410428×
    sig: &Signature,
411428×
    domain: Domain,
412428×
    target: &ObjectRef,
413428×
) -> Result<(), VerifyError> {
414428×
    let key = identity.hash();
415428×
    if sig.key != key {
4161×
        return Err(VerifyError::KeyMismatch);
417427×
    }
418427×
    let msg = signing_message(domain, &key, target);
419427×
    let ed_sig = EdSignature::from_bytes(&sig.ed);
420427×
    identity
421427×
        .ed_key()?
422427×
        .verify_strict(&msg, &ed_sig)
423427×
        .map_err(|_| VerifyError::Ed25519)?;
424420×
    let enc =
425420×
        EncodedSignature::<MlDsa65>::try_from(sig.ml.as_slice()).map_err(|_| VerifyError::MlDsa)?;
426420×
    let ml_sig = MlSignature::<MlDsa65>::decode(&enc).ok_or(VerifyError::MlDsa)?;
427419×
    if !identity.ml_key()?.verify_with_context(&msg, b"", &ml_sig) {
4280×
        return Err(VerifyError::MlDsa);
429419×
    }
430419×
    Ok(())
431428×
}
432
433
/// The seeds of a composite key pair. Stored only in the user's key directory.
434
#[derive(Clone)]
435
pub struct SecretKey {
436
    pub ed_seed: [u8; 32],
437
    pub ml_seed: [u8; 32],
438
}
439
440
impl std::fmt::Debug for SecretKey {
4410×
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
4420×
        f.write_str("SecretKey(..)")
4430×
    }
444
}
445
446
impl SecretKey {
44767×
    pub fn generate() -> SecretKey {
44867×
        let mut ed_seed = [0u8; 32];
44967×
        let mut ml_seed = [0u8; 32];
45067×
        rand::rngs::OsRng.fill_bytes(&mut ed_seed);
45167×
        rand::rngs::OsRng.fill_bytes(&mut ml_seed);
45267×
        SecretKey { ed_seed, ml_seed }
45367×
    }
454
455336×
    fn ed(&self) -> EdSigningKey {
456336×
        EdSigningKey::from_bytes(&self.ed_seed)
457336×
    }
458336×
    fn ml(&self) -> MlSigningKey<MlDsa65> {
459336×
        MlSigningKey::from_seed(&Seed::from(self.ml_seed))
460336×
    }
461
462
    /// The identity object for these keys.
46385×
    pub fn identity(&self, name: &str, email: &str, created: u64) -> Identity {
46485×
        Identity {
46585×
            ed25519_pk: self.ed().verifying_key().to_bytes(),
46685×
            mldsa65_pk: self
46785×
                .ml()
46885×
                .expanded_key()
46985×
                .verifying_key()
47085×
                .encode()
47185×
                .as_slice()
47285×
                .to_vec(),
47385×
            name: name.into(),
47485×
            email: email.into(),
47585×
            created,
47685×
            expires: None,
47785×
            previous: None,
47885×
            delegates: vec![],
47985×
        }
48085×
    }
481
482251×
    pub fn sign(&self, domain: Domain, key: &KeyId, target: &ObjectRef) -> Signature {
483251×
        let msg = signing_message(domain, key, target);
484251×
        let ed = self.ed().sign(&msg).to_bytes();
485251×
        let ml = self
486251×
            .ml()
487251×
            .expanded_key()
488251×
            .sign_deterministic(&msg, b"")
489251×
            .expect("empty context is valid")
490251×
            .encode()
491251×
            .as_slice()
492251×
            .to_vec();
493251×
        Signature { key: *key, ed, ml }
494251×
    }
495
49657×
    pub fn encode(&self, key: &KeyId) -> Vec<u8> {
49757×
        cbor::encode(&Value::map([
49857×
            (0, Value::Uint(FORMAT_VERSION)),
49957×
            (1, Value::Bytes(key.0.to_vec())),
50057×
            (2, Value::Bytes(self.ed_seed.to_vec())),
50157×
            (3, Value::Bytes(self.ml_seed.to_vec())),
50257×
        ]))
50357×
    }
504
505371×
    pub fn decode(b: &[u8]) -> Result<(KeyId, SecretKey), ObjectError> {
506371×
        let v = cbor::decode(b)?;
507371×
        let m = v
508371×
            .as_map()
509371×
            .ok_or_else(|| ObjectError::Schema("secret key: expected map".into()))?;
510371×
        check_version(m)?;
511742×
        let seed = |k: u64| -> Result<[u8; 32], ObjectError> {
512742×
            bytes(field(m, k, "seed")?, "seed")?
513742×
                .try_into()
514742×
                .map_err(|_| ObjectError::Schema("seed: expected 32 bytes".into()))
515742×
        };
516
        Ok((
517371×
            oref(field(m, 1, "key")?, "key")?,
518
            SecretKey {
519371×
                ed_seed: seed(2)?,
520371×
                ml_seed: seed(3)?,
521
            },
522
        ))
523371×
    }
524
}
525
526
#[cfg(test)]
527
mod tests {
528
    use super::*;
529
5306×
    fn fixed_key() -> SecretKey {
5316×
        SecretKey {
5326×
            ed_seed: [1; 32],
5336×
            ml_seed: [2; 32],
5346×
        }
5356×
    }
536
537
    #[test]
5381×
    fn identity_round_trip_and_sizes() {
5391×
        let sk = fixed_key();
5401×
        let id = sk.identity("Ada", "[email protected]", 1_700_000_000_000);
5411×
        assert_eq!(id.mldsa65_pk.len(), MLDSA65_PK_LEN);
5421×
        let d = Identity::decode(&id.encode()).unwrap();
5431×
        assert_eq!(d, id);
5441×
        assert_eq!(d.hash(), id.hash());
545
        // Deterministic from seeds.
5461×
        assert_eq!(
5471×
            fixed_key()
5481×
                .identity("Ada", "[email protected]", 1_700_000_000_000)
5491×
                .hash(),
5501×
            id.hash()
551
        );
5521×
        let mut other = id.clone();
5531×
        other.delegates.push(Delegate::full(ObjectRef([9; 32])));
5541×
        assert_ne!(other.hash(), id.hash());
5551×
    }
556
557
    #[test]
5581×
    fn delegates_carry_scope_and_expiry_and_bare_keys_mean_every_scope() {
5591×
        let sk = fixed_key();
5601×
        let mut id = sk.identity("Ada", "[email protected]", 1_700_000_000_000);
5611×
        let agent = ObjectRef([7; 32]);
5621×
        let host = ObjectRef([3; 32]);
5631×
        id.delegates = vec![
5641×
            Delegate {
5651×
                key: agent,
5661×
                scope: Scope::CHANGES,
5671×
                expires: Some(2_000),
5681×
            },
5691×
            Delegate {
5701×
                key: host,
5711×
                scope: Scope::CHANGES | Scope::REFS,
5721×
                expires: None,
5731×
            },
574
        ];
5751×
        let d = Identity::decode(&id.encode()).unwrap();
5761×
        assert_eq!(d.delegates.len(), 2);
5771×
        assert!(d.delegates_to(&agent, Scope::CHANGES, 1_000));
5781×
        assert!(!d.delegates_to(&agent, Scope::CHANGES, 2_001), "expired");
5791×
        assert!(!d.delegates_to(&agent, Scope::REFS, 1_000));
5801×
        assert!(!d.delegates_to(&agent, Scope::SEAL, 1_000));
5811×
        assert!(d.delegates_to(&host, Scope::REFS, u64::MAX));
5821×
        assert!(!d.delegates_to(&host, Scope::SEAL, 0));
5831×
        assert!(!d.delegates_to(&ObjectRef([1; 32]), Scope::CHANGES, 0));
5841×
        assert_eq!(
5851×
            Scope::parse("changes, refs").unwrap(),
5861×
            Scope::CHANGES | Scope::REFS
587
        );
5881×
        assert_eq!(Scope::parse("all").unwrap(), Scope::ALL);
5891×
        assert_eq!((Scope::CHANGES | Scope::SEAL).to_string(), "changes,seal");
5901×
        assert!(Scope::parse("push").is_err() && Scope::parse("").is_err());
591
        // An identity written before scopes existed lists bare KeyIds.
5921×
        let mut v = id.to_value();
5931×
        if let Value::Map(m) = &mut v {
5941×
            m.insert(8, Value::Array(vec![Value::Bytes(host.0.to_vec())]));
5951×
        }
5961×
        let old = Identity::decode(&cbor::encode(&v)).unwrap();
5971×
        assert_eq!(old.delegates, vec![Delegate::full(host)]);
5981×
        assert!(old.delegates_to(&host, Scope::ALL, u64::MAX));
5991×
    }
600
601
    #[test]
6021×
    fn sign_and_verify() {
6031×
        let sk = fixed_key();
6041×
        let id = sk.identity("Ada", "[email protected]", 1);
6051×
        let key = id.hash();
6061×
        let target = ObjectRef([7; 32]);
6071×
        let sig = sk.sign(Domain::Change, &key, &target);
6081×
        assert_eq!(sig.ml.len(), MLDSA65_SIG_LEN);
6091×
        assert_eq!(verify(&id, &sig, Domain::Change, &target), Ok(()));
610
        // Different target, different domain: invalid.
6111×
        assert_eq!(
6121×
            verify(&id, &sig, Domain::Change, &ObjectRef([8; 32])),
613
            Err(VerifyError::Ed25519)
614
        );
6151×
        assert_eq!(
6161×
            verify(&id, &sig, Domain::Attest, &target),
617
            Err(VerifyError::Ed25519)
618
        );
619
        // Deterministic signatures.
6201×
        assert_eq!(sk.sign(Domain::Change, &key, &target), sig);
621
        // Signature list round trip.
6221×
        let l =
6231×
            Signature::decode_list(&Signature::encode_list(std::slice::from_ref(&sig))).unwrap();
6241×
        assert_eq!(l, vec![sig]);
6251×
    }
626
627
    #[test]
6281×
    fn stripping_or_forging_either_half_fails() {
6291×
        let sk = fixed_key();
6301×
        let id = sk.identity("Ada", "a@b", 1);
6311×
        let key = id.hash();
6321×
        let target = ObjectRef([7; 32]);
6331×
        let good = sk.sign(Domain::Change, &key, &target);
634
6351×
        let mut no_ml = good.clone();
6361×
        no_ml.ml = vec![0; MLDSA65_SIG_LEN];
6371×
        assert_eq!(
6381×
            verify(&id, &no_ml, Domain::Change, &target),
639
            Err(VerifyError::MlDsa)
640
        );
641
6421×
        let mut bad_ed = good.clone();
6431×
        bad_ed.ed[10] ^= 1;
6441×
        assert_eq!(
6451×
            verify(&id, &bad_ed, Domain::Change, &target),
646
            Err(VerifyError::Ed25519)
647
        );
648
649
        // A signature made for another KeyId over the same target does not transfer.
6501×
        let other = SecretKey {
6511×
            ed_seed: [3; 32],
6521×
            ml_seed: [4; 32],
6531×
        };
6541×
        let other_id = other.identity("Bob", "b@b", 1);
6551×
        let theirs = other.sign(Domain::Change, &other_id.hash(), &target);
6561×
        assert_eq!(
6571×
            verify(&id, &theirs, Domain::Change, &target),
658
            Err(VerifyError::KeyMismatch)
659
        );
6601×
        let mut relabelled = theirs.clone();
6611×
        relabelled.key = key;
6621×
        assert_eq!(
6631×
            verify(&id, &relabelled, Domain::Change, &target),
664
            Err(VerifyError::Ed25519)
665
        );
666
667
        // Wrong length is rejected at decode time.
6681×
        let mut short = good.to_value();
6691×
        if let Value::Map(m) = &mut short {
6701×
            m.insert(3, Value::Bytes(vec![0; 10]));
6711×
        }
6721×
        assert!(Signature::from_value(&short).is_err());
6731×
    }
674
675
    #[test]
6761×
    fn secret_key_round_trip() {
6771×
        let sk = fixed_key();
6781×
        let key = sk.identity("x", "y", 0).hash();
6791×
        let (k, d) = SecretKey::decode(&sk.encode(&key)).unwrap();
6801×
        assert_eq!(k, key);
6811×
        assert_eq!(d.ed_seed, sk.ed_seed);
6821×
        assert_eq!(d.ml_seed, sk.ml_seed);
6831×
        assert_ne!(SecretKey::generate().ed_seed, SecretKey::generate().ed_seed);
6841×
    }
685
}
686
687
/// The signing target of a challenge: `BLAKE3-256("oxy1 challenge " || bytes)`,
688
/// so a challenge can never collide with a stored object's reference.
6894×
pub fn challenge_target(challenge: &[u8]) -> ObjectRef {
6904×
    let mut h = blake3::Hasher::new();
6914×
    h.update(b"oxy1 challenge ");
6924×
    h.update(challenge);
6934×
    ObjectRef(*h.finalize().as_bytes())
6944×
}
695
696
impl SecretKey {
697
    /// Sign a host's challenge (at least 16 bytes) with this key.
6982×
    pub fn sign_challenge(&self, key: &KeyId, challenge: &[u8]) -> Result<Signature, VerifyError> {
6992×
        if challenge.len() < 16 {
7001×
            return Err(VerifyError::ShortChallenge);
7011×
        }
7021×
        Ok(self.sign(Domain::Challenge, key, &challenge_target(challenge)))
7032×
    }
704
}
705
706
/// Check a challenge signature against the identity that claims it.
7073×
pub fn verify_challenge(
7083×
    identity: &Identity,
7093×
    sig: &Signature,
7103×
    challenge: &[u8],
7113×
) -> Result<(), VerifyError> {
7123×
    if challenge.len() < 16 {
7130×
        return Err(VerifyError::ShortChallenge);
7143×
    }
7153×
    if sig.key != identity.hash() {
7161×
        return Err(VerifyError::KeyMismatch);
7172×
    }
7182×
    verify(
7192×
        identity,
7202×
        sig,
7212×
        Domain::Challenge,
7222×
        &challenge_target(challenge),
723
    )
7243×
}
725
726
#[cfg(test)]
727
mod challenge_tests {
728
    use super::*;
729
730
    #[test]
7311×
    fn a_challenge_signature_binds_key_and_bytes() {
7321×
        let sk = SecretKey::generate();
7331×
        let id = sk.identity("A", "a@example", 1);
7341×
        let key = id.hash();
7351×
        let challenge = [7u8; 32];
7361×
        let sig = sk.sign_challenge(&key, &challenge).unwrap();
7371×
        assert!(verify_challenge(&id, &sig, &challenge).is_ok());
7381×
        assert!(
7391×
            verify_challenge(&id, &sig, &[8u8; 32]).is_err(),
740
            "other bytes"
741
        );
7421×
        let other = SecretKey::generate().identity("B", "b@example", 1);
7431×
        assert!(
7441×
            verify_challenge(&other, &sig, &challenge).is_err(),
745
            "other identity"
746
        );
7471×
        assert!(sk.sign_challenge(&key, b"short").is_err());
748
        // A challenge target never equals a change signature's target for the same bytes.
7491×
        assert_ne!(challenge_target(&challenge), ObjectRef(challenge));
7501×
    }
751
}