OXYGENHUB
# 02e691881a4e oxygen / crates / oxy-core / src / identity.rs
25.4 KiB · Rust · last changed Certificates for short-lived keys (keyless, step 1) 18 days ago source blame history raw
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
49
    pub fn has(self, other: Scope) -> bool {
50
        self.0 & other.0 == other.0
51
    }
52
    pub fn is_empty(self) -> bool {
53
        self.0 == 0
54
    }
55
    /// The names in the set, in the order they are written.
56
    pub fn names(self) -> Vec<&'static str> {
57
        Self::NAMES
58
            .iter()
59
            .filter(|(s, _)| self.has(*s))
60
            .map(|(_, n)| *n)
61
            .collect()
62
    }
63
    pub(crate) fn named(name: &str) -> Option<Scope> {
64
        Self::NAMES
65
            .iter()
66
            .find(|(_, n)| *n == name)
67
            .map(|(s, _)| *s)
68
    }
69
    /// `changes,refs` (also with spaces); `all` is every scope.
70
    pub fn parse(s: &str) -> Result<Scope, String> {
71
        let mut out = Scope::NONE;
72
        for part in s.split(',').map(str::trim).filter(|p| !p.is_empty()) {
73
            if part == "all" {
74
                return Ok(Scope::ALL);
75
            }
76
            match Self::named(part) {
77
                Some(sc) => out = out | sc,
78
                None => return Err(format!("unknown scope {part:?}: use changes, refs or seal")),
79
            }
80
        }
81
        if out.is_empty() {
82
            return Err("a delegate needs at least one scope: changes, refs or seal".into());
83
        }
84
        Ok(out)
85
    }
86
}
87
88
impl std::ops::BitOr for Scope {
89
    type Output = Scope;
90
    fn bitor(self, rhs: Scope) -> Scope {
91
        Scope(self.0 | rhs.0)
92
    }
93
}
94
95
impl std::fmt::Display for Scope {
96
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
97
        f.write_str(&self.names().join(","))
98
    }
99
}
100
101
impl std::fmt::Debug for Scope {
102
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
103
        write!(f, "Scope({self})")
104
    }
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.
118
    pub fn full(key: KeyId) -> Delegate {
119
        Delegate {
120
            key,
121
            scope: Scope::ALL,
122
            expires: None,
123
        }
124
    }
125
    /// Whether the delegation covers `scope` at `at_ms`.
126
    pub fn allows(&self, scope: Scope, at_ms: u64) -> bool {
127
        self.scope.has(scope) && !self.expires.is_some_and(|e| at_ms > e)
128
    }
129
    fn to_value(self) -> Value {
130
        Value::map([
131
            (0, Value::Bytes(self.key.0.to_vec())),
132
            (
133
                1,
134
                Value::Array(
135
                    self.scope
136
                        .names()
137
                        .into_iter()
138
                        .map(|n| Value::Text(n.to_string()))
139
                        .collect(),
140
                ),
141
            ),
142
            (2, self.expires.map(Value::Uint).unwrap_or(Value::Null)),
143
        ])
144
    }
145
    /// An entry, or a bare KeyId as identities carried before scopes
146
    /// existed, which meant every scope.
147
    fn from_value(v: &Value) -> Result<Delegate, ObjectError> {
148
        if let Value::Bytes(_) = v {
149
            return Ok(Delegate::full(oref(v, "delegate")?));
150
        }
151
        let m = v
152
            .as_map()
153
            .ok_or_else(|| ObjectError::Schema("delegate: expected map".into()))?;
154
        let key = oref(field(m, 0, "delegate key")?, "delegate key")?;
155
        let mut scope = Scope::NONE;
156
        for n in array(field(m, 1, "delegate scope")?, "delegate scope")? {
157
            let n = text(n, "delegate scope")?;
158
            scope = scope
159
                | Scope::named(n)
160
                    .ok_or_else(|| ObjectError::Schema(format!("delegate: unknown scope {n:?}")))?;
161
        }
162
        let expires = match field(m, 2, "delegate expires")? {
163
            v if v.is_null() => None,
164
            v => Some(uint(v, "delegate expires")?),
165
        };
166
        Ok(Delegate {
167
            key,
168
            scope,
169
            expires,
170
        })
171
    }
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.
187
fn tidy(mut delegates: Vec<Delegate>) -> Vec<Delegate> {
188
    delegates.sort_by_key(|d| d.key);
189
    delegates.dedup_by(|a, b| a.key == b.key);
190
    delegates
191
}
192
193
impl Identity {
194
    /// The delegation to `key`, if any.
195
    pub fn delegate(&self, key: &KeyId) -> Option<&Delegate> {
196
        self.delegates.iter().find(|d| d.key == *key)
197
    }
198
    /// Whether `key` may act for this identity within `scope` at `at_ms`.
199
    pub fn delegates_to(&self, key: &KeyId, scope: Scope, at_ms: u64) -> bool {
200
        self.delegate(key).is_some_and(|d| d.allows(scope, at_ms))
201
    }
202
    pub fn to_value(&self) -> Value {
203
        Value::map([
204
            (0, Value::Uint(FORMAT_VERSION)),
205
            (1, Value::Bytes(self.ed25519_pk.to_vec())),
206
            (2, Value::Bytes(self.mldsa65_pk.clone())),
207
            (3, Value::Text(self.name.clone())),
208
            (4, Value::Text(self.email.clone())),
209
            (5, Value::Uint(self.created)),
210
            (6, self.expires.map(Value::Uint).unwrap_or(Value::Null)),
211
            (
212
                7,
213
                self.previous
214
                    .map(|p| Value::Bytes(p.0.to_vec()))
215
                    .unwrap_or(Value::Null),
216
            ),
217
            (
218
                8,
219
                Value::Array(self.delegates.iter().map(|d| d.to_value()).collect()),
220
            ),
221
        ])
222
    }
223
    pub fn encode(&self) -> Vec<u8> {
224
        cbor::encode(&self.to_value())
225
    }
226
    pub fn hash(&self) -> KeyId {
227
        hash_object(ObjectType::Identity, &self.encode())
228
    }
229
    pub fn decode(b: &[u8]) -> Result<Identity, ObjectError> {
230
        let v = cbor::decode(b)?;
231
        let m = v
232
            .as_map()
233
            .ok_or_else(|| ObjectError::Schema("identity: expected map".into()))?;
234
        check_version(m)?;
235
        let ed = bytes(field(m, 1, "ed25519_pk")?, "ed25519_pk")?;
236
        let ml = bytes(field(m, 2, "mldsa65_pk")?, "mldsa65_pk")?;
237
        if ed.len() != ED25519_PK_LEN || ml.len() != MLDSA65_PK_LEN {
238
            return Err(ObjectError::Schema(
239
                "identity: wrong public key length".into(),
240
            ));
241
        }
242
        let opt_u = |v: &Value| -> Result<Option<u64>, ObjectError> {
243
            if v.is_null() {
244
                Ok(None)
245
            } else {
246
                uint(v, "expires").map(Some)
247
            }
248
        };
249
        let opt_r = |v: &Value| -> Result<Option<KeyId>, ObjectError> {
250
            if v.is_null() {
251
                Ok(None)
252
            } else {
253
                oref(v, "previous").map(Some)
254
            }
255
        };
256
        let delegates = tidy(
257
            array(field(m, 8, "delegates")?, "delegates")?
258
                .iter()
259
                .map(Delegate::from_value)
260
                .collect::<Result<Vec<_>, _>>()?,
261
        );
262
        Ok(Identity {
263
            ed25519_pk: ed.try_into().unwrap(),
264
            mldsa65_pk: ml.to_vec(),
265
            name: text(field(m, 3, "name")?, "name")?.to_owned(),
266
            email: text(field(m, 4, "email")?, "email")?.to_owned(),
267
            created: uint(field(m, 5, "created")?, "created")?,
268
            expires: opt_u(field(m, 6, "expires")?)?,
269
            previous: opt_r(field(m, 7, "previous")?)?,
270
            delegates,
271
        })
272
    }
273
274
    /// Whether the identity is past its expiry at `now_ms`.
275
    pub fn is_expired_at(&self, now_ms: u64) -> bool {
276
        self.expires.is_some_and(|e| now_ms > e)
277
    }
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).
281
    pub fn successor(
282
        &self,
283
        delegates: Vec<Delegate>,
284
        expires: Option<u64>,
285
        created: u64,
286
    ) -> Identity {
287
        Identity {
288
            previous: Some(self.hash()),
289
            delegates: tidy(delegates),
290
            expires,
291
            created,
292
            ..self.clone()
293
        }
294
    }
295
296
    /// Check a [`SecretKey::sign_ed25519`] signature by this identity.
297
    pub fn verify_ed25519(&self, msg: &[u8], sig: &[u8]) -> Result<(), VerifyError> {
298
        let sig = EdSignature::from_slice(sig).map_err(|_| VerifyError::Ed25519)?;
299
        self.ed_key()?
300
            .verify_strict(msg, &sig)
301
            .map_err(|_| VerifyError::Ed25519)
302
    }
303
304
    fn ed_key(&self) -> Result<EdVerifyingKey, VerifyError> {
305
        EdVerifyingKey::from_bytes(&self.ed25519_pk).map_err(|_| VerifyError::BadKey)
306
    }
307
    fn ml_key(&self) -> Result<MlVerifyingKey<MlDsa65>, VerifyError> {
308
        let enc = EncodedVerifyingKey::<MlDsa65>::try_from(self.mldsa65_pk.as_slice())
309
            .map_err(|_| VerifyError::BadKey)?;
310
        Ok(MlVerifyingKey::decode(&enc))
311
    }
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 {
327
    pub fn name(self) -> &'static str {
328
        match self {
329
            Domain::Change => "change",
330
            Domain::Attest => "attest",
331
            Domain::Policy => "policy",
332
            Domain::Challenge => "challenge",
333
            Domain::Certificate => "certificate",
334
        }
335
    }
336
}
337
338
/// `"oxy1 sig " || domain || 0x00 || KeyId || target` (spec §14.3).
339
pub fn signing_message(domain: Domain, key: &KeyId, target: &ObjectRef) -> Vec<u8> {
340
    let mut m = Vec::with_capacity(80);
341
    m.extend_from_slice(b"oxy1 sig ");
342
    m.extend_from_slice(domain.name().as_bytes());
343
    m.push(0);
344
    m.extend_from_slice(&key.0);
345
    m.extend_from_slice(&target.0);
346
    m
347
}
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 {
357
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
358
        write!(f, "Signature(key {:?})", self.key)
359
    }
360
}
361
362
impl Signature {
363
    pub fn to_value(&self) -> Value {
364
        Value::map([
365
            (0, Value::Bytes(self.key.0.to_vec())),
366
            (1, Value::Uint(ALG_COMPOSITE)),
367
            (2, Value::Bytes(self.ed.to_vec())),
368
            (3, Value::Bytes(self.ml.clone())),
369
        ])
370
    }
371
    pub fn from_value(v: &Value) -> Result<Signature, ObjectError> {
372
        let m = v
373
            .as_map()
374
            .ok_or_else(|| ObjectError::Schema("signature: expected map".into()))?;
375
        let alg = uint(field(m, 1, "alg")?, "alg")?;
376
        if alg != ALG_COMPOSITE {
377
            return Err(ObjectError::Schema(format!(
378
                "unknown signature algorithm {alg}"
379
            )));
380
        }
381
        let ed = bytes(field(m, 2, "ed")?, "ed")?;
382
        let ml = bytes(field(m, 3, "ml")?, "ml")?;
383
        if ed.len() != ED25519_SIG_LEN || ml.len() != MLDSA65_SIG_LEN {
384
            return Err(ObjectError::Schema("signature: wrong length".into()));
385
        }
386
        Ok(Signature {
387
            key: oref(field(m, 0, "key")?, "key")?,
388
            ed: ed.try_into().unwrap(),
389
            ml: ml.to_vec(),
390
        })
391
    }
392
    pub fn encode_list(sigs: &[Signature]) -> Vec<u8> {
393
        cbor::encode(&Value::Array(sigs.iter().map(|s| s.to_value()).collect()))
394
    }
395
    pub fn decode_list(b: &[u8]) -> Result<Vec<Signature>, ObjectError> {
396
        let v = cbor::decode(b)?;
397
        array(&v, "signatures")?
398
            .iter()
399
            .map(Signature::from_value)
400
            .collect()
401
    }
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).
419
pub fn verify(
420
    identity: &Identity,
421
    sig: &Signature,
422
    domain: Domain,
423
    target: &ObjectRef,
424
) -> Result<(), VerifyError> {
425
    let key = identity.hash();
426
    if sig.key != key {
427
        return Err(VerifyError::KeyMismatch);
428
    }
429
    let msg = signing_message(domain, &key, target);
430
    let ed_sig = EdSignature::from_bytes(&sig.ed);
431
    identity
432
        .ed_key()?
433
        .verify_strict(&msg, &ed_sig)
434
        .map_err(|_| VerifyError::Ed25519)?;
435
    let enc =
436
        EncodedSignature::<MlDsa65>::try_from(sig.ml.as_slice()).map_err(|_| VerifyError::MlDsa)?;
437
    let ml_sig = MlSignature::<MlDsa65>::decode(&enc).ok_or(VerifyError::MlDsa)?;
438
    if !identity.ml_key()?.verify_with_context(&msg, b"", &ml_sig) {
439
        return Err(VerifyError::MlDsa);
440
    }
441
    Ok(())
442
}
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 {
452
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
453
        f.write_str("SecretKey(..)")
454
    }
455
}
456
457
impl SecretKey {
458
    pub fn generate() -> SecretKey {
459
        let mut ed_seed = [0u8; 32];
460
        let mut ml_seed = [0u8; 32];
461
        rand::rngs::OsRng.fill_bytes(&mut ed_seed);
462
        rand::rngs::OsRng.fill_bytes(&mut ml_seed);
463
        SecretKey { ed_seed, ml_seed }
464
    }
465
466
    fn ed(&self) -> EdSigningKey {
467
        EdSigningKey::from_bytes(&self.ed_seed)
468
    }
469
    fn ml(&self) -> MlSigningKey<MlDsa65> {
470
        MlSigningKey::from_seed(&Seed::from(self.ml_seed))
471
    }
472
473
    /// The identity object for these keys.
474
    pub fn identity(&self, name: &str, email: &str, created: u64) -> Identity {
475
        Identity {
476
            ed25519_pk: self.ed().verifying_key().to_bytes(),
477
            mldsa65_pk: self
478
                .ml()
479
                .expanded_key()
480
                .verifying_key()
481
                .encode()
482
                .as_slice()
483
                .to_vec(),
484
            name: name.into(),
485
            email: email.into(),
486
            created,
487
            expires: None,
488
            previous: None,
489
            delegates: vec![],
490
        }
491
    }
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`].
496
    pub fn sign_ed25519(&self, msg: &[u8]) -> [u8; 64] {
497
        self.ed().sign(msg).to_bytes()
498
    }
499
500
    pub fn sign(&self, domain: Domain, key: &KeyId, target: &ObjectRef) -> Signature {
501
        let msg = signing_message(domain, key, target);
502
        let ed = self.ed().sign(&msg).to_bytes();
503
        let ml = self
504
            .ml()
505
            .expanded_key()
506
            .sign_deterministic(&msg, b"")
507
            .expect("empty context is valid")
508
            .encode()
509
            .as_slice()
510
            .to_vec();
511
        Signature { key: *key, ed, ml }
512
    }
513
514
    pub fn encode(&self, key: &KeyId) -> Vec<u8> {
515
        cbor::encode(&Value::map([
516
            (0, Value::Uint(FORMAT_VERSION)),
517
            (1, Value::Bytes(key.0.to_vec())),
518
            (2, Value::Bytes(self.ed_seed.to_vec())),
519
            (3, Value::Bytes(self.ml_seed.to_vec())),
520
        ]))
521
    }
522
523
    pub fn decode(b: &[u8]) -> Result<(KeyId, SecretKey), ObjectError> {
524
        let v = cbor::decode(b)?;
525
        let m = v
526
            .as_map()
527
            .ok_or_else(|| ObjectError::Schema("secret key: expected map".into()))?;
528
        check_version(m)?;
529
        let seed = |k: u64| -> Result<[u8; 32], ObjectError> {
530
            bytes(field(m, k, "seed")?, "seed")?
531
                .try_into()
532
                .map_err(|_| ObjectError::Schema("seed: expected 32 bytes".into()))
533
        };
534
        Ok((
535
            oref(field(m, 1, "key")?, "key")?,
536
            SecretKey {
537
                ed_seed: seed(2)?,
538
                ml_seed: seed(3)?,
539
            },
540
        ))
541
    }
542
}
543
544
#[cfg(test)]
545
mod tests {
546
    use super::*;
547
548
    fn fixed_key() -> SecretKey {
549
        SecretKey {
550
            ed_seed: [1; 32],
551
            ml_seed: [2; 32],
552
        }
553
    }
554
555
    #[test]
556
    fn identity_round_trip_and_sizes() {
557
        let sk = fixed_key();
558
        let id = sk.identity("Ada", "[email protected]", 1_700_000_000_000);
559
        assert_eq!(id.mldsa65_pk.len(), MLDSA65_PK_LEN);
560
        let d = Identity::decode(&id.encode()).unwrap();
561
        assert_eq!(d, id);
562
        assert_eq!(d.hash(), id.hash());
563
        // Deterministic from seeds.
564
        assert_eq!(
565
            fixed_key()
566
                .identity("Ada", "[email protected]", 1_700_000_000_000)
567
                .hash(),
568
            id.hash()
569
        );
570
        let mut other = id.clone();
571
        other.delegates.push(Delegate::full(ObjectRef([9; 32])));
572
        assert_ne!(other.hash(), id.hash());
573
    }
574
575
    #[test]
576
    fn delegates_carry_scope_and_expiry_and_bare_keys_mean_every_scope() {
577
        let sk = fixed_key();
578
        let mut id = sk.identity("Ada", "[email protected]", 1_700_000_000_000);
579
        let agent = ObjectRef([7; 32]);
580
        let host = ObjectRef([3; 32]);
581
        id.delegates = vec![
582
            Delegate {
583
                key: agent,
584
                scope: Scope::CHANGES,
585
                expires: Some(2_000),
586
            },
587
            Delegate {
588
                key: host,
589
                scope: Scope::CHANGES | Scope::REFS,
590
                expires: None,
591
            },
592
        ];
593
        let d = Identity::decode(&id.encode()).unwrap();
594
        assert_eq!(d.delegates.len(), 2);
595
        assert!(d.delegates_to(&agent, Scope::CHANGES, 1_000));
596
        assert!(!d.delegates_to(&agent, Scope::CHANGES, 2_001), "expired");
597
        assert!(!d.delegates_to(&agent, Scope::REFS, 1_000));
598
        assert!(!d.delegates_to(&agent, Scope::SEAL, 1_000));
599
        assert!(d.delegates_to(&host, Scope::REFS, u64::MAX));
600
        assert!(!d.delegates_to(&host, Scope::SEAL, 0));
601
        assert!(!d.delegates_to(&ObjectRef([1; 32]), Scope::CHANGES, 0));
602
        assert_eq!(
603
            Scope::parse("changes, refs").unwrap(),
604
            Scope::CHANGES | Scope::REFS
605
        );
606
        assert_eq!(Scope::parse("all").unwrap(), Scope::ALL);
607
        assert_eq!((Scope::CHANGES | Scope::SEAL).to_string(), "changes,seal");
608
        assert!(Scope::parse("push").is_err() && Scope::parse("").is_err());
609
        // An identity written before scopes existed lists bare KeyIds.
610
        let mut v = id.to_value();
611
        if let Value::Map(m) = &mut v {
612
            m.insert(8, Value::Array(vec![Value::Bytes(host.0.to_vec())]));
613
        }
614
        let old = Identity::decode(&cbor::encode(&v)).unwrap();
615
        assert_eq!(old.delegates, vec![Delegate::full(host)]);
616
        assert!(old.delegates_to(&host, Scope::ALL, u64::MAX));
617
    }
618
619
    #[test]
620
    fn sign_and_verify() {
621
        let sk = fixed_key();
622
        let id = sk.identity("Ada", "[email protected]", 1);
623
        let key = id.hash();
624
        let target = ObjectRef([7; 32]);
625
        let sig = sk.sign(Domain::Change, &key, &target);
626
        assert_eq!(sig.ml.len(), MLDSA65_SIG_LEN);
627
        assert_eq!(verify(&id, &sig, Domain::Change, &target), Ok(()));
628
        // Different target, different domain: invalid.
629
        assert_eq!(
630
            verify(&id, &sig, Domain::Change, &ObjectRef([8; 32])),
631
            Err(VerifyError::Ed25519)
632
        );
633
        assert_eq!(
634
            verify(&id, &sig, Domain::Attest, &target),
635
            Err(VerifyError::Ed25519)
636
        );
637
        // Deterministic signatures.
638
        assert_eq!(sk.sign(Domain::Change, &key, &target), sig);
639
        // Signature list round trip.
640
        let l =
641
            Signature::decode_list(&Signature::encode_list(std::slice::from_ref(&sig))).unwrap();
642
        assert_eq!(l, vec![sig]);
643
    }
644
645
    #[test]
646
    fn stripping_or_forging_either_half_fails() {
647
        let sk = fixed_key();
648
        let id = sk.identity("Ada", "a@b", 1);
649
        let key = id.hash();
650
        let target = ObjectRef([7; 32]);
651
        let good = sk.sign(Domain::Change, &key, &target);
652
653
        let mut no_ml = good.clone();
654
        no_ml.ml = vec![0; MLDSA65_SIG_LEN];
655
        assert_eq!(
656
            verify(&id, &no_ml, Domain::Change, &target),
657
            Err(VerifyError::MlDsa)
658
        );
659
660
        let mut bad_ed = good.clone();
661
        bad_ed.ed[10] ^= 1;
662
        assert_eq!(
663
            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.
668
        let other = SecretKey {
669
            ed_seed: [3; 32],
670
            ml_seed: [4; 32],
671
        };
672
        let other_id = other.identity("Bob", "b@b", 1);
673
        let theirs = other.sign(Domain::Change, &other_id.hash(), &target);
674
        assert_eq!(
675
            verify(&id, &theirs, Domain::Change, &target),
676
            Err(VerifyError::KeyMismatch)
677
        );
678
        let mut relabelled = theirs.clone();
679
        relabelled.key = key;
680
        assert_eq!(
681
            verify(&id, &relabelled, Domain::Change, &target),
682
            Err(VerifyError::Ed25519)
683
        );
684
685
        // Wrong length is rejected at decode time.
686
        let mut short = good.to_value();
687
        if let Value::Map(m) = &mut short {
688
            m.insert(3, Value::Bytes(vec![0; 10]));
689
        }
690
        assert!(Signature::from_value(&short).is_err());
691
    }
692
693
    #[test]
694
    fn secret_key_round_trip() {
695
        let sk = fixed_key();
696
        let key = sk.identity("x", "y", 0).hash();
697
        let (k, d) = SecretKey::decode(&sk.encode(&key)).unwrap();
698
        assert_eq!(k, key);
699
        assert_eq!(d.ed_seed, sk.ed_seed);
700
        assert_eq!(d.ml_seed, sk.ml_seed);
701
        assert_ne!(SecretKey::generate().ed_seed, SecretKey::generate().ed_seed);
702
    }
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.
707
pub fn challenge_target(challenge: &[u8]) -> ObjectRef {
708
    let mut h = blake3::Hasher::new();
709
    h.update(b"oxy1 challenge ");
710
    h.update(challenge);
711
    ObjectRef(*h.finalize().as_bytes())
712
}
713
714
impl SecretKey {
715
    /// Sign a host's challenge (at least 16 bytes) with this key.
716
    pub fn sign_challenge(&self, key: &KeyId, challenge: &[u8]) -> Result<Signature, VerifyError> {
717
        if challenge.len() < 16 {
718
            return Err(VerifyError::ShortChallenge);
719
        }
720
        Ok(self.sign(Domain::Challenge, key, &challenge_target(challenge)))
721
    }
722
}
723
724
/// Check a challenge signature against the identity that claims it.
725
pub fn verify_challenge(
726
    identity: &Identity,
727
    sig: &Signature,
728
    challenge: &[u8],
729
) -> Result<(), VerifyError> {
730
    if challenge.len() < 16 {
731
        return Err(VerifyError::ShortChallenge);
732
    }
733
    if sig.key != identity.hash() {
734
        return Err(VerifyError::KeyMismatch);
735
    }
736
    verify(
737
        identity,
738
        sig,
739
        Domain::Challenge,
740
        &challenge_target(challenge),
741
    )
742
}
743
744
#[cfg(test)]
745
mod challenge_tests {
746
    use super::*;
747
748
    #[test]
749
    fn a_challenge_signature_binds_key_and_bytes() {
750
        let sk = SecretKey::generate();
751
        let id = sk.identity("A", "a@example", 1);
752
        let key = id.hash();
753
        let challenge = [7u8; 32];
754
        let sig = sk.sign_challenge(&key, &challenge).unwrap();
755
        assert!(verify_challenge(&id, &sig, &challenge).is_ok());
756
        assert!(
757
            verify_challenge(&id, &sig, &[8u8; 32]).is_err(),
758
            "other bytes"
759
        );
760
        let other = SecretKey::generate().identity("B", "b@example", 1);
761
        assert!(
762
            verify_challenge(&other, &sig, &challenge).is_err(),
763
            "other identity"
764
        );
765
        assert!(sk.sign_challenge(&key, b"short").is_err());
766
        // A challenge target never equals a change signature's target for the same bytes.
767
        assert_ne!(challenge_target(&challenge), ObjectRef(challenge));
768
    }
769
}