OXYGENHUB

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

499 of 522 lines run, 92 of 137 functions · run #308 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
49725×
    pub fn has(self, other: Scope) -> bool {
50725×
        self.0 & other.0 == other.0
51725×
    }
5221×
    pub fn is_empty(self) -> bool {
5321×
        self.0 == 0
5421×
    }
55
    /// The names in the set, in the order they are written.
56224×
    pub fn names(self) -> Vec<&'static str> {
57224×
        Self::NAMES
58224×
            .iter()
59672×
            .filter(|(s, _)| self.has(*s))
60224×
            .map(|(_, n)| *n)
61224×
            .collect()
62224×
    }
63477×
    pub(crate) fn named(name: &str) -> Option<Scope> {
64477×
        Self::NAMES
65477×
            .iter()
66840×
            .find(|(_, n)| *n == name)
67477×
            .map(|(s, _)| *s)
68477×
    }
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;
90487×
    fn bitor(self, rhs: Scope) -> Scope {
91487×
        Scope(self.0 | rhs.0)
92487×
    }
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.
1871688×
fn tidy(mut delegates: Vec<Delegate>) -> Vec<Delegate> {
1881688×
    delegates.sort_by_key(|d| d.key);
1891688×
    delegates.dedup_by(|a, b| a.key == b.key);
1901688×
    delegates
1911688×
}
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×
    }
2021702×
    pub fn to_value(&self) -> Value {
2031702×
        Value::map([
2041702×
            (0, Value::Uint(FORMAT_VERSION)),
2051702×
            (1, Value::Bytes(self.ed25519_pk.to_vec())),
2061702×
            (2, Value::Bytes(self.mldsa65_pk.clone())),
2071702×
            (3, Value::Text(self.name.clone())),
2081702×
            (4, Value::Text(self.email.clone())),
2091702×
            (5, Value::Uint(self.created)),
2101702×
            (6, self.expires.map(Value::Uint).unwrap_or(Value::Null)),
211
            (
212
                7,
2131702×
                self.previous
2141702×
                    .map(|p| Value::Bytes(p.0.to_vec()))
2151702×
                    .unwrap_or(Value::Null),
216
            ),
217
            (
218
                8,
2191702×
                Value::Array(self.delegates.iter().map(|d| d.to_value()).collect()),
220
            ),
221
        ])
2221702×
    }
2231701×
    pub fn encode(&self) -> Vec<u8> {
2241701×
        cbor::encode(&self.to_value())
2251701×
    }
226825×
    pub fn hash(&self) -> KeyId {
227825×
        hash_object(ObjectType::Identity, &self.encode())
228825×
    }
2291675×
    pub fn decode(b: &[u8]) -> Result<Identity, ObjectError> {
2301675×
        let v = cbor::decode(b)?;
2311675×
        let m = v
2321675×
            .as_map()
2331675×
            .ok_or_else(|| ObjectError::Schema("identity: expected map".into()))?;
2341675×
        check_version(m)?;
2351675×
        let ed = bytes(field(m, 1, "ed25519_pk")?, "ed25519_pk")?;
2361675×
        let ml = bytes(field(m, 2, "mldsa65_pk")?, "mldsa65_pk")?;
2371675×
        if ed.len() != ED25519_PK_LEN || ml.len() != MLDSA65_PK_LEN {
2380×
            return Err(ObjectError::Schema(
2390×
                "identity: wrong public key length".into(),
2400×
            ));
2411675×
        }
2421675×
        let opt_u = |v: &Value| -> Result<Option<u64>, ObjectError> {
2431675×
            if v.is_null() {
2441671×
                Ok(None)
245
            } else {
2464×
                uint(v, "expires").map(Some)
247
            }
2481675×
        };
2491675×
        let opt_r = |v: &Value| -> Result<Option<KeyId>, ObjectError> {
2501675×
            if v.is_null() {
2511223×
                Ok(None)
252
            } else {
253452×
                oref(v, "previous").map(Some)
254
            }
2551675×
        };
2561675×
        let delegates = tidy(
2571675×
            array(field(m, 8, "delegates")?, "delegates")?
2581675×
                .iter()
2591675×
                .map(Delegate::from_value)
2601675×
                .collect::<Result<Vec<_>, _>>()?,
261
        );
262
        Ok(Identity {
2631675×
            ed25519_pk: ed.try_into().unwrap(),
2641675×
            mldsa65_pk: ml.to_vec(),
2651675×
            name: text(field(m, 3, "name")?, "name")?.to_owned(),
2661675×
            email: text(field(m, 4, "email")?, "email")?.to_owned(),
2671675×
            created: uint(field(m, 5, "created")?, "created")?,
2681675×
            expires: opt_u(field(m, 6, "expires")?)?,
2691675×
            previous: opt_r(field(m, 7, "previous")?)?,
2701675×
            delegates,
271
        })
2721675×
    }
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
304467×
    fn ed_key(&self) -> Result<EdVerifyingKey, VerifyError> {
305467×
        EdVerifyingKey::from_bytes(&self.ed25519_pk).map_err(|_| VerifyError::BadKey)
306467×
    }
307448×
    fn ml_key(&self) -> Result<MlVerifyingKey<MlDsa65>, VerifyError> {
308448×
        let enc = EncodedVerifyingKey::<MlDsa65>::try_from(self.mldsa65_pk.as_slice())
309448×
            .map_err(|_| VerifyError::BadKey)?;
310448×
        Ok(MlVerifyingKey::decode(&enc))
311448×
    }
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
}
325
326
impl Domain {
327734×
    pub fn name(self) -> &'static str {
328734×
        match self {
329155×
            Domain::Change => "change",
330454×
            Domain::Attest => "attest",
331113×
            Domain::Policy => "policy",
3323×
            Domain::Challenge => "challenge",
3339×
            Domain::Certificate => "certificate",
334
        }
335734×
    }
336
}
337
338
/// `"oxy1 sig " || domain || 0x00 || KeyId || target` (spec §14.3).
339734×
pub fn signing_message(domain: Domain, key: &KeyId, target: &ObjectRef) -> Vec<u8> {
340734×
    let mut m = Vec::with_capacity(80);
341734×
    m.extend_from_slice(b"oxy1 sig ");
342734×
    m.extend_from_slice(domain.name().as_bytes());
343734×
    m.push(0);
344734×
    m.extend_from_slice(&key.0);
345734×
    m.extend_from_slice(&target.0);
346734×
    m
347734×
}
348
349
#[derive(Clone, PartialEq, Eq)]
350
pub struct Signature {
351
    pub key: KeyId,
352
    pub ed: [u8; ED25519_SIG_LEN],
353
    pub ml: Vec<u8>,
354
}
355
356
impl std::fmt::Debug for Signature {
3570×
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
3580×
        write!(f, "Signature(key {:?})", self.key)
3590×
    }
360
}
361
362
impl Signature {
363534×
    pub fn to_value(&self) -> Value {
364534×
        Value::map([
365534×
            (0, Value::Bytes(self.key.0.to_vec())),
366534×
            (1, Value::Uint(ALG_COMPOSITE)),
367534×
            (2, Value::Bytes(self.ed.to_vec())),
368534×
            (3, Value::Bytes(self.ml.clone())),
369534×
        ])
370534×
    }
3711321×
    pub fn from_value(v: &Value) -> Result<Signature, ObjectError> {
3721321×
        let m = v
3731321×
            .as_map()
3741321×
            .ok_or_else(|| ObjectError::Schema("signature: expected map".into()))?;
3751321×
        let alg = uint(field(m, 1, "alg")?, "alg")?;
3761321×
        if alg != ALG_COMPOSITE {
3770×
            return Err(ObjectError::Schema(format!(
3780×
                "unknown signature algorithm {alg}"
3790×
            )));
3801321×
        }
3811321×
        let ed = bytes(field(m, 2, "ed")?, "ed")?;
3821321×
        let ml = bytes(field(m, 3, "ml")?, "ml")?;
3831321×
        if ed.len() != ED25519_SIG_LEN || ml.len() != MLDSA65_SIG_LEN {
3841×
            return Err(ObjectError::Schema("signature: wrong length".into()));
3851320×
        }
386
        Ok(Signature {
3871320×
            key: oref(field(m, 0, "key")?, "key")?,
3881320×
            ed: ed.try_into().unwrap(),
3891320×
            ml: ml.to_vec(),
390
        })
3911321×
    }
392495×
    pub fn encode_list(sigs: &[Signature]) -> Vec<u8> {
393495×
        cbor::encode(&Value::Array(sigs.iter().map(|s| s.to_value()).collect()))
394495×
    }
3951268×
    pub fn decode_list(b: &[u8]) -> Result<Vec<Signature>, ObjectError> {
3961268×
        let v = cbor::decode(b)?;
3971268×
        array(&v, "signatures")?
3981268×
            .iter()
3991268×
            .map(Signature::from_value)
4001268×
            .collect()
4011268×
    }
402
}
403
404
#[derive(Clone, Copy, Debug, PartialEq, Eq, thiserror::Error)]
405
pub enum VerifyError {
406
    #[error("signature names a different key than the identity")]
407
    KeyMismatch,
408
    #[error("identity holds a malformed public key")]
409
    BadKey,
410
    #[error("Ed25519 signature invalid")]
411
    Ed25519,
412
    #[error("ML-DSA-65 signature invalid")]
413
    MlDsa,
414
    #[error("a challenge is at least 16 bytes")]
415
    ShortChallenge,
416
}
417
418
/// Verify a composite signature by `identity` over `target` (spec §14.3).
419462×
pub fn verify(
420462×
    identity: &Identity,
421462×
    sig: &Signature,
422462×
    domain: Domain,
423462×
    target: &ObjectRef,
424462×
) -> Result<(), VerifyError> {
425462×
    let key = identity.hash();
426462×
    if sig.key != key {
4271×
        return Err(VerifyError::KeyMismatch);
428461×
    }
429461×
    let msg = signing_message(domain, &key, target);
430461×
    let ed_sig = EdSignature::from_bytes(&sig.ed);
431461×
    identity
432461×
        .ed_key()?
433461×
        .verify_strict(&msg, &ed_sig)
434461×
        .map_err(|_| VerifyError::Ed25519)?;
435449×
    let enc =
436449×
        EncodedSignature::<MlDsa65>::try_from(sig.ml.as_slice()).map_err(|_| VerifyError::MlDsa)?;
437449×
    let ml_sig = MlSignature::<MlDsa65>::decode(&enc).ok_or(VerifyError::MlDsa)?;
438448×
    if !identity.ml_key()?.verify_with_context(&msg, b"", &ml_sig) {
4390×
        return Err(VerifyError::MlDsa);
440448×
    }
441448×
    Ok(())
442462×
}
443
444
/// The seeds of a composite key pair. Stored only in the user's key directory.
445
#[derive(Clone)]
446
pub struct SecretKey {
447
    pub ed_seed: [u8; 32],
448
    pub ml_seed: [u8; 32],
449
}
450
451
impl std::fmt::Debug for SecretKey {
4520×
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
4530×
        f.write_str("SecretKey(..)")
4540×
    }
455
}
456
457
impl SecretKey {
45887×
    pub fn generate() -> SecretKey {
45987×
        let mut ed_seed = [0u8; 32];
46087×
        let mut ml_seed = [0u8; 32];
46187×
        rand::rngs::OsRng.fill_bytes(&mut ed_seed);
46287×
        rand::rngs::OsRng.fill_bytes(&mut ml_seed);
46387×
        SecretKey { ed_seed, ml_seed }
46487×
    }
465
466379×
    fn ed(&self) -> EdSigningKey {
467379×
        EdSigningKey::from_bytes(&self.ed_seed)
468379×
    }
469377×
    fn ml(&self) -> MlSigningKey<MlDsa65> {
470377×
        MlSigningKey::from_seed(&Seed::from(self.ml_seed))
471377×
    }
472
473
    /// The identity object for these keys.
474104×
    pub fn identity(&self, name: &str, email: &str, created: u64) -> Identity {
475104×
        Identity {
476104×
            ed25519_pk: self.ed().verifying_key().to_bytes(),
477104×
            mldsa65_pk: self
478104×
                .ml()
479104×
                .expanded_key()
480104×
                .verifying_key()
481104×
                .encode()
482104×
                .as_slice()
483104×
                .to_vec(),
484104×
            name: name.into(),
485104×
            email: email.into(),
486104×
            created,
487104×
            expires: None,
488104×
            previous: None,
489104×
            delegates: vec![],
490104×
        }
491104×
    }
492
493
    /// Ed25519 alone over `msg`, for a format that separates its own
494
    /// domain and whose verifiers know only Ed25519 (DSSE: see
495
    /// [`crate::dsse`]). Oxygen's own objects are signed with [`Self::sign`].
4962×
    pub fn sign_ed25519(&self, msg: &[u8]) -> [u8; 64] {
4972×
        self.ed().sign(msg).to_bytes()
4982×
    }
499
500273×
    pub fn sign(&self, domain: Domain, key: &KeyId, target: &ObjectRef) -> Signature {
501273×
        let msg = signing_message(domain, key, target);
502273×
        let ed = self.ed().sign(&msg).to_bytes();
503273×
        let ml = self
504273×
            .ml()
505273×
            .expanded_key()
506273×
            .sign_deterministic(&msg, b"")
507273×
            .expect("empty context is valid")
508273×
            .encode()
509273×
            .as_slice()
510273×
            .to_vec();
511273×
        Signature { key: *key, ed, ml }
512273×
    }
513
51463×
    pub fn encode(&self, key: &KeyId) -> Vec<u8> {
51563×
        cbor::encode(&Value::map([
51663×
            (0, Value::Uint(FORMAT_VERSION)),
51763×
            (1, Value::Bytes(key.0.to_vec())),
51863×
            (2, Value::Bytes(self.ed_seed.to_vec())),
51963×
            (3, Value::Bytes(self.ml_seed.to_vec())),
52063×
        ]))
52163×
    }
522
523392×
    pub fn decode(b: &[u8]) -> Result<(KeyId, SecretKey), ObjectError> {
524392×
        let v = cbor::decode(b)?;
525392×
        let m = v
526392×
            .as_map()
527392×
            .ok_or_else(|| ObjectError::Schema("secret key: expected map".into()))?;
528392×
        check_version(m)?;
529784×
        let seed = |k: u64| -> Result<[u8; 32], ObjectError> {
530784×
            bytes(field(m, k, "seed")?, "seed")?
531784×
                .try_into()
532784×
                .map_err(|_| ObjectError::Schema("seed: expected 32 bytes".into()))
533784×
        };
534
        Ok((
535392×
            oref(field(m, 1, "key")?, "key")?,
536
            SecretKey {
537392×
                ed_seed: seed(2)?,
538392×
                ml_seed: seed(3)?,
539
            },
540
        ))
541392×
    }
542
}
543
544
#[cfg(test)]
545
mod tests {
546
    use super::*;
547
5486×
    fn fixed_key() -> SecretKey {
5496×
        SecretKey {
5506×
            ed_seed: [1; 32],
5516×
            ml_seed: [2; 32],
5526×
        }
5536×
    }
554
555
    #[test]
5561×
    fn identity_round_trip_and_sizes() {
5571×
        let sk = fixed_key();
5581×
        let id = sk.identity("Ada", "[email protected]", 1_700_000_000_000);
5591×
        assert_eq!(id.mldsa65_pk.len(), MLDSA65_PK_LEN);
5601×
        let d = Identity::decode(&id.encode()).unwrap();
5611×
        assert_eq!(d, id);
5621×
        assert_eq!(d.hash(), id.hash());
563
        // Deterministic from seeds.
5641×
        assert_eq!(
5651×
            fixed_key()
5661×
                .identity("Ada", "[email protected]", 1_700_000_000_000)
5671×
                .hash(),
5681×
            id.hash()
569
        );
5701×
        let mut other = id.clone();
5711×
        other.delegates.push(Delegate::full(ObjectRef([9; 32])));
5721×
        assert_ne!(other.hash(), id.hash());
5731×
    }
574
575
    #[test]
5761×
    fn delegates_carry_scope_and_expiry_and_bare_keys_mean_every_scope() {
5771×
        let sk = fixed_key();
5781×
        let mut id = sk.identity("Ada", "[email protected]", 1_700_000_000_000);
5791×
        let agent = ObjectRef([7; 32]);
5801×
        let host = ObjectRef([3; 32]);
5811×
        id.delegates = vec![
5821×
            Delegate {
5831×
                key: agent,
5841×
                scope: Scope::CHANGES,
5851×
                expires: Some(2_000),
5861×
            },
5871×
            Delegate {
5881×
                key: host,
5891×
                scope: Scope::CHANGES | Scope::REFS,
5901×
                expires: None,
5911×
            },
592
        ];
5931×
        let d = Identity::decode(&id.encode()).unwrap();
5941×
        assert_eq!(d.delegates.len(), 2);
5951×
        assert!(d.delegates_to(&agent, Scope::CHANGES, 1_000));
5961×
        assert!(!d.delegates_to(&agent, Scope::CHANGES, 2_001), "expired");
5971×
        assert!(!d.delegates_to(&agent, Scope::REFS, 1_000));
5981×
        assert!(!d.delegates_to(&agent, Scope::SEAL, 1_000));
5991×
        assert!(d.delegates_to(&host, Scope::REFS, u64::MAX));
6001×
        assert!(!d.delegates_to(&host, Scope::SEAL, 0));
6011×
        assert!(!d.delegates_to(&ObjectRef([1; 32]), Scope::CHANGES, 0));
6021×
        assert_eq!(
6031×
            Scope::parse("changes, refs").unwrap(),
6041×
            Scope::CHANGES | Scope::REFS
605
        );
6061×
        assert_eq!(Scope::parse("all").unwrap(), Scope::ALL);
6071×
        assert_eq!((Scope::CHANGES | Scope::SEAL).to_string(), "changes,seal");
6081×
        assert!(Scope::parse("push").is_err() && Scope::parse("").is_err());
609
        // An identity written before scopes existed lists bare KeyIds.
6101×
        let mut v = id.to_value();
6111×
        if let Value::Map(m) = &mut v {
6121×
            m.insert(8, Value::Array(vec![Value::Bytes(host.0.to_vec())]));
6131×
        }
6141×
        let old = Identity::decode(&cbor::encode(&v)).unwrap();
6151×
        assert_eq!(old.delegates, vec![Delegate::full(host)]);
6161×
        assert!(old.delegates_to(&host, Scope::ALL, u64::MAX));
6171×
    }
618
619
    #[test]
6201×
    fn sign_and_verify() {
6211×
        let sk = fixed_key();
6221×
        let id = sk.identity("Ada", "[email protected]", 1);
6231×
        let key = id.hash();
6241×
        let target = ObjectRef([7; 32]);
6251×
        let sig = sk.sign(Domain::Change, &key, &target);
6261×
        assert_eq!(sig.ml.len(), MLDSA65_SIG_LEN);
6271×
        assert_eq!(verify(&id, &sig, Domain::Change, &target), Ok(()));
628
        // Different target, different domain: invalid.
6291×
        assert_eq!(
6301×
            verify(&id, &sig, Domain::Change, &ObjectRef([8; 32])),
631
            Err(VerifyError::Ed25519)
632
        );
6331×
        assert_eq!(
6341×
            verify(&id, &sig, Domain::Attest, &target),
635
            Err(VerifyError::Ed25519)
636
        );
637
        // Deterministic signatures.
6381×
        assert_eq!(sk.sign(Domain::Change, &key, &target), sig);
639
        // Signature list round trip.
6401×
        let l =
6411×
            Signature::decode_list(&Signature::encode_list(std::slice::from_ref(&sig))).unwrap();
6421×
        assert_eq!(l, vec![sig]);
6431×
    }
644
645
    #[test]
6461×
    fn stripping_or_forging_either_half_fails() {
6471×
        let sk = fixed_key();
6481×
        let id = sk.identity("Ada", "a@b", 1);
6491×
        let key = id.hash();
6501×
        let target = ObjectRef([7; 32]);
6511×
        let good = sk.sign(Domain::Change, &key, &target);
652
6531×
        let mut no_ml = good.clone();
6541×
        no_ml.ml = vec![0; MLDSA65_SIG_LEN];
6551×
        assert_eq!(
6561×
            verify(&id, &no_ml, Domain::Change, &target),
657
            Err(VerifyError::MlDsa)
658
        );
659
6601×
        let mut bad_ed = good.clone();
6611×
        bad_ed.ed[10] ^= 1;
6621×
        assert_eq!(
6631×
            verify(&id, &bad_ed, Domain::Change, &target),
664
            Err(VerifyError::Ed25519)
665
        );
666
667
        // A signature made for another KeyId over the same target does not transfer.
6681×
        let other = SecretKey {
6691×
            ed_seed: [3; 32],
6701×
            ml_seed: [4; 32],
6711×
        };
6721×
        let other_id = other.identity("Bob", "b@b", 1);
6731×
        let theirs = other.sign(Domain::Change, &other_id.hash(), &target);
6741×
        assert_eq!(
6751×
            verify(&id, &theirs, Domain::Change, &target),
676
            Err(VerifyError::KeyMismatch)
677
        );
6781×
        let mut relabelled = theirs.clone();
6791×
        relabelled.key = key;
6801×
        assert_eq!(
6811×
            verify(&id, &relabelled, Domain::Change, &target),
682
            Err(VerifyError::Ed25519)
683
        );
684
685
        // Wrong length is rejected at decode time.
6861×
        let mut short = good.to_value();
6871×
        if let Value::Map(m) = &mut short {
6881×
            m.insert(3, Value::Bytes(vec![0; 10]));
6891×
        }
6901×
        assert!(Signature::from_value(&short).is_err());
6911×
    }
692
693
    #[test]
6941×
    fn secret_key_round_trip() {
6951×
        let sk = fixed_key();
6961×
        let key = sk.identity("x", "y", 0).hash();
6971×
        let (k, d) = SecretKey::decode(&sk.encode(&key)).unwrap();
6981×
        assert_eq!(k, key);
6991×
        assert_eq!(d.ed_seed, sk.ed_seed);
7001×
        assert_eq!(d.ml_seed, sk.ml_seed);
7011×
        assert_ne!(SecretKey::generate().ed_seed, SecretKey::generate().ed_seed);
7021×
    }
703
}
704
705
/// The signing target of a challenge: `BLAKE3-256("oxy1 challenge " || bytes)`,
706
/// so a challenge can never collide with a stored object's reference.
7074×
pub fn challenge_target(challenge: &[u8]) -> ObjectRef {
7084×
    let mut h = blake3::Hasher::new();
7094×
    h.update(b"oxy1 challenge ");
7104×
    h.update(challenge);
7114×
    ObjectRef(*h.finalize().as_bytes())
7124×
}
713
714
impl SecretKey {
715
    /// Sign a host's challenge (at least 16 bytes) with this key.
7162×
    pub fn sign_challenge(&self, key: &KeyId, challenge: &[u8]) -> Result<Signature, VerifyError> {
7172×
        if challenge.len() < 16 {
7181×
            return Err(VerifyError::ShortChallenge);
7191×
        }
7201×
        Ok(self.sign(Domain::Challenge, key, &challenge_target(challenge)))
7212×
    }
722
}
723
724
/// Check a challenge signature against the identity that claims it.
7253×
pub fn verify_challenge(
7263×
    identity: &Identity,
7273×
    sig: &Signature,
7283×
    challenge: &[u8],
7293×
) -> Result<(), VerifyError> {
7303×
    if challenge.len() < 16 {
7310×
        return Err(VerifyError::ShortChallenge);
7323×
    }
7333×
    if sig.key != identity.hash() {
7341×
        return Err(VerifyError::KeyMismatch);
7352×
    }
7362×
    verify(
7372×
        identity,
7382×
        sig,
7392×
        Domain::Challenge,
7402×
        &challenge_target(challenge),
741
    )
7423×
}
743
744
#[cfg(test)]
745
mod challenge_tests {
746
    use super::*;
747
748
    #[test]
7491×
    fn a_challenge_signature_binds_key_and_bytes() {
7501×
        let sk = SecretKey::generate();
7511×
        let id = sk.identity("A", "a@example", 1);
7521×
        let key = id.hash();
7531×
        let challenge = [7u8; 32];
7541×
        let sig = sk.sign_challenge(&key, &challenge).unwrap();
7551×
        assert!(verify_challenge(&id, &sig, &challenge).is_ok());
7561×
        assert!(
7571×
            verify_challenge(&id, &sig, &[8u8; 32]).is_err(),
758
            "other bytes"
759
        );
7601×
        let other = SecretKey::generate().identity("B", "b@example", 1);
7611×
        assert!(
7621×
            verify_challenge(&other, &sig, &challenge).is_err(),
763
            "other identity"
764
        );
7651×
        assert!(sk.sign_challenge(&key, b"short").is_err());
766
        // A challenge target never equals a change signature's target for the same bytes.
7671×
        assert_ne!(challenge_target(&challenge), ObjectRef(challenge));
7681×
    }
769
}