OXYGENHUB

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

498 of 521 lines run, 92 of 137 functions · run #302 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
49690×
    pub fn has(self, other: Scope) -> bool {
50690×
        self.0 & other.0 == other.0
51690×
    }
5214×
    pub fn is_empty(self) -> bool {
5314×
        self.0 == 0
5414×
    }
55
    /// The names in the set, in the order they are written.
56214×
    pub fn names(self) -> Vec<&'static str> {
57214×
        Self::NAMES
58214×
            .iter()
59642×
            .filter(|(s, _)| self.has(*s))
60214×
            .map(|(_, n)| *n)
61214×
            .collect()
62214×
    }
63475×
    fn named(name: &str) -> Option<Scope> {
64475×
        Self::NAMES
65475×
            .iter()
66837×
            .find(|(_, n)| *n == name)
67475×
            .map(|(s, _)| *s)
68475×
    }
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;
90481×
    fn bitor(self, rhs: Scope) -> Scope {
91481×
        Scope(self.0 | rhs.0)
92481×
    }
93
}
94
95
impl std::fmt::Display for Scope {
9612×
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
9712×
        f.write_str(&self.names().join(","))
9812×
    }
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`.
12629×
    pub fn allows(&self, scope: Scope, at_ms: u64) -> bool {
12729×
        self.scope.has(scope) && !self.expires.is_some_and(|e| at_ms > e)
12829×
    }
129202×
    fn to_value(self) -> Value {
130202×
        Value::map([
131202×
            (0, Value::Bytes(self.key.0.to_vec())),
132
            (
133
                1,
134
                Value::Array(
135202×
                    self.scope
136202×
                        .names()
137202×
                        .into_iter()
138457×
                        .map(|n| Value::Text(n.to_string()))
139202×
                        .collect(),
140
                ),
141
            ),
142202×
            (2, self.expires.map(Value::Uint).unwrap_or(Value::Null)),
143
        ])
144202×
    }
145
    /// An entry, or a bare KeyId as identities carried before scopes
146
    /// existed, which meant every scope.
147217×
    fn from_value(v: &Value) -> Result<Delegate, ObjectError> {
148217×
        if let Value::Bytes(_) = v {
1491×
            return Ok(Delegate::full(oref(v, "delegate")?));
150216×
        }
151216×
        let m = v
152216×
            .as_map()
153216×
            .ok_or_else(|| ObjectError::Schema("delegate: expected map".into()))?;
154216×
        let key = oref(field(m, 0, "delegate key")?, "delegate key")?;
155216×
        let mut scope = Scope::NONE;
156472×
        for n in array(field(m, 1, "delegate scope")?, "delegate scope")? {
157472×
            let n = text(n, "delegate scope")?;
158472×
            scope = scope
159472×
                | Scope::named(n)
160472×
                    .ok_or_else(|| ObjectError::Schema(format!("delegate: unknown scope {n:?}")))?;
161
        }
162216×
        let expires = match field(m, 2, "delegate expires")? {
163216×
            v if v.is_null() => None,
1645×
            v => Some(uint(v, "delegate expires")?),
165
        };
166216×
        Ok(Delegate {
167216×
            key,
168216×
            scope,
169216×
            expires,
170216×
        })
171217×
    }
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.
1871687×
fn tidy(mut delegates: Vec<Delegate>) -> Vec<Delegate> {
1881687×
    delegates.sort_by_key(|d| d.key);
1891687×
    delegates.dedup_by(|a, b| a.key == b.key);
1901687×
    delegates
1911687×
}
192
193
impl Identity {
194
    /// The delegation to `key`, if any.
19562×
    pub fn delegate(&self, key: &KeyId) -> Option<&Delegate> {
19662×
        self.delegates.iter().find(|d| d.key == *key)
19762×
    }
198
    /// Whether `key` may act for this identity within `scope` at `at_ms`.
19918×
    pub fn delegates_to(&self, key: &KeyId, scope: Scope, at_ms: u64) -> bool {
20018×
        self.delegate(key).is_some_and(|d| d.allows(scope, at_ms))
20118×
    }
2021675×
    pub fn to_value(&self) -> Value {
2031675×
        Value::map([
2041675×
            (0, Value::Uint(FORMAT_VERSION)),
2051675×
            (1, Value::Bytes(self.ed25519_pk.to_vec())),
2061675×
            (2, Value::Bytes(self.mldsa65_pk.clone())),
2071675×
            (3, Value::Text(self.name.clone())),
2081675×
            (4, Value::Text(self.email.clone())),
2091675×
            (5, Value::Uint(self.created)),
2101675×
            (6, self.expires.map(Value::Uint).unwrap_or(Value::Null)),
211
            (
212
                7,
2131675×
                self.previous
2141675×
                    .map(|p| Value::Bytes(p.0.to_vec()))
2151675×
                    .unwrap_or(Value::Null),
216
            ),
217
            (
218
                8,
2191675×
                Value::Array(self.delegates.iter().map(|d| d.to_value()).collect()),
220
            ),
221
        ])
2221675×
    }
2231674×
    pub fn encode(&self) -> Vec<u8> {
2241674×
        cbor::encode(&self.to_value())
2251674×
    }
226808×
    pub fn hash(&self) -> KeyId {
227808×
        hash_object(ObjectType::Identity, &self.encode())
228808×
    }
2291674×
    pub fn decode(b: &[u8]) -> Result<Identity, ObjectError> {
2301674×
        let v = cbor::decode(b)?;
2311674×
        let m = v
2321674×
            .as_map()
2331674×
            .ok_or_else(|| ObjectError::Schema("identity: expected map".into()))?;
2341674×
        check_version(m)?;
2351674×
        let ed = bytes(field(m, 1, "ed25519_pk")?, "ed25519_pk")?;
2361674×
        let ml = bytes(field(m, 2, "mldsa65_pk")?, "mldsa65_pk")?;
2371674×
        if ed.len() != ED25519_PK_LEN || ml.len() != MLDSA65_PK_LEN {
2380×
            return Err(ObjectError::Schema(
2390×
                "identity: wrong public key length".into(),
2400×
            ));
2411674×
        }
2421674×
        let opt_u = |v: &Value| -> Result<Option<u64>, ObjectError> {
2431674×
            if v.is_null() {
2441670×
                Ok(None)
245
            } else {
2464×
                uint(v, "expires").map(Some)
247
            }
2481674×
        };
2491674×
        let opt_r = |v: &Value| -> Result<Option<KeyId>, ObjectError> {
2501674×
            if v.is_null() {
2511222×
                Ok(None)
252
            } else {
253452×
                oref(v, "previous").map(Some)
254
            }
2551674×
        };
2561674×
        let delegates = tidy(
2571674×
            array(field(m, 8, "delegates")?, "delegates")?
2581674×
                .iter()
2591674×
                .map(Delegate::from_value)
2601674×
                .collect::<Result<Vec<_>, _>>()?,
261
        );
262
        Ok(Identity {
2631674×
            ed25519_pk: ed.try_into().unwrap(),
2641674×
            mldsa65_pk: ml.to_vec(),
2651674×
            name: text(field(m, 3, "name")?, "name")?.to_owned(),
2661674×
            email: text(field(m, 4, "email")?, "email")?.to_owned(),
2671674×
            created: uint(field(m, 5, "created")?, "created")?,
2681674×
            expires: opt_u(field(m, 6, "expires")?)?,
2691674×
            previous: opt_r(field(m, 7, "previous")?)?,
2701674×
            delegates,
271
        })
2721674×
    }
273
274
    /// Whether the identity is past its expiry at `now_ms`.
275218×
    pub fn is_expired_at(&self, now_ms: u64) -> bool {
276218×
        self.expires.is_some_and(|e| now_ms > e)
277218×
    }
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).
28113×
    pub fn successor(
28213×
        &self,
28313×
        delegates: Vec<Delegate>,
28413×
        expires: Option<u64>,
28513×
        created: u64,
28613×
    ) -> Identity {
28713×
        Identity {
28813×
            previous: Some(self.hash()),
28913×
            delegates: tidy(delegates),
29013×
            expires,
29113×
            created,
29213×
            ..self.clone()
29313×
        }
29413×
    }
295
296
    /// Check a [`SecretKey::sign_ed25519`] signature by this identity.
2976×
    pub fn verify_ed25519(&self, msg: &[u8], sig: &[u8]) -> Result<(), VerifyError> {
2986×
        let sig = EdSignature::from_slice(sig).map_err(|_| VerifyError::Ed25519)?;
2996×
        self.ed_key()?
3006×
            .verify_strict(msg, &sig)
3016×
            .map_err(|_| VerifyError::Ed25519)
3026×
    }
303
304462×
    fn ed_key(&self) -> Result<EdVerifyingKey, VerifyError> {
305462×
        EdVerifyingKey::from_bytes(&self.ed25519_pk).map_err(|_| VerifyError::BadKey)
306462×
    }
307445×
    fn ml_key(&self) -> Result<MlVerifyingKey<MlDsa65>, VerifyError> {
308445×
        let enc = EncodedVerifyingKey::<MlDsa65>::try_from(self.mldsa65_pk.as_slice())
309445×
            .map_err(|_| VerifyError::BadKey)?;
310445×
        Ok(MlVerifyingKey::decode(&enc))
311445×
    }
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
}
323
324
impl Domain {
325723×
    pub fn name(self) -> &'static str {
326723×
        match self {
327153×
            Domain::Change => "change",
328454×
            Domain::Attest => "attest",
329113×
            Domain::Policy => "policy",
3303×
            Domain::Challenge => "challenge",
331
        }
332723×
    }
333
}
334
335
/// `"oxy1 sig " || domain || 0x00 || KeyId || target` (spec §14.3).
336723×
pub fn signing_message(domain: Domain, key: &KeyId, target: &ObjectRef) -> Vec<u8> {
337723×
    let mut m = Vec::with_capacity(80);
338723×
    m.extend_from_slice(b"oxy1 sig ");
339723×
    m.extend_from_slice(domain.name().as_bytes());
340723×
    m.push(0);
341723×
    m.extend_from_slice(&key.0);
342723×
    m.extend_from_slice(&target.0);
343723×
    m
344723×
}
345
346
#[derive(Clone, PartialEq, Eq)]
347
pub struct Signature {
348
    pub key: KeyId,
349
    pub ed: [u8; ED25519_SIG_LEN],
350
    pub ml: Vec<u8>,
351
}
352
353
impl std::fmt::Debug for Signature {
3540×
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
3550×
        write!(f, "Signature(key {:?})", self.key)
3560×
    }
357
}
358
359
impl Signature {
360533×
    pub fn to_value(&self) -> Value {
361533×
        Value::map([
362533×
            (0, Value::Bytes(self.key.0.to_vec())),
363533×
            (1, Value::Uint(ALG_COMPOSITE)),
364533×
            (2, Value::Bytes(self.ed.to_vec())),
365533×
            (3, Value::Bytes(self.ml.clone())),
366533×
        ])
367533×
    }
3681320×
    pub fn from_value(v: &Value) -> Result<Signature, ObjectError> {
3691320×
        let m = v
3701320×
            .as_map()
3711320×
            .ok_or_else(|| ObjectError::Schema("signature: expected map".into()))?;
3721320×
        let alg = uint(field(m, 1, "alg")?, "alg")?;
3731320×
        if alg != ALG_COMPOSITE {
3740×
            return Err(ObjectError::Schema(format!(
3750×
                "unknown signature algorithm {alg}"
3760×
            )));
3771320×
        }
3781320×
        let ed = bytes(field(m, 2, "ed")?, "ed")?;
3791320×
        let ml = bytes(field(m, 3, "ml")?, "ml")?;
3801320×
        if ed.len() != ED25519_SIG_LEN || ml.len() != MLDSA65_SIG_LEN {
3811×
            return Err(ObjectError::Schema("signature: wrong length".into()));
3821319×
        }
383
        Ok(Signature {
3841319×
            key: oref(field(m, 0, "key")?, "key")?,
3851319×
            ed: ed.try_into().unwrap(),
3861319×
            ml: ml.to_vec(),
387
        })
3881320×
    }
389495×
    pub fn encode_list(sigs: &[Signature]) -> Vec<u8> {
390495×
        cbor::encode(&Value::Array(sigs.iter().map(|s| s.to_value()).collect()))
391495×
    }
3921268×
    pub fn decode_list(b: &[u8]) -> Result<Vec<Signature>, ObjectError> {
3931268×
        let v = cbor::decode(b)?;
3941268×
        array(&v, "signatures")?
3951268×
            .iter()
3961268×
            .map(Signature::from_value)
3971268×
            .collect()
3981268×
    }
399
}
400
401
#[derive(Clone, Copy, Debug, PartialEq, Eq, thiserror::Error)]
402
pub enum VerifyError {
403
    #[error("signature names a different key than the identity")]
404
    KeyMismatch,
405
    #[error("identity holds a malformed public key")]
406
    BadKey,
407
    #[error("Ed25519 signature invalid")]
408
    Ed25519,
409
    #[error("ML-DSA-65 signature invalid")]
410
    MlDsa,
411
    #[error("a challenge is at least 16 bytes")]
412
    ShortChallenge,
413
}
414
415
/// Verify a composite signature by `identity` over `target` (spec §14.3).
416457×
pub fn verify(
417457×
    identity: &Identity,
418457×
    sig: &Signature,
419457×
    domain: Domain,
420457×
    target: &ObjectRef,
421457×
) -> Result<(), VerifyError> {
422457×
    let key = identity.hash();
423457×
    if sig.key != key {
4241×
        return Err(VerifyError::KeyMismatch);
425456×
    }
426456×
    let msg = signing_message(domain, &key, target);
427456×
    let ed_sig = EdSignature::from_bytes(&sig.ed);
428456×
    identity
429456×
        .ed_key()?
430456×
        .verify_strict(&msg, &ed_sig)
431456×
        .map_err(|_| VerifyError::Ed25519)?;
432446×
    let enc =
433446×
        EncodedSignature::<MlDsa65>::try_from(sig.ml.as_slice()).map_err(|_| VerifyError::MlDsa)?;
434446×
    let ml_sig = MlSignature::<MlDsa65>::decode(&enc).ok_or(VerifyError::MlDsa)?;
435445×
    if !identity.ml_key()?.verify_with_context(&msg, b"", &ml_sig) {
4360×
        return Err(VerifyError::MlDsa);
437445×
    }
438445×
    Ok(())
439457×
}
440
441
/// The seeds of a composite key pair. Stored only in the user's key directory.
442
#[derive(Clone)]
443
pub struct SecretKey {
444
    pub ed_seed: [u8; 32],
445
    pub ml_seed: [u8; 32],
446
}
447
448
impl std::fmt::Debug for SecretKey {
4490×
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
4500×
        f.write_str("SecretKey(..)")
4510×
    }
452
}
453
454
impl SecretKey {
45579×
    pub fn generate() -> SecretKey {
45679×
        let mut ed_seed = [0u8; 32];
45779×
        let mut ml_seed = [0u8; 32];
45879×
        rand::rngs::OsRng.fill_bytes(&mut ed_seed);
45979×
        rand::rngs::OsRng.fill_bytes(&mut ml_seed);
46079×
        SecretKey { ed_seed, ml_seed }
46179×
    }
462
463365×
    fn ed(&self) -> EdSigningKey {
464365×
        EdSigningKey::from_bytes(&self.ed_seed)
465365×
    }
466363×
    fn ml(&self) -> MlSigningKey<MlDsa65> {
467363×
        MlSigningKey::from_seed(&Seed::from(self.ml_seed))
468363×
    }
469
470
    /// The identity object for these keys.
47196×
    pub fn identity(&self, name: &str, email: &str, created: u64) -> Identity {
47296×
        Identity {
47396×
            ed25519_pk: self.ed().verifying_key().to_bytes(),
47496×
            mldsa65_pk: self
47596×
                .ml()
47696×
                .expanded_key()
47796×
                .verifying_key()
47896×
                .encode()
47996×
                .as_slice()
48096×
                .to_vec(),
48196×
            name: name.into(),
48296×
            email: email.into(),
48396×
            created,
48496×
            expires: None,
48596×
            previous: None,
48696×
            delegates: vec![],
48796×
        }
48896×
    }
489
490
    /// Ed25519 alone over `msg`, for a format that separates its own
491
    /// domain and whose verifiers know only Ed25519 (DSSE: see
492
    /// [`crate::dsse`]). Oxygen's own objects are signed with [`Self::sign`].
4932×
    pub fn sign_ed25519(&self, msg: &[u8]) -> [u8; 64] {
4942×
        self.ed().sign(msg).to_bytes()
4952×
    }
496
497267×
    pub fn sign(&self, domain: Domain, key: &KeyId, target: &ObjectRef) -> Signature {
498267×
        let msg = signing_message(domain, key, target);
499267×
        let ed = self.ed().sign(&msg).to_bytes();
500267×
        let ml = self
501267×
            .ml()
502267×
            .expanded_key()
503267×
            .sign_deterministic(&msg, b"")
504267×
            .expect("empty context is valid")
505267×
            .encode()
506267×
            .as_slice()
507267×
            .to_vec();
508267×
        Signature { key: *key, ed, ml }
509267×
    }
510
51163×
    pub fn encode(&self, key: &KeyId) -> Vec<u8> {
51263×
        cbor::encode(&Value::map([
51363×
            (0, Value::Uint(FORMAT_VERSION)),
51463×
            (1, Value::Bytes(key.0.to_vec())),
51563×
            (2, Value::Bytes(self.ed_seed.to_vec())),
51663×
            (3, Value::Bytes(self.ml_seed.to_vec())),
51763×
        ]))
51863×
    }
519
520392×
    pub fn decode(b: &[u8]) -> Result<(KeyId, SecretKey), ObjectError> {
521392×
        let v = cbor::decode(b)?;
522392×
        let m = v
523392×
            .as_map()
524392×
            .ok_or_else(|| ObjectError::Schema("secret key: expected map".into()))?;
525392×
        check_version(m)?;
526784×
        let seed = |k: u64| -> Result<[u8; 32], ObjectError> {
527784×
            bytes(field(m, k, "seed")?, "seed")?
528784×
                .try_into()
529784×
                .map_err(|_| ObjectError::Schema("seed: expected 32 bytes".into()))
530784×
        };
531
        Ok((
532392×
            oref(field(m, 1, "key")?, "key")?,
533
            SecretKey {
534392×
                ed_seed: seed(2)?,
535392×
                ml_seed: seed(3)?,
536
            },
537
        ))
538392×
    }
539
}
540
541
#[cfg(test)]
542
mod tests {
543
    use super::*;
544
5456×
    fn fixed_key() -> SecretKey {
5466×
        SecretKey {
5476×
            ed_seed: [1; 32],
5486×
            ml_seed: [2; 32],
5496×
        }
5506×
    }
551
552
    #[test]
5531×
    fn identity_round_trip_and_sizes() {
5541×
        let sk = fixed_key();
5551×
        let id = sk.identity("Ada", "[email protected]", 1_700_000_000_000);
5561×
        assert_eq!(id.mldsa65_pk.len(), MLDSA65_PK_LEN);
5571×
        let d = Identity::decode(&id.encode()).unwrap();
5581×
        assert_eq!(d, id);
5591×
        assert_eq!(d.hash(), id.hash());
560
        // Deterministic from seeds.
5611×
        assert_eq!(
5621×
            fixed_key()
5631×
                .identity("Ada", "[email protected]", 1_700_000_000_000)
5641×
                .hash(),
5651×
            id.hash()
566
        );
5671×
        let mut other = id.clone();
5681×
        other.delegates.push(Delegate::full(ObjectRef([9; 32])));
5691×
        assert_ne!(other.hash(), id.hash());
5701×
    }
571
572
    #[test]
5731×
    fn delegates_carry_scope_and_expiry_and_bare_keys_mean_every_scope() {
5741×
        let sk = fixed_key();
5751×
        let mut id = sk.identity("Ada", "[email protected]", 1_700_000_000_000);
5761×
        let agent = ObjectRef([7; 32]);
5771×
        let host = ObjectRef([3; 32]);
5781×
        id.delegates = vec![
5791×
            Delegate {
5801×
                key: agent,
5811×
                scope: Scope::CHANGES,
5821×
                expires: Some(2_000),
5831×
            },
5841×
            Delegate {
5851×
                key: host,
5861×
                scope: Scope::CHANGES | Scope::REFS,
5871×
                expires: None,
5881×
            },
589
        ];
5901×
        let d = Identity::decode(&id.encode()).unwrap();
5911×
        assert_eq!(d.delegates.len(), 2);
5921×
        assert!(d.delegates_to(&agent, Scope::CHANGES, 1_000));
5931×
        assert!(!d.delegates_to(&agent, Scope::CHANGES, 2_001), "expired");
5941×
        assert!(!d.delegates_to(&agent, Scope::REFS, 1_000));
5951×
        assert!(!d.delegates_to(&agent, Scope::SEAL, 1_000));
5961×
        assert!(d.delegates_to(&host, Scope::REFS, u64::MAX));
5971×
        assert!(!d.delegates_to(&host, Scope::SEAL, 0));
5981×
        assert!(!d.delegates_to(&ObjectRef([1; 32]), Scope::CHANGES, 0));
5991×
        assert_eq!(
6001×
            Scope::parse("changes, refs").unwrap(),
6011×
            Scope::CHANGES | Scope::REFS
602
        );
6031×
        assert_eq!(Scope::parse("all").unwrap(), Scope::ALL);
6041×
        assert_eq!((Scope::CHANGES | Scope::SEAL).to_string(), "changes,seal");
6051×
        assert!(Scope::parse("push").is_err() && Scope::parse("").is_err());
606
        // An identity written before scopes existed lists bare KeyIds.
6071×
        let mut v = id.to_value();
6081×
        if let Value::Map(m) = &mut v {
6091×
            m.insert(8, Value::Array(vec![Value::Bytes(host.0.to_vec())]));
6101×
        }
6111×
        let old = Identity::decode(&cbor::encode(&v)).unwrap();
6121×
        assert_eq!(old.delegates, vec![Delegate::full(host)]);
6131×
        assert!(old.delegates_to(&host, Scope::ALL, u64::MAX));
6141×
    }
615
616
    #[test]
6171×
    fn sign_and_verify() {
6181×
        let sk = fixed_key();
6191×
        let id = sk.identity("Ada", "[email protected]", 1);
6201×
        let key = id.hash();
6211×
        let target = ObjectRef([7; 32]);
6221×
        let sig = sk.sign(Domain::Change, &key, &target);
6231×
        assert_eq!(sig.ml.len(), MLDSA65_SIG_LEN);
6241×
        assert_eq!(verify(&id, &sig, Domain::Change, &target), Ok(()));
625
        // Different target, different domain: invalid.
6261×
        assert_eq!(
6271×
            verify(&id, &sig, Domain::Change, &ObjectRef([8; 32])),
628
            Err(VerifyError::Ed25519)
629
        );
6301×
        assert_eq!(
6311×
            verify(&id, &sig, Domain::Attest, &target),
632
            Err(VerifyError::Ed25519)
633
        );
634
        // Deterministic signatures.
6351×
        assert_eq!(sk.sign(Domain::Change, &key, &target), sig);
636
        // Signature list round trip.
6371×
        let l =
6381×
            Signature::decode_list(&Signature::encode_list(std::slice::from_ref(&sig))).unwrap();
6391×
        assert_eq!(l, vec![sig]);
6401×
    }
641
642
    #[test]
6431×
    fn stripping_or_forging_either_half_fails() {
6441×
        let sk = fixed_key();
6451×
        let id = sk.identity("Ada", "a@b", 1);
6461×
        let key = id.hash();
6471×
        let target = ObjectRef([7; 32]);
6481×
        let good = sk.sign(Domain::Change, &key, &target);
649
6501×
        let mut no_ml = good.clone();
6511×
        no_ml.ml = vec![0; MLDSA65_SIG_LEN];
6521×
        assert_eq!(
6531×
            verify(&id, &no_ml, Domain::Change, &target),
654
            Err(VerifyError::MlDsa)
655
        );
656
6571×
        let mut bad_ed = good.clone();
6581×
        bad_ed.ed[10] ^= 1;
6591×
        assert_eq!(
6601×
            verify(&id, &bad_ed, Domain::Change, &target),
661
            Err(VerifyError::Ed25519)
662
        );
663
664
        // A signature made for another KeyId over the same target does not transfer.
6651×
        let other = SecretKey {
6661×
            ed_seed: [3; 32],
6671×
            ml_seed: [4; 32],
6681×
        };
6691×
        let other_id = other.identity("Bob", "b@b", 1);
6701×
        let theirs = other.sign(Domain::Change, &other_id.hash(), &target);
6711×
        assert_eq!(
6721×
            verify(&id, &theirs, Domain::Change, &target),
673
            Err(VerifyError::KeyMismatch)
674
        );
6751×
        let mut relabelled = theirs.clone();
6761×
        relabelled.key = key;
6771×
        assert_eq!(
6781×
            verify(&id, &relabelled, Domain::Change, &target),
679
            Err(VerifyError::Ed25519)
680
        );
681
682
        // Wrong length is rejected at decode time.
6831×
        let mut short = good.to_value();
6841×
        if let Value::Map(m) = &mut short {
6851×
            m.insert(3, Value::Bytes(vec![0; 10]));
6861×
        }
6871×
        assert!(Signature::from_value(&short).is_err());
6881×
    }
689
690
    #[test]
6911×
    fn secret_key_round_trip() {
6921×
        let sk = fixed_key();
6931×
        let key = sk.identity("x", "y", 0).hash();
6941×
        let (k, d) = SecretKey::decode(&sk.encode(&key)).unwrap();
6951×
        assert_eq!(k, key);
6961×
        assert_eq!(d.ed_seed, sk.ed_seed);
6971×
        assert_eq!(d.ml_seed, sk.ml_seed);
6981×
        assert_ne!(SecretKey::generate().ed_seed, SecretKey::generate().ed_seed);
6991×
    }
700
}
701
702
/// The signing target of a challenge: `BLAKE3-256("oxy1 challenge " || bytes)`,
703
/// so a challenge can never collide with a stored object's reference.
7044×
pub fn challenge_target(challenge: &[u8]) -> ObjectRef {
7054×
    let mut h = blake3::Hasher::new();
7064×
    h.update(b"oxy1 challenge ");
7074×
    h.update(challenge);
7084×
    ObjectRef(*h.finalize().as_bytes())
7094×
}
710
711
impl SecretKey {
712
    /// Sign a host's challenge (at least 16 bytes) with this key.
7132×
    pub fn sign_challenge(&self, key: &KeyId, challenge: &[u8]) -> Result<Signature, VerifyError> {
7142×
        if challenge.len() < 16 {
7151×
            return Err(VerifyError::ShortChallenge);
7161×
        }
7171×
        Ok(self.sign(Domain::Challenge, key, &challenge_target(challenge)))
7182×
    }
719
}
720
721
/// Check a challenge signature against the identity that claims it.
7223×
pub fn verify_challenge(
7233×
    identity: &Identity,
7243×
    sig: &Signature,
7253×
    challenge: &[u8],
7263×
) -> Result<(), VerifyError> {
7273×
    if challenge.len() < 16 {
7280×
        return Err(VerifyError::ShortChallenge);
7293×
    }
7303×
    if sig.key != identity.hash() {
7311×
        return Err(VerifyError::KeyMismatch);
7322×
    }
7332×
    verify(
7342×
        identity,
7352×
        sig,
7362×
        Domain::Challenge,
7372×
        &challenge_target(challenge),
738
    )
7393×
}
740
741
#[cfg(test)]
742
mod challenge_tests {
743
    use super::*;
744
745
    #[test]
7461×
    fn a_challenge_signature_binds_key_and_bytes() {
7471×
        let sk = SecretKey::generate();
7481×
        let id = sk.identity("A", "a@example", 1);
7491×
        let key = id.hash();
7501×
        let challenge = [7u8; 32];
7511×
        let sig = sk.sign_challenge(&key, &challenge).unwrap();
7521×
        assert!(verify_challenge(&id, &sig, &challenge).is_ok());
7531×
        assert!(
7541×
            verify_challenge(&id, &sig, &[8u8; 32]).is_err(),
755
            "other bytes"
756
        );
7571×
        let other = SecretKey::generate().identity("B", "b@example", 1);
7581×
        assert!(
7591×
            verify_challenge(&other, &sig, &challenge).is_err(),
760
            "other identity"
761
        );
7621×
        assert!(sk.sign_challenge(&key, b"short").is_err());
763
        // A challenge target never equals a change signature's target for the same bytes.
7641×
        assert_ne!(challenge_target(&challenge), ObjectRef(challenge));
7651×
    }
766
}