OXYGENHUB

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

501 of 524 lines run, 103 of 137 functions · run #427 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
492073×
    pub fn has(self, other: Scope) -> bool {
502073×
        self.0 & other.0 == other.0
512073×
    }
52199×
    pub fn is_empty(self) -> bool {
53199×
        self.0 == 0
54199×
    }
55
    /// The names in the set, in the order they are written.
56628×
    pub fn names(self) -> Vec<&'static str> {
57628×
        Self::NAMES
58628×
            .iter()
591884×
            .filter(|(s, _)| self.has(*s))
60628×
            .map(|(_, n)| *n)
61628×
            .collect()
62628×
    }
631579×
    pub(crate) fn named(name: &str) -> Option<Scope> {
641579×
        Self::NAMES
651579×
            .iter()
662579×
            .find(|(_, n)| *n == name)
671579×
            .map(|(s, _)| *s)
681579×
    }
69
    /// `changes,refs` (also with spaces); `all` is every scope.
705×
    pub fn parse(s: &str) -> Result<Scope, String> {
715×
        let mut out = Scope::NONE;
726×
        for part in s.split(',').map(str::trim).filter(|p| !p.is_empty()) {
735×
            if part == "all" {
741×
                return Ok(Scope::ALL);
754×
            }
764×
            match Self::named(part) {
773×
                Some(sc) => out = out | sc,
781×
                None => return Err(format!("unknown scope {part:?}: use changes, refs or seal")),
79
            }
80
        }
813×
        if out.is_empty() {
821×
            return Err("a delegate needs at least one scope: changes, refs or seal".into());
832×
        }
842×
        Ok(out)
855×
    }
86
}
87
88
impl std::ops::BitOr for Scope {
89
    type Output = Scope;
901627×
    fn bitor(self, rhs: Scope) -> Scope {
911627×
        Scope(self.0 | rhs.0)
921627×
    }
93
}
94
95
impl std::fmt::Display for Scope {
9615×
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
9715×
        f.write_str(&self.names().join(","))
9815×
    }
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`.
12633×
    pub fn allows(&self, scope: Scope, at_ms: u64) -> bool {
12733×
        self.scope.has(scope) && !self.expires.is_some_and(|e| at_ms > e)
12833×
    }
129227×
    fn to_value(self) -> Value {
130227×
        Value::map([
131227×
            (0, Value::Bytes(self.key.0.to_vec())),
132
            (
133
                1,
134
                Value::Array(
135227×
                    self.scope
136227×
                        .names()
137227×
                        .into_iter()
138507×
                        .map(|n| Value::Text(n.to_string()))
139227×
                        .collect(),
140
                ),
141
            ),
142227×
            (2, self.expires.map(Value::Uint).unwrap_or(Value::Null)),
143
        ])
144227×
    }
145
    /// An entry, or a bare KeyId as identities carried before scopes
146
    /// existed, which meant every scope.
147249×
    fn from_value(v: &Value) -> Result<Delegate, ObjectError> {
148249×
        if let Value::Bytes(_) = v {
1491×
            return Ok(Delegate::full(oref(v, "delegate")?));
150248×
        }
151248×
        let m = v
152248×
            .as_map()
153248×
            .ok_or_else(|| ObjectError::Schema("delegate: expected map".into()))?;
154248×
        let key = oref(field(m, 0, "delegate key")?, "delegate key")?;
155248×
        let mut scope = Scope::NONE;
156534×
        for n in array(field(m, 1, "delegate scope")?, "delegate scope")? {
157534×
            let n = text(n, "delegate scope")?;
158534×
            scope = scope
159534×
                | Scope::named(n)
160534×
                    .ok_or_else(|| ObjectError::Schema(format!("delegate: unknown scope {n:?}")))?;
161
        }
162248×
        let expires = match field(m, 2, "delegate expires")? {
163248×
            v if v.is_null() => None,
1646×
            v => Some(uint(v, "delegate expires")?),
165
        };
166248×
        Ok(Delegate {
167248×
            key,
168248×
            scope,
169248×
            expires,
170248×
        })
171249×
    }
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.
1873339×
fn tidy(mut delegates: Vec<Delegate>) -> Vec<Delegate> {
1883339×
    delegates.sort_by_key(|d| d.key);
1893339×
    delegates.dedup_by(|a, b| a.key == b.key);
1903339×
    delegates
1913339×
}
192
193
impl Identity {
194
    /// The delegation to `key`, if any.
195136×
    pub fn delegate(&self, key: &KeyId) -> Option<&Delegate> {
196136×
        self.delegates.iter().find(|d| d.key == *key)
197136×
    }
198
    /// Whether `key` may act for this identity within `scope` at `at_ms`.
19980×
    pub fn delegates_to(&self, key: &KeyId, scope: Scope, at_ms: u64) -> bool {
20080×
        self.delegate(key).is_some_and(|d| d.allows(scope, at_ms))
20180×
    }
2023775×
    pub fn to_value(&self) -> Value {
2033775×
        Value::map([
2043775×
            (0, Value::Uint(FORMAT_VERSION)),
2053775×
            (1, Value::Bytes(self.ed25519_pk.to_vec())),
2063775×
            (2, Value::Bytes(self.mldsa65_pk.clone())),
2073775×
            (3, Value::Text(self.name.clone())),
2083775×
            (4, Value::Text(self.email.clone())),
2093775×
            (5, Value::Uint(self.created)),
2103775×
            (6, self.expires.map(Value::Uint).unwrap_or(Value::Null)),
211
            (
212
                7,
2133775×
                self.previous
2143775×
                    .map(|p| Value::Bytes(p.0.to_vec()))
2153775×
                    .unwrap_or(Value::Null),
216
            ),
217
            (
218
                8,
2193775×
                Value::Array(self.delegates.iter().map(|d| d.to_value()).collect()),
220
            ),
221
        ])
2223775×
    }
2233774×
    pub fn encode(&self) -> Vec<u8> {
2243774×
        cbor::encode(&self.to_value())
2253774×
    }
2261922×
    pub fn hash(&self) -> KeyId {
2271922×
        hash_object(ObjectType::Identity, &self.encode())
2281922×
    }
2293323×
    pub fn decode(b: &[u8]) -> Result<Identity, ObjectError> {
2303323×
        let v = cbor::decode(b)?;
2313323×
        let m = v
2323323×
            .as_map()
2333323×
            .ok_or_else(|| ObjectError::Schema("identity: expected map".into()))?;
2343323×
        check_version(m)?;
2353323×
        let ed = bytes(field(m, 1, "ed25519_pk")?, "ed25519_pk")?;
2363323×
        let ml = bytes(field(m, 2, "mldsa65_pk")?, "mldsa65_pk")?;
2373323×
        if ed.len() != ED25519_PK_LEN || ml.len() != MLDSA65_PK_LEN {
2380×
            return Err(ObjectError::Schema(
2390×
                "identity: wrong public key length".into(),
2400×
            ));
2413323×
        }
2423323×
        let opt_u = |v: &Value| -> Result<Option<u64>, ObjectError> {
2433323×
            if v.is_null() {
2443318×
                Ok(None)
245
            } else {
2465×
                uint(v, "expires").map(Some)
247
            }
2483323×
        };
2493323×
        let opt_r = |v: &Value| -> Result<Option<KeyId>, ObjectError> {
2503323×
            if v.is_null() {
2512811×
                Ok(None)
252
            } else {
253512×
                oref(v, "previous").map(Some)
254
            }
2553323×
        };
2563323×
        let delegates = tidy(
2573323×
            array(field(m, 8, "delegates")?, "delegates")?
2583323×
                .iter()
2593323×
                .map(Delegate::from_value)
2603323×
                .collect::<Result<Vec<_>, _>>()?,
261
        );
262
        Ok(Identity {
2633323×
            ed25519_pk: ed.try_into().unwrap(),
2643323×
            mldsa65_pk: ml.to_vec(),
2653323×
            name: text(field(m, 3, "name")?, "name")?.to_owned(),
2663323×
            email: text(field(m, 4, "email")?, "email")?.to_owned(),
2673323×
            created: uint(field(m, 5, "created")?, "created")?,
2683323×
            expires: opt_u(field(m, 6, "expires")?)?,
2693323×
            previous: opt_r(field(m, 7, "previous")?)?,
2703323×
            delegates,
271
        })
2723323×
    }
273
274
    /// Whether the identity is past its expiry at `now_ms`.
275251×
    pub fn is_expired_at(&self, now_ms: u64) -> bool {
276251×
        self.expires.is_some_and(|e| now_ms > e)
277251×
    }
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).
28116×
    pub fn successor(
28216×
        &self,
28316×
        delegates: Vec<Delegate>,
28416×
        expires: Option<u64>,
28516×
        created: u64,
28616×
    ) -> Identity {
28716×
        Identity {
28816×
            previous: Some(self.hash()),
28916×
            delegates: tidy(delegates),
29016×
            expires,
29116×
            created,
29216×
            ..self.clone()
29316×
        }
29416×
    }
295
296
    /// Check a [`SecretKey::sign_ed25519`] signature by this identity.
29749×
    pub fn verify_ed25519(&self, msg: &[u8], sig: &[u8]) -> Result<(), VerifyError> {
29849×
        let sig = EdSignature::from_slice(sig).map_err(|_| VerifyError::Ed25519)?;
29949×
        self.ed_key()?
30049×
            .verify_strict(msg, &sig)
30149×
            .map_err(|_| VerifyError::Ed25519)
30249×
    }
303
304920×
    fn ed_key(&self) -> Result<EdVerifyingKey, VerifyError> {
305920×
        EdVerifyingKey::from_bytes(&self.ed25519_pk).map_err(|_| VerifyError::BadKey)
306920×
    }
307851×
    fn ml_key(&self) -> Result<MlVerifyingKey<MlDsa65>, VerifyError> {
308851×
        let enc = EncodedVerifyingKey::<MlDsa65>::try_from(self.mldsa65_pk.as_slice())
309851×
            .map_err(|_| VerifyError::BadKey)?;
310851×
        Ok(MlVerifyingKey::decode(&enc))
311851×
    }
312
}
313
314
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
315
pub enum Domain {
316
    Change,
317
    Attest,
318
    Policy,
319
    /// A server-issued challenge, proving possession of a key to a host
320
    /// (hub spec §5.3, §5.4). Never a stored object.
321
    Challenge,
322
    /// A certificate an issuer gives a short-lived key (§14.7).
323
    Certificate,
324
    /// An author's grant to a certified subject (§14.7).
325
    Grant,
326
    /// A transparency log's checkpoint note (§14.8).
327
    Checkpoint,
328
}
329
330
impl Domain {
3311334×
    pub fn name(self) -> &'static str {
3321334×
        match self {
333188×
            Domain::Change => "change",
334714×
            Domain::Attest => "attest",
335205×
            Domain::Policy => "policy",
3366×
            Domain::Challenge => "challenge",
337134×
            Domain::Certificate => "certificate",
33816×
            Domain::Grant => "grant",
33971×
            Domain::Checkpoint => "checkpoint",
340
        }
3411334×
    }
342
}
343
344
/// `"oxy1 sig " || domain || 0x00 || KeyId || target` (spec §14.3).
3451334×
pub fn signing_message(domain: Domain, key: &KeyId, target: &ObjectRef) -> Vec<u8> {
3461334×
    let mut m = Vec::with_capacity(80);
3471334×
    m.extend_from_slice(b"oxy1 sig ");
3481334×
    m.extend_from_slice(domain.name().as_bytes());
3491334×
    m.push(0);
3501334×
    m.extend_from_slice(&key.0);
3511334×
    m.extend_from_slice(&target.0);
3521334×
    m
3531334×
}
354
355
#[derive(Clone, PartialEq, Eq)]
356
pub struct Signature {
357
    pub key: KeyId,
358
    pub ed: [u8; ED25519_SIG_LEN],
359
    pub ml: Vec<u8>,
360
}
361
362
impl std::fmt::Debug for Signature {
3630×
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
3640×
        write!(f, "Signature(key {:?})", self.key)
3650×
    }
366
}
367
368
impl Signature {
3691103×
    pub fn to_value(&self) -> Value {
3701103×
        Value::map([
3711103×
            (0, Value::Bytes(self.key.0.to_vec())),
3721103×
            (1, Value::Uint(ALG_COMPOSITE)),
3731103×
            (2, Value::Bytes(self.ed.to_vec())),
3741103×
            (3, Value::Bytes(self.ml.clone())),
3751103×
        ])
3761103×
    }
3772759×
    pub fn from_value(v: &Value) -> Result<Signature, ObjectError> {
3782759×
        let m = v
3792759×
            .as_map()
3802759×
            .ok_or_else(|| ObjectError::Schema("signature: expected map".into()))?;
3812759×
        let alg = uint(field(m, 1, "alg")?, "alg")?;
3822759×
        if alg != ALG_COMPOSITE {
3830×
            return Err(ObjectError::Schema(format!(
3840×
                "unknown signature algorithm {alg}"
3850×
            )));
3862759×
        }
3872759×
        let ed = bytes(field(m, 2, "ed")?, "ed")?;
3882759×
        let ml = bytes(field(m, 3, "ml")?, "ml")?;
3892759×
        if ed.len() != ED25519_SIG_LEN || ml.len() != MLDSA65_SIG_LEN {
3901×
            return Err(ObjectError::Schema("signature: wrong length".into()));
3912758×
        }
392
        Ok(Signature {
3932758×
            key: oref(field(m, 0, "key")?, "key")?,
3942758×
            ed: ed.try_into().unwrap(),
3952758×
            ml: ml.to_vec(),
396
        })
3972759×
    }
398865×
    pub fn encode_list(sigs: &[Signature]) -> Vec<u8> {
399865×
        cbor::encode(&Value::Array(sigs.iter().map(|s| s.to_value()).collect()))
400865×
    }
4012523×
    pub fn decode_list(b: &[u8]) -> Result<Vec<Signature>, ObjectError> {
4022523×
        let v = cbor::decode(b)?;
4032523×
        array(&v, "signatures")?
4042523×
            .iter()
4052523×
            .map(Signature::from_value)
4062523×
            .collect()
4072523×
    }
408
}
409
410
#[derive(Clone, Copy, Debug, PartialEq, Eq, thiserror::Error)]
411
pub enum VerifyError {
412
    #[error("signature names a different key than the identity")]
413
    KeyMismatch,
414
    #[error("identity holds a malformed public key")]
415
    BadKey,
416
    #[error("Ed25519 signature invalid")]
417
    Ed25519,
418
    #[error("ML-DSA-65 signature invalid")]
419
    MlDsa,
420
    #[error("a challenge is at least 16 bytes")]
421
    ShortChallenge,
422
}
423
424
/// Verify a composite signature by `identity` over `target` (spec §14.3).
425872×
pub fn verify(
426872×
    identity: &Identity,
427872×
    sig: &Signature,
428872×
    domain: Domain,
429872×
    target: &ObjectRef,
430872×
) -> Result<(), VerifyError> {
431872×
    let key = identity.hash();
432872×
    if sig.key != key {
4331×
        return Err(VerifyError::KeyMismatch);
434871×
    }
435871×
    let msg = signing_message(domain, &key, target);
436871×
    let ed_sig = EdSignature::from_bytes(&sig.ed);
437871×
    identity
438871×
        .ed_key()?
439871×
        .verify_strict(&msg, &ed_sig)
440871×
        .map_err(|_| VerifyError::Ed25519)?;
441852×
    let enc =
442852×
        EncodedSignature::<MlDsa65>::try_from(sig.ml.as_slice()).map_err(|_| VerifyError::MlDsa)?;
443852×
    let ml_sig = MlSignature::<MlDsa65>::decode(&enc).ok_or(VerifyError::MlDsa)?;
444851×
    if !identity.ml_key()?.verify_with_context(&msg, b"", &ml_sig) {
4450×
        return Err(VerifyError::MlDsa);
446851×
    }
447851×
    Ok(())
448872×
}
449
450
/// The seeds of a composite key pair. Stored only in the user's key directory.
451
#[derive(Clone)]
452
pub struct SecretKey {
453
    pub ed_seed: [u8; 32],
454
    pub ml_seed: [u8; 32],
455
}
456
457
impl std::fmt::Debug for SecretKey {
4580×
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
4590×
        f.write_str("SecretKey(..)")
4600×
    }
461
}
462
463
impl SecretKey {
464165×
    pub fn generate() -> SecretKey {
465165×
        let mut ed_seed = [0u8; 32];
466165×
        let mut ml_seed = [0u8; 32];
467165×
        rand::rngs::OsRng.fill_bytes(&mut ed_seed);
468165×
        rand::rngs::OsRng.fill_bytes(&mut ml_seed);
469165×
        SecretKey { ed_seed, ml_seed }
470165×
    }
471
472695×
    fn ed(&self) -> EdSigningKey {
473695×
        EdSigningKey::from_bytes(&self.ed_seed)
474695×
    }
475661×
    fn ml(&self) -> MlSigningKey<MlDsa65> {
476661×
        MlSigningKey::from_seed(&Seed::from(self.ml_seed))
477661×
    }
478
479
    /// The identity object for these keys.
480198×
    pub fn identity(&self, name: &str, email: &str, created: u64) -> Identity {
481198×
        Identity {
482198×
            ed25519_pk: self.ed().verifying_key().to_bytes(),
483198×
            mldsa65_pk: self
484198×
                .ml()
485198×
                .expanded_key()
486198×
                .verifying_key()
487198×
                .encode()
488198×
                .as_slice()
489198×
                .to_vec(),
490198×
            name: name.into(),
491198×
            email: email.into(),
492198×
            created,
493198×
            expires: None,
494198×
            previous: None,
495198×
            delegates: vec![],
496198×
        }
497198×
    }
498
499
    /// Ed25519 alone over `msg`, for a format that separates its own
500
    /// domain and whose verifiers know only Ed25519 (DSSE: see
501
    /// [`crate::dsse`]). Oxygen's own objects are signed with [`Self::sign`].
50234×
    pub fn sign_ed25519(&self, msg: &[u8]) -> [u8; 64] {
50334×
        self.ed().sign(msg).to_bytes()
50434×
    }
505
506463×
    pub fn sign(&self, domain: Domain, key: &KeyId, target: &ObjectRef) -> Signature {
507463×
        let msg = signing_message(domain, key, target);
508463×
        let ed = self.ed().sign(&msg).to_bytes();
509463×
        let ml = self
510463×
            .ml()
511463×
            .expanded_key()
512463×
            .sign_deterministic(&msg, b"")
513463×
            .expect("empty context is valid")
514463×
            .encode()
515463×
            .as_slice()
516463×
            .to_vec();
517463×
        Signature { key: *key, ed, ml }
518463×
    }
519
520102×
    pub fn encode(&self, key: &KeyId) -> Vec<u8> {
521102×
        cbor::encode(&Value::map([
522102×
            (0, Value::Uint(FORMAT_VERSION)),
523102×
            (1, Value::Bytes(key.0.to_vec())),
524102×
            (2, Value::Bytes(self.ed_seed.to_vec())),
525102×
            (3, Value::Bytes(self.ml_seed.to_vec())),
526102×
        ]))
527102×
    }
528
529589×
    pub fn decode(b: &[u8]) -> Result<(KeyId, SecretKey), ObjectError> {
530589×
        let v = cbor::decode(b)?;
531589×
        let m = v
532589×
            .as_map()
533589×
            .ok_or_else(|| ObjectError::Schema("secret key: expected map".into()))?;
534589×
        check_version(m)?;
5351178×
        let seed = |k: u64| -> Result<[u8; 32], ObjectError> {
5361178×
            bytes(field(m, k, "seed")?, "seed")?
5371178×
                .try_into()
5381178×
                .map_err(|_| ObjectError::Schema("seed: expected 32 bytes".into()))
5391178×
        };
540
        Ok((
541589×
            oref(field(m, 1, "key")?, "key")?,
542
            SecretKey {
543589×
                ed_seed: seed(2)?,
544589×
                ml_seed: seed(3)?,
545
            },
546
        ))
547589×
    }
548
}
549
550
#[cfg(test)]
551
mod tests {
552
    use super::*;
553
5546×
    fn fixed_key() -> SecretKey {
5556×
        SecretKey {
5566×
            ed_seed: [1; 32],
5576×
            ml_seed: [2; 32],
5586×
        }
5596×
    }
560
561
    #[test]
5621×
    fn identity_round_trip_and_sizes() {
5631×
        let sk = fixed_key();
5641×
        let id = sk.identity("Ada", "[email protected]", 1_700_000_000_000);
5651×
        assert_eq!(id.mldsa65_pk.len(), MLDSA65_PK_LEN);
5661×
        let d = Identity::decode(&id.encode()).unwrap();
5671×
        assert_eq!(d, id);
5681×
        assert_eq!(d.hash(), id.hash());
569
        // Deterministic from seeds.
5701×
        assert_eq!(
5711×
            fixed_key()
5721×
                .identity("Ada", "[email protected]", 1_700_000_000_000)
5731×
                .hash(),
5741×
            id.hash()
575
        );
5761×
        let mut other = id.clone();
5771×
        other.delegates.push(Delegate::full(ObjectRef([9; 32])));
5781×
        assert_ne!(other.hash(), id.hash());
5791×
    }
580
581
    #[test]
5821×
    fn delegates_carry_scope_and_expiry_and_bare_keys_mean_every_scope() {
5831×
        let sk = fixed_key();
5841×
        let mut id = sk.identity("Ada", "[email protected]", 1_700_000_000_000);
5851×
        let agent = ObjectRef([7; 32]);
5861×
        let host = ObjectRef([3; 32]);
5871×
        id.delegates = vec![
5881×
            Delegate {
5891×
                key: agent,
5901×
                scope: Scope::CHANGES,
5911×
                expires: Some(2_000),
5921×
            },
5931×
            Delegate {
5941×
                key: host,
5951×
                scope: Scope::CHANGES | Scope::REFS,
5961×
                expires: None,
5971×
            },
598
        ];
5991×
        let d = Identity::decode(&id.encode()).unwrap();
6001×
        assert_eq!(d.delegates.len(), 2);
6011×
        assert!(d.delegates_to(&agent, Scope::CHANGES, 1_000));
6021×
        assert!(!d.delegates_to(&agent, Scope::CHANGES, 2_001), "expired");
6031×
        assert!(!d.delegates_to(&agent, Scope::REFS, 1_000));
6041×
        assert!(!d.delegates_to(&agent, Scope::SEAL, 1_000));
6051×
        assert!(d.delegates_to(&host, Scope::REFS, u64::MAX));
6061×
        assert!(!d.delegates_to(&host, Scope::SEAL, 0));
6071×
        assert!(!d.delegates_to(&ObjectRef([1; 32]), Scope::CHANGES, 0));
6081×
        assert_eq!(
6091×
            Scope::parse("changes, refs").unwrap(),
6101×
            Scope::CHANGES | Scope::REFS
611
        );
6121×
        assert_eq!(Scope::parse("all").unwrap(), Scope::ALL);
6131×
        assert_eq!((Scope::CHANGES | Scope::SEAL).to_string(), "changes,seal");
6141×
        assert!(Scope::parse("push").is_err() && Scope::parse("").is_err());
615
        // An identity written before scopes existed lists bare KeyIds.
6161×
        let mut v = id.to_value();
6171×
        if let Value::Map(m) = &mut v {
6181×
            m.insert(8, Value::Array(vec![Value::Bytes(host.0.to_vec())]));
6191×
        }
6201×
        let old = Identity::decode(&cbor::encode(&v)).unwrap();
6211×
        assert_eq!(old.delegates, vec![Delegate::full(host)]);
6221×
        assert!(old.delegates_to(&host, Scope::ALL, u64::MAX));
6231×
    }
624
625
    #[test]
6261×
    fn sign_and_verify() {
6271×
        let sk = fixed_key();
6281×
        let id = sk.identity("Ada", "[email protected]", 1);
6291×
        let key = id.hash();
6301×
        let target = ObjectRef([7; 32]);
6311×
        let sig = sk.sign(Domain::Change, &key, &target);
6321×
        assert_eq!(sig.ml.len(), MLDSA65_SIG_LEN);
6331×
        assert_eq!(verify(&id, &sig, Domain::Change, &target), Ok(()));
634
        // Different target, different domain: invalid.
6351×
        assert_eq!(
6361×
            verify(&id, &sig, Domain::Change, &ObjectRef([8; 32])),
637
            Err(VerifyError::Ed25519)
638
        );
6391×
        assert_eq!(
6401×
            verify(&id, &sig, Domain::Attest, &target),
641
            Err(VerifyError::Ed25519)
642
        );
643
        // Deterministic signatures.
6441×
        assert_eq!(sk.sign(Domain::Change, &key, &target), sig);
645
        // Signature list round trip.
6461×
        let l =
6471×
            Signature::decode_list(&Signature::encode_list(std::slice::from_ref(&sig))).unwrap();
6481×
        assert_eq!(l, vec![sig]);
6491×
    }
650
651
    #[test]
6521×
    fn stripping_or_forging_either_half_fails() {
6531×
        let sk = fixed_key();
6541×
        let id = sk.identity("Ada", "a@b", 1);
6551×
        let key = id.hash();
6561×
        let target = ObjectRef([7; 32]);
6571×
        let good = sk.sign(Domain::Change, &key, &target);
658
6591×
        let mut no_ml = good.clone();
6601×
        no_ml.ml = vec![0; MLDSA65_SIG_LEN];
6611×
        assert_eq!(
6621×
            verify(&id, &no_ml, Domain::Change, &target),
663
            Err(VerifyError::MlDsa)
664
        );
665
6661×
        let mut bad_ed = good.clone();
6671×
        bad_ed.ed[10] ^= 1;
6681×
        assert_eq!(
6691×
            verify(&id, &bad_ed, Domain::Change, &target),
670
            Err(VerifyError::Ed25519)
671
        );
672
673
        // A signature made for another KeyId over the same target does not transfer.
6741×
        let other = SecretKey {
6751×
            ed_seed: [3; 32],
6761×
            ml_seed: [4; 32],
6771×
        };
6781×
        let other_id = other.identity("Bob", "b@b", 1);
6791×
        let theirs = other.sign(Domain::Change, &other_id.hash(), &target);
6801×
        assert_eq!(
6811×
            verify(&id, &theirs, Domain::Change, &target),
682
            Err(VerifyError::KeyMismatch)
683
        );
6841×
        let mut relabelled = theirs.clone();
6851×
        relabelled.key = key;
6861×
        assert_eq!(
6871×
            verify(&id, &relabelled, Domain::Change, &target),
688
            Err(VerifyError::Ed25519)
689
        );
690
691
        // Wrong length is rejected at decode time.
6921×
        let mut short = good.to_value();
6931×
        if let Value::Map(m) = &mut short {
6941×
            m.insert(3, Value::Bytes(vec![0; 10]));
6951×
        }
6961×
        assert!(Signature::from_value(&short).is_err());
6971×
    }
698
699
    #[test]
7001×
    fn secret_key_round_trip() {
7011×
        let sk = fixed_key();
7021×
        let key = sk.identity("x", "y", 0).hash();
7031×
        let (k, d) = SecretKey::decode(&sk.encode(&key)).unwrap();
7041×
        assert_eq!(k, key);
7051×
        assert_eq!(d.ed_seed, sk.ed_seed);
7061×
        assert_eq!(d.ml_seed, sk.ml_seed);
7071×
        assert_ne!(SecretKey::generate().ed_seed, SecretKey::generate().ed_seed);
7081×
    }
709
}
710
711
/// The signing target of a challenge: `BLAKE3-256("oxy1 challenge " || bytes)`,
712
/// so a challenge can never collide with a stored object's reference.
7137×
pub fn challenge_target(challenge: &[u8]) -> ObjectRef {
7147×
    let mut h = blake3::Hasher::new();
7157×
    h.update(b"oxy1 challenge ");
7167×
    h.update(challenge);
7177×
    ObjectRef(*h.finalize().as_bytes())
7187×
}
719
720
impl SecretKey {
721
    /// Sign a host's challenge (at least 16 bytes) with this key.
7223×
    pub fn sign_challenge(&self, key: &KeyId, challenge: &[u8]) -> Result<Signature, VerifyError> {
7233×
        if challenge.len() < 16 {
7241×
            return Err(VerifyError::ShortChallenge);
7252×
        }
7262×
        Ok(self.sign(Domain::Challenge, key, &challenge_target(challenge)))
7273×
    }
728
}
729
730
/// Check a challenge signature against the identity that claims it.
7315×
pub fn verify_challenge(
7325×
    identity: &Identity,
7335×
    sig: &Signature,
7345×
    challenge: &[u8],
7355×
) -> Result<(), VerifyError> {
7365×
    if challenge.len() < 16 {
7370×
        return Err(VerifyError::ShortChallenge);
7385×
    }
7395×
    if sig.key != identity.hash() {
7401×
        return Err(VerifyError::KeyMismatch);
7414×
    }
7424×
    verify(
7434×
        identity,
7444×
        sig,
7454×
        Domain::Challenge,
7464×
        &challenge_target(challenge),
747
    )
7485×
}
749
750
#[cfg(test)]
751
mod challenge_tests {
752
    use super::*;
753
754
    #[test]
7551×
    fn a_challenge_signature_binds_key_and_bytes() {
7561×
        let sk = SecretKey::generate();
7571×
        let id = sk.identity("A", "a@example", 1);
7581×
        let key = id.hash();
7591×
        let challenge = [7u8; 32];
7601×
        let sig = sk.sign_challenge(&key, &challenge).unwrap();
7611×
        assert!(verify_challenge(&id, &sig, &challenge).is_ok());
7621×
        assert!(
7631×
            verify_challenge(&id, &sig, &[8u8; 32]).is_err(),
764
            "other bytes"
765
        );
7661×
        let other = SecretKey::generate().identity("B", "b@example", 1);
7671×
        assert!(
7681×
            verify_challenge(&other, &sig, &challenge).is_err(),
769
            "other identity"
770
        );
7711×
        assert!(sk.sign_challenge(&key, b"short").is_err());
772
        // A challenge target never equals a change signature's target for the same bytes.
7731×
        assert_ne!(challenge_target(&challenge), ObjectRef(challenge));
7741×
    }
775
}