OXYGENHUB

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

500 of 523 lines run, 102 of 137 functions · run #315 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
491359×
    pub fn has(self, other: Scope) -> bool {
501359×
        self.0 & other.0 == other.0
511359×
    }
5299×
    pub fn is_empty(self) -> bool {
5399×
        self.0 == 0
5499×
    }
55
    /// The names in the set, in the order they are written.
56415×
    pub fn names(self) -> Vec<&'static str> {
57415×
        Self::NAMES
58415×
            .iter()
591245×
            .filter(|(s, _)| self.has(*s))
60415×
            .map(|(_, n)| *n)
61415×
            .collect()
62415×
    }
63902×
    pub(crate) fn named(name: &str) -> Option<Scope> {
64902×
        Self::NAMES
65902×
            .iter()
661545×
            .find(|(_, n)| *n == name)
67902×
            .map(|(s, _)| *s)
68902×
    }
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;
90931×
    fn bitor(self, rhs: Scope) -> Scope {
91931×
        Scope(self.0 | rhs.0)
92931×
    }
93
}
94
95
impl std::fmt::Display for Scope {
9614×
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
9714×
        f.write_str(&self.names().join(","))
9814×
    }
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`.
12630×
    pub fn allows(&self, scope: Scope, at_ms: u64) -> bool {
12730×
        self.scope.has(scope) && !self.expires.is_some_and(|e| at_ms > e)
12830×
    }
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.
147219×
    fn from_value(v: &Value) -> Result<Delegate, ObjectError> {
148219×
        if let Value::Bytes(_) = v {
1491×
            return Ok(Delegate::full(oref(v, "delegate")?));
150218×
        }
151218×
        let m = v
152218×
            .as_map()
153218×
            .ok_or_else(|| ObjectError::Schema("delegate: expected map".into()))?;
154218×
        let key = oref(field(m, 0, "delegate key")?, "delegate key")?;
155218×
        let mut scope = Scope::NONE;
156474×
        for n in array(field(m, 1, "delegate scope")?, "delegate scope")? {
157474×
            let n = text(n, "delegate scope")?;
158474×
            scope = scope
159474×
                | Scope::named(n)
160474×
                    .ok_or_else(|| ObjectError::Schema(format!("delegate: unknown scope {n:?}")))?;
161
        }
162218×
        let expires = match field(m, 2, "delegate expires")? {
163218×
            v if v.is_null() => None,
1645×
            v => Some(uint(v, "delegate expires")?),
165
        };
166218×
        Ok(Delegate {
167218×
            key,
168218×
            scope,
169218×
            expires,
170218×
        })
171219×
    }
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.
1872156×
fn tidy(mut delegates: Vec<Delegate>) -> Vec<Delegate> {
1882156×
    delegates.sort_by_key(|d| d.key);
1892156×
    delegates.dedup_by(|a, b| a.key == b.key);
1902156×
    delegates
1912156×
}
192
193
impl Identity {
194
    /// The delegation to `key`, if any.
19583×
    pub fn delegate(&self, key: &KeyId) -> Option<&Delegate> {
19683×
        self.delegates.iter().find(|d| d.key == *key)
19783×
    }
198
    /// Whether `key` may act for this identity within `scope` at `at_ms`.
19930×
    pub fn delegates_to(&self, key: &KeyId, scope: Scope, at_ms: u64) -> bool {
20030×
        self.delegate(key).is_some_and(|d| d.allows(scope, at_ms))
20130×
    }
2022372×
    pub fn to_value(&self) -> Value {
2032372×
        Value::map([
2042372×
            (0, Value::Uint(FORMAT_VERSION)),
2052372×
            (1, Value::Bytes(self.ed25519_pk.to_vec())),
2062372×
            (2, Value::Bytes(self.mldsa65_pk.clone())),
2072372×
            (3, Value::Text(self.name.clone())),
2082372×
            (4, Value::Text(self.email.clone())),
2092372×
            (5, Value::Uint(self.created)),
2102372×
            (6, self.expires.map(Value::Uint).unwrap_or(Value::Null)),
211
            (
212
                7,
2132372×
                self.previous
2142372×
                    .map(|p| Value::Bytes(p.0.to_vec()))
2152372×
                    .unwrap_or(Value::Null),
216
            ),
217
            (
218
                8,
2192372×
                Value::Array(self.delegates.iter().map(|d| d.to_value()).collect()),
220
            ),
221
        ])
2222372×
    }
2232371×
    pub fn encode(&self) -> Vec<u8> {
2242371×
        cbor::encode(&self.to_value())
2252371×
    }
2261192×
    pub fn hash(&self) -> KeyId {
2271192×
        hash_object(ObjectType::Identity, &self.encode())
2281192×
    }
2292143×
    pub fn decode(b: &[u8]) -> Result<Identity, ObjectError> {
2302143×
        let v = cbor::decode(b)?;
2312143×
        let m = v
2322143×
            .as_map()
2332143×
            .ok_or_else(|| ObjectError::Schema("identity: expected map".into()))?;
2342143×
        check_version(m)?;
2352143×
        let ed = bytes(field(m, 1, "ed25519_pk")?, "ed25519_pk")?;
2362143×
        let ml = bytes(field(m, 2, "mldsa65_pk")?, "mldsa65_pk")?;
2372143×
        if ed.len() != ED25519_PK_LEN || ml.len() != MLDSA65_PK_LEN {
2380×
            return Err(ObjectError::Schema(
2390×
                "identity: wrong public key length".into(),
2400×
            ));
2412143×
        }
2422143×
        let opt_u = |v: &Value| -> Result<Option<u64>, ObjectError> {
2432143×
            if v.is_null() {
2442139×
                Ok(None)
245
            } else {
2464×
                uint(v, "expires").map(Some)
247
            }
2482143×
        };
2492143×
        let opt_r = |v: &Value| -> Result<Option<KeyId>, ObjectError> {
2502143×
            if v.is_null() {
2511689×
                Ok(None)
252
            } else {
253454×
                oref(v, "previous").map(Some)
254
            }
2552143×
        };
2562143×
        let delegates = tidy(
2572143×
            array(field(m, 8, "delegates")?, "delegates")?
2582143×
                .iter()
2592143×
                .map(Delegate::from_value)
2602143×
                .collect::<Result<Vec<_>, _>>()?,
261
        );
262
        Ok(Identity {
2632143×
            ed25519_pk: ed.try_into().unwrap(),
2642143×
            mldsa65_pk: ml.to_vec(),
2652143×
            name: text(field(m, 3, "name")?, "name")?.to_owned(),
2662143×
            email: text(field(m, 4, "email")?, "email")?.to_owned(),
2672143×
            created: uint(field(m, 5, "created")?, "created")?,
2682143×
            expires: opt_u(field(m, 6, "expires")?)?,
2692143×
            previous: opt_r(field(m, 7, "previous")?)?,
2702143×
            delegates,
271
        })
2722143×
    }
273
274
    /// Whether the identity is past its expiry at `now_ms`.
275231×
    pub fn is_expired_at(&self, now_ms: u64) -> bool {
276231×
        self.expires.is_some_and(|e| now_ms > e)
277231×
    }
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
304584×
    fn ed_key(&self) -> Result<EdVerifyingKey, VerifyError> {
305584×
        EdVerifyingKey::from_bytes(&self.ed25519_pk).map_err(|_| VerifyError::BadKey)
306584×
    }
307564×
    fn ml_key(&self) -> Result<MlVerifyingKey<MlDsa65>, VerifyError> {
308564×
        let enc = EncodedVerifyingKey::<MlDsa65>::try_from(self.mldsa65_pk.as_slice())
309564×
            .map_err(|_| VerifyError::BadKey)?;
310564×
        Ok(MlVerifyingKey::decode(&enc))
311564×
    }
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
}
327
328
impl Domain {
329903×
    pub fn name(self) -> &'static str {
330903×
        match self {
331156×
            Domain::Change => "change",
332520×
            Domain::Attest => "attest",
333141×
            Domain::Policy => "policy",
3346×
            Domain::Challenge => "challenge",
33567×
            Domain::Certificate => "certificate",
33613×
            Domain::Grant => "grant",
337
        }
338903×
    }
339
}
340
341
/// `"oxy1 sig " || domain || 0x00 || KeyId || target` (spec §14.3).
342903×
pub fn signing_message(domain: Domain, key: &KeyId, target: &ObjectRef) -> Vec<u8> {
343903×
    let mut m = Vec::with_capacity(80);
344903×
    m.extend_from_slice(b"oxy1 sig ");
345903×
    m.extend_from_slice(domain.name().as_bytes());
346903×
    m.push(0);
347903×
    m.extend_from_slice(&key.0);
348903×
    m.extend_from_slice(&target.0);
349903×
    m
350903×
}
351
352
#[derive(Clone, PartialEq, Eq)]
353
pub struct Signature {
354
    pub key: KeyId,
355
    pub ed: [u8; ED25519_SIG_LEN],
356
    pub ml: Vec<u8>,
357
}
358
359
impl std::fmt::Debug for Signature {
3600×
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
3610×
        write!(f, "Signature(key {:?})", self.key)
3620×
    }
363
}
364
365
impl Signature {
366696×
    pub fn to_value(&self) -> Value {
367696×
        Value::map([
368696×
            (0, Value::Bytes(self.key.0.to_vec())),
369696×
            (1, Value::Uint(ALG_COMPOSITE)),
370696×
            (2, Value::Bytes(self.ed.to_vec())),
371696×
            (3, Value::Bytes(self.ml.clone())),
372696×
        ])
373696×
    }
3741672×
    pub fn from_value(v: &Value) -> Result<Signature, ObjectError> {
3751672×
        let m = v
3761672×
            .as_map()
3771672×
            .ok_or_else(|| ObjectError::Schema("signature: expected map".into()))?;
3781672×
        let alg = uint(field(m, 1, "alg")?, "alg")?;
3791672×
        if alg != ALG_COMPOSITE {
3800×
            return Err(ObjectError::Schema(format!(
3810×
                "unknown signature algorithm {alg}"
3820×
            )));
3831672×
        }
3841672×
        let ed = bytes(field(m, 2, "ed")?, "ed")?;
3851672×
        let ml = bytes(field(m, 3, "ml")?, "ml")?;
3861672×
        if ed.len() != ED25519_SIG_LEN || ml.len() != MLDSA65_SIG_LEN {
3871×
            return Err(ObjectError::Schema("signature: wrong length".into()));
3881671×
        }
389
        Ok(Signature {
3901671×
            key: oref(field(m, 0, "key")?, "key")?,
3911671×
            ed: ed.try_into().unwrap(),
3921671×
            ml: ml.to_vec(),
393
        })
3941672×
    }
395601×
    pub fn encode_list(sigs: &[Signature]) -> Vec<u8> {
396601×
        cbor::encode(&Value::Array(sigs.iter().map(|s| s.to_value()).collect()))
397601×
    }
3981588×
    pub fn decode_list(b: &[u8]) -> Result<Vec<Signature>, ObjectError> {
3991588×
        let v = cbor::decode(b)?;
4001588×
        array(&v, "signatures")?
4011588×
            .iter()
4021588×
            .map(Signature::from_value)
4031588×
            .collect()
4041588×
    }
405
}
406
407
#[derive(Clone, Copy, Debug, PartialEq, Eq, thiserror::Error)]
408
pub enum VerifyError {
409
    #[error("signature names a different key than the identity")]
410
    KeyMismatch,
411
    #[error("identity holds a malformed public key")]
412
    BadKey,
413
    #[error("Ed25519 signature invalid")]
414
    Ed25519,
415
    #[error("ML-DSA-65 signature invalid")]
416
    MlDsa,
417
    #[error("a challenge is at least 16 bytes")]
418
    ShortChallenge,
419
}
420
421
/// Verify a composite signature by `identity` over `target` (spec §14.3).
422579×
pub fn verify(
423579×
    identity: &Identity,
424579×
    sig: &Signature,
425579×
    domain: Domain,
426579×
    target: &ObjectRef,
427579×
) -> Result<(), VerifyError> {
428579×
    let key = identity.hash();
429579×
    if sig.key != key {
4301×
        return Err(VerifyError::KeyMismatch);
431578×
    }
432578×
    let msg = signing_message(domain, &key, target);
433578×
    let ed_sig = EdSignature::from_bytes(&sig.ed);
434578×
    identity
435578×
        .ed_key()?
436578×
        .verify_strict(&msg, &ed_sig)
437578×
        .map_err(|_| VerifyError::Ed25519)?;
438565×
    let enc =
439565×
        EncodedSignature::<MlDsa65>::try_from(sig.ml.as_slice()).map_err(|_| VerifyError::MlDsa)?;
440565×
    let ml_sig = MlSignature::<MlDsa65>::decode(&enc).ok_or(VerifyError::MlDsa)?;
441564×
    if !identity.ml_key()?.verify_with_context(&msg, b"", &ml_sig) {
4420×
        return Err(VerifyError::MlDsa);
443564×
    }
444564×
    Ok(())
445579×
}
446
447
/// The seeds of a composite key pair. Stored only in the user's key directory.
448
#[derive(Clone)]
449
pub struct SecretKey {
450
    pub ed_seed: [u8; 32],
451
    pub ml_seed: [u8; 32],
452
}
453
454
impl std::fmt::Debug for SecretKey {
4550×
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
4560×
        f.write_str("SecretKey(..)")
4570×
    }
458
}
459
460
impl SecretKey {
461112×
    pub fn generate() -> SecretKey {
462112×
        let mut ed_seed = [0u8; 32];
463112×
        let mut ml_seed = [0u8; 32];
464112×
        rand::rngs::OsRng.fill_bytes(&mut ed_seed);
465112×
        rand::rngs::OsRng.fill_bytes(&mut ml_seed);
466112×
        SecretKey { ed_seed, ml_seed }
467112×
    }
468
469458×
    fn ed(&self) -> EdSigningKey {
470458×
        EdSigningKey::from_bytes(&self.ed_seed)
471458×
    }
472456×
    fn ml(&self) -> MlSigningKey<MlDsa65> {
473456×
        MlSigningKey::from_seed(&Seed::from(self.ml_seed))
474456×
    }
475
476
    /// The identity object for these keys.
477131×
    pub fn identity(&self, name: &str, email: &str, created: u64) -> Identity {
478131×
        Identity {
479131×
            ed25519_pk: self.ed().verifying_key().to_bytes(),
480131×
            mldsa65_pk: self
481131×
                .ml()
482131×
                .expanded_key()
483131×
                .verifying_key()
484131×
                .encode()
485131×
                .as_slice()
486131×
                .to_vec(),
487131×
            name: name.into(),
488131×
            email: email.into(),
489131×
            created,
490131×
            expires: None,
491131×
            previous: None,
492131×
            delegates: vec![],
493131×
        }
494131×
    }
495
496
    /// Ed25519 alone over `msg`, for a format that separates its own
497
    /// domain and whose verifiers know only Ed25519 (DSSE: see
498
    /// [`crate::dsse`]). Oxygen's own objects are signed with [`Self::sign`].
4992×
    pub fn sign_ed25519(&self, msg: &[u8]) -> [u8; 64] {
5002×
        self.ed().sign(msg).to_bytes()
5012×
    }
502
503325×
    pub fn sign(&self, domain: Domain, key: &KeyId, target: &ObjectRef) -> Signature {
504325×
        let msg = signing_message(domain, key, target);
505325×
        let ed = self.ed().sign(&msg).to_bytes();
506325×
        let ml = self
507325×
            .ml()
508325×
            .expanded_key()
509325×
            .sign_deterministic(&msg, b"")
510325×
            .expect("empty context is valid")
511325×
            .encode()
512325×
            .as_slice()
513325×
            .to_vec();
514325×
        Signature { key: *key, ed, ml }
515325×
    }
516
51773×
    pub fn encode(&self, key: &KeyId) -> Vec<u8> {
51873×
        cbor::encode(&Value::map([
51973×
            (0, Value::Uint(FORMAT_VERSION)),
52073×
            (1, Value::Bytes(key.0.to_vec())),
52173×
            (2, Value::Bytes(self.ed_seed.to_vec())),
52273×
            (3, Value::Bytes(self.ml_seed.to_vec())),
52373×
        ]))
52473×
    }
525
526443×
    pub fn decode(b: &[u8]) -> Result<(KeyId, SecretKey), ObjectError> {
527443×
        let v = cbor::decode(b)?;
528443×
        let m = v
529443×
            .as_map()
530443×
            .ok_or_else(|| ObjectError::Schema("secret key: expected map".into()))?;
531443×
        check_version(m)?;
532886×
        let seed = |k: u64| -> Result<[u8; 32], ObjectError> {
533886×
            bytes(field(m, k, "seed")?, "seed")?
534886×
                .try_into()
535886×
                .map_err(|_| ObjectError::Schema("seed: expected 32 bytes".into()))
536886×
        };
537
        Ok((
538443×
            oref(field(m, 1, "key")?, "key")?,
539
            SecretKey {
540443×
                ed_seed: seed(2)?,
541443×
                ml_seed: seed(3)?,
542
            },
543
        ))
544443×
    }
545
}
546
547
#[cfg(test)]
548
mod tests {
549
    use super::*;
550
5516×
    fn fixed_key() -> SecretKey {
5526×
        SecretKey {
5536×
            ed_seed: [1; 32],
5546×
            ml_seed: [2; 32],
5556×
        }
5566×
    }
557
558
    #[test]
5591×
    fn identity_round_trip_and_sizes() {
5601×
        let sk = fixed_key();
5611×
        let id = sk.identity("Ada", "[email protected]", 1_700_000_000_000);
5621×
        assert_eq!(id.mldsa65_pk.len(), MLDSA65_PK_LEN);
5631×
        let d = Identity::decode(&id.encode()).unwrap();
5641×
        assert_eq!(d, id);
5651×
        assert_eq!(d.hash(), id.hash());
566
        // Deterministic from seeds.
5671×
        assert_eq!(
5681×
            fixed_key()
5691×
                .identity("Ada", "[email protected]", 1_700_000_000_000)
5701×
                .hash(),
5711×
            id.hash()
572
        );
5731×
        let mut other = id.clone();
5741×
        other.delegates.push(Delegate::full(ObjectRef([9; 32])));
5751×
        assert_ne!(other.hash(), id.hash());
5761×
    }
577
578
    #[test]
5791×
    fn delegates_carry_scope_and_expiry_and_bare_keys_mean_every_scope() {
5801×
        let sk = fixed_key();
5811×
        let mut id = sk.identity("Ada", "[email protected]", 1_700_000_000_000);
5821×
        let agent = ObjectRef([7; 32]);
5831×
        let host = ObjectRef([3; 32]);
5841×
        id.delegates = vec![
5851×
            Delegate {
5861×
                key: agent,
5871×
                scope: Scope::CHANGES,
5881×
                expires: Some(2_000),
5891×
            },
5901×
            Delegate {
5911×
                key: host,
5921×
                scope: Scope::CHANGES | Scope::REFS,
5931×
                expires: None,
5941×
            },
595
        ];
5961×
        let d = Identity::decode(&id.encode()).unwrap();
5971×
        assert_eq!(d.delegates.len(), 2);
5981×
        assert!(d.delegates_to(&agent, Scope::CHANGES, 1_000));
5991×
        assert!(!d.delegates_to(&agent, Scope::CHANGES, 2_001), "expired");
6001×
        assert!(!d.delegates_to(&agent, Scope::REFS, 1_000));
6011×
        assert!(!d.delegates_to(&agent, Scope::SEAL, 1_000));
6021×
        assert!(d.delegates_to(&host, Scope::REFS, u64::MAX));
6031×
        assert!(!d.delegates_to(&host, Scope::SEAL, 0));
6041×
        assert!(!d.delegates_to(&ObjectRef([1; 32]), Scope::CHANGES, 0));
6051×
        assert_eq!(
6061×
            Scope::parse("changes, refs").unwrap(),
6071×
            Scope::CHANGES | Scope::REFS
608
        );
6091×
        assert_eq!(Scope::parse("all").unwrap(), Scope::ALL);
6101×
        assert_eq!((Scope::CHANGES | Scope::SEAL).to_string(), "changes,seal");
6111×
        assert!(Scope::parse("push").is_err() && Scope::parse("").is_err());
612
        // An identity written before scopes existed lists bare KeyIds.
6131×
        let mut v = id.to_value();
6141×
        if let Value::Map(m) = &mut v {
6151×
            m.insert(8, Value::Array(vec![Value::Bytes(host.0.to_vec())]));
6161×
        }
6171×
        let old = Identity::decode(&cbor::encode(&v)).unwrap();
6181×
        assert_eq!(old.delegates, vec![Delegate::full(host)]);
6191×
        assert!(old.delegates_to(&host, Scope::ALL, u64::MAX));
6201×
    }
621
622
    #[test]
6231×
    fn sign_and_verify() {
6241×
        let sk = fixed_key();
6251×
        let id = sk.identity("Ada", "[email protected]", 1);
6261×
        let key = id.hash();
6271×
        let target = ObjectRef([7; 32]);
6281×
        let sig = sk.sign(Domain::Change, &key, &target);
6291×
        assert_eq!(sig.ml.len(), MLDSA65_SIG_LEN);
6301×
        assert_eq!(verify(&id, &sig, Domain::Change, &target), Ok(()));
631
        // Different target, different domain: invalid.
6321×
        assert_eq!(
6331×
            verify(&id, &sig, Domain::Change, &ObjectRef([8; 32])),
634
            Err(VerifyError::Ed25519)
635
        );
6361×
        assert_eq!(
6371×
            verify(&id, &sig, Domain::Attest, &target),
638
            Err(VerifyError::Ed25519)
639
        );
640
        // Deterministic signatures.
6411×
        assert_eq!(sk.sign(Domain::Change, &key, &target), sig);
642
        // Signature list round trip.
6431×
        let l =
6441×
            Signature::decode_list(&Signature::encode_list(std::slice::from_ref(&sig))).unwrap();
6451×
        assert_eq!(l, vec![sig]);
6461×
    }
647
648
    #[test]
6491×
    fn stripping_or_forging_either_half_fails() {
6501×
        let sk = fixed_key();
6511×
        let id = sk.identity("Ada", "a@b", 1);
6521×
        let key = id.hash();
6531×
        let target = ObjectRef([7; 32]);
6541×
        let good = sk.sign(Domain::Change, &key, &target);
655
6561×
        let mut no_ml = good.clone();
6571×
        no_ml.ml = vec![0; MLDSA65_SIG_LEN];
6581×
        assert_eq!(
6591×
            verify(&id, &no_ml, Domain::Change, &target),
660
            Err(VerifyError::MlDsa)
661
        );
662
6631×
        let mut bad_ed = good.clone();
6641×
        bad_ed.ed[10] ^= 1;
6651×
        assert_eq!(
6661×
            verify(&id, &bad_ed, Domain::Change, &target),
667
            Err(VerifyError::Ed25519)
668
        );
669
670
        // A signature made for another KeyId over the same target does not transfer.
6711×
        let other = SecretKey {
6721×
            ed_seed: [3; 32],
6731×
            ml_seed: [4; 32],
6741×
        };
6751×
        let other_id = other.identity("Bob", "b@b", 1);
6761×
        let theirs = other.sign(Domain::Change, &other_id.hash(), &target);
6771×
        assert_eq!(
6781×
            verify(&id, &theirs, Domain::Change, &target),
679
            Err(VerifyError::KeyMismatch)
680
        );
6811×
        let mut relabelled = theirs.clone();
6821×
        relabelled.key = key;
6831×
        assert_eq!(
6841×
            verify(&id, &relabelled, Domain::Change, &target),
685
            Err(VerifyError::Ed25519)
686
        );
687
688
        // Wrong length is rejected at decode time.
6891×
        let mut short = good.to_value();
6901×
        if let Value::Map(m) = &mut short {
6911×
            m.insert(3, Value::Bytes(vec![0; 10]));
6921×
        }
6931×
        assert!(Signature::from_value(&short).is_err());
6941×
    }
695
696
    #[test]
6971×
    fn secret_key_round_trip() {
6981×
        let sk = fixed_key();
6991×
        let key = sk.identity("x", "y", 0).hash();
7001×
        let (k, d) = SecretKey::decode(&sk.encode(&key)).unwrap();
7011×
        assert_eq!(k, key);
7021×
        assert_eq!(d.ed_seed, sk.ed_seed);
7031×
        assert_eq!(d.ml_seed, sk.ml_seed);
7041×
        assert_ne!(SecretKey::generate().ed_seed, SecretKey::generate().ed_seed);
7051×
    }
706
}
707
708
/// The signing target of a challenge: `BLAKE3-256("oxy1 challenge " || bytes)`,
709
/// so a challenge can never collide with a stored object's reference.
7107×
pub fn challenge_target(challenge: &[u8]) -> ObjectRef {
7117×
    let mut h = blake3::Hasher::new();
7127×
    h.update(b"oxy1 challenge ");
7137×
    h.update(challenge);
7147×
    ObjectRef(*h.finalize().as_bytes())
7157×
}
716
717
impl SecretKey {
718
    /// Sign a host's challenge (at least 16 bytes) with this key.
7193×
    pub fn sign_challenge(&self, key: &KeyId, challenge: &[u8]) -> Result<Signature, VerifyError> {
7203×
        if challenge.len() < 16 {
7211×
            return Err(VerifyError::ShortChallenge);
7222×
        }
7232×
        Ok(self.sign(Domain::Challenge, key, &challenge_target(challenge)))
7243×
    }
725
}
726
727
/// Check a challenge signature against the identity that claims it.
7285×
pub fn verify_challenge(
7295×
    identity: &Identity,
7305×
    sig: &Signature,
7315×
    challenge: &[u8],
7325×
) -> Result<(), VerifyError> {
7335×
    if challenge.len() < 16 {
7340×
        return Err(VerifyError::ShortChallenge);
7355×
    }
7365×
    if sig.key != identity.hash() {
7371×
        return Err(VerifyError::KeyMismatch);
7384×
    }
7394×
    verify(
7404×
        identity,
7414×
        sig,
7424×
        Domain::Challenge,
7434×
        &challenge_target(challenge),
744
    )
7455×
}
746
747
#[cfg(test)]
748
mod challenge_tests {
749
    use super::*;
750
751
    #[test]
7521×
    fn a_challenge_signature_binds_key_and_bytes() {
7531×
        let sk = SecretKey::generate();
7541×
        let id = sk.identity("A", "a@example", 1);
7551×
        let key = id.hash();
7561×
        let challenge = [7u8; 32];
7571×
        let sig = sk.sign_challenge(&key, &challenge).unwrap();
7581×
        assert!(verify_challenge(&id, &sig, &challenge).is_ok());
7591×
        assert!(
7601×
            verify_challenge(&id, &sig, &[8u8; 32]).is_err(),
761
            "other bytes"
762
        );
7631×
        let other = SecretKey::generate().identity("B", "b@example", 1);
7641×
        assert!(
7651×
            verify_challenge(&other, &sig, &challenge).is_err(),
766
            "other identity"
767
        );
7681×
        assert!(sk.sign_challenge(&key, b"short").is_err());
769
        // A challenge target never equals a change signature's target for the same bytes.
7701×
        assert_ne!(challenge_target(&challenge), ObjectRef(challenge));
7711×
    }
772
}