OXYGENHUB
◆ carry-identical oxygen / crates / oxy-core / src / identity.rs
24.6 KiB · Rust · last changed Scoped, expiring delegates, and revocation by the delegator 1 month 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
    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
    fn ed_key(&self) -> Result<EdVerifyingKey, VerifyError> {
297
        EdVerifyingKey::from_bytes(&self.ed25519_pk).map_err(|_| VerifyError::BadKey)
298
    }
299
    fn ml_key(&self) -> Result<MlVerifyingKey<MlDsa65>, VerifyError> {
300
        let enc = EncodedVerifyingKey::<MlDsa65>::try_from(self.mldsa65_pk.as_slice())
301
            .map_err(|_| VerifyError::BadKey)?;
302
        Ok(MlVerifyingKey::decode(&enc))
303
    }
304
}
305
306
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
307
pub enum Domain {
308
    Change,
309
    Attest,
310
    Policy,
311
    /// A server-issued challenge, proving possession of a key to a host
312
    /// (hub spec §5.3, §5.4). Never a stored object.
313
    Challenge,
314
}
315
316
impl Domain {
317
    pub fn name(self) -> &'static str {
318
        match self {
319
            Domain::Change => "change",
320
            Domain::Attest => "attest",
321
            Domain::Policy => "policy",
322
            Domain::Challenge => "challenge",
323
        }
324
    }
325
}
326
327
/// `"oxy1 sig " || domain || 0x00 || KeyId || target` (spec §14.3).
328
pub fn signing_message(domain: Domain, key: &KeyId, target: &ObjectRef) -> Vec<u8> {
329
    let mut m = Vec::with_capacity(80);
330
    m.extend_from_slice(b"oxy1 sig ");
331
    m.extend_from_slice(domain.name().as_bytes());
332
    m.push(0);
333
    m.extend_from_slice(&key.0);
334
    m.extend_from_slice(&target.0);
335
    m
336
}
337
338
#[derive(Clone, PartialEq, Eq)]
339
pub struct Signature {
340
    pub key: KeyId,
341
    pub ed: [u8; ED25519_SIG_LEN],
342
    pub ml: Vec<u8>,
343
}
344
345
impl std::fmt::Debug for Signature {
346
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
347
        write!(f, "Signature(key {:?})", self.key)
348
    }
349
}
350
351
impl Signature {
352
    pub fn to_value(&self) -> Value {
353
        Value::map([
354
            (0, Value::Bytes(self.key.0.to_vec())),
355
            (1, Value::Uint(ALG_COMPOSITE)),
356
            (2, Value::Bytes(self.ed.to_vec())),
357
            (3, Value::Bytes(self.ml.clone())),
358
        ])
359
    }
360
    pub fn from_value(v: &Value) -> Result<Signature, ObjectError> {
361
        let m = v
362
            .as_map()
363
            .ok_or_else(|| ObjectError::Schema("signature: expected map".into()))?;
364
        let alg = uint(field(m, 1, "alg")?, "alg")?;
365
        if alg != ALG_COMPOSITE {
366
            return Err(ObjectError::Schema(format!(
367
                "unknown signature algorithm {alg}"
368
            )));
369
        }
370
        let ed = bytes(field(m, 2, "ed")?, "ed")?;
371
        let ml = bytes(field(m, 3, "ml")?, "ml")?;
372
        if ed.len() != ED25519_SIG_LEN || ml.len() != MLDSA65_SIG_LEN {
373
            return Err(ObjectError::Schema("signature: wrong length".into()));
374
        }
375
        Ok(Signature {
376
            key: oref(field(m, 0, "key")?, "key")?,
377
            ed: ed.try_into().unwrap(),
378
            ml: ml.to_vec(),
379
        })
380
    }
381
    pub fn encode_list(sigs: &[Signature]) -> Vec<u8> {
382
        cbor::encode(&Value::Array(sigs.iter().map(|s| s.to_value()).collect()))
383
    }
384
    pub fn decode_list(b: &[u8]) -> Result<Vec<Signature>, ObjectError> {
385
        let v = cbor::decode(b)?;
386
        array(&v, "signatures")?
387
            .iter()
388
            .map(Signature::from_value)
389
            .collect()
390
    }
391
}
392
393
#[derive(Clone, Copy, Debug, PartialEq, Eq, thiserror::Error)]
394
pub enum VerifyError {
395
    #[error("signature names a different key than the identity")]
396
    KeyMismatch,
397
    #[error("identity holds a malformed public key")]
398
    BadKey,
399
    #[error("Ed25519 signature invalid")]
400
    Ed25519,
401
    #[error("ML-DSA-65 signature invalid")]
402
    MlDsa,
403
    #[error("a challenge is at least 16 bytes")]
404
    ShortChallenge,
405
}
406
407
/// Verify a composite signature by `identity` over `target` (spec §14.3).
408
pub fn verify(
409
    identity: &Identity,
410
    sig: &Signature,
411
    domain: Domain,
412
    target: &ObjectRef,
413
) -> Result<(), VerifyError> {
414
    let key = identity.hash();
415
    if sig.key != key {
416
        return Err(VerifyError::KeyMismatch);
417
    }
418
    let msg = signing_message(domain, &key, target);
419
    let ed_sig = EdSignature::from_bytes(&sig.ed);
420
    identity
421
        .ed_key()?
422
        .verify_strict(&msg, &ed_sig)
423
        .map_err(|_| VerifyError::Ed25519)?;
424
    let enc =
425
        EncodedSignature::<MlDsa65>::try_from(sig.ml.as_slice()).map_err(|_| VerifyError::MlDsa)?;
426
    let ml_sig = MlSignature::<MlDsa65>::decode(&enc).ok_or(VerifyError::MlDsa)?;
427
    if !identity.ml_key()?.verify_with_context(&msg, b"", &ml_sig) {
428
        return Err(VerifyError::MlDsa);
429
    }
430
    Ok(())
431
}
432
433
/// The seeds of a composite key pair. Stored only in the user's key directory.
434
#[derive(Clone)]
435
pub struct SecretKey {
436
    pub ed_seed: [u8; 32],
437
    pub ml_seed: [u8; 32],
438
}
439
440
impl std::fmt::Debug for SecretKey {
441
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
442
        f.write_str("SecretKey(..)")
443
    }
444
}
445
446
impl SecretKey {
447
    pub fn generate() -> SecretKey {
448
        let mut ed_seed = [0u8; 32];
449
        let mut ml_seed = [0u8; 32];
450
        rand::rngs::OsRng.fill_bytes(&mut ed_seed);
451
        rand::rngs::OsRng.fill_bytes(&mut ml_seed);
452
        SecretKey { ed_seed, ml_seed }
453
    }
454
455
    fn ed(&self) -> EdSigningKey {
456
        EdSigningKey::from_bytes(&self.ed_seed)
457
    }
458
    fn ml(&self) -> MlSigningKey<MlDsa65> {
459
        MlSigningKey::from_seed(&Seed::from(self.ml_seed))
460
    }
461
462
    /// The identity object for these keys.
463
    pub fn identity(&self, name: &str, email: &str, created: u64) -> Identity {
464
        Identity {
465
            ed25519_pk: self.ed().verifying_key().to_bytes(),
466
            mldsa65_pk: self
467
                .ml()
468
                .expanded_key()
469
                .verifying_key()
470
                .encode()
471
                .as_slice()
472
                .to_vec(),
473
            name: name.into(),
474
            email: email.into(),
475
            created,
476
            expires: None,
477
            previous: None,
478
            delegates: vec![],
479
        }
480
    }
481
482
    pub fn sign(&self, domain: Domain, key: &KeyId, target: &ObjectRef) -> Signature {
483
        let msg = signing_message(domain, key, target);
484
        let ed = self.ed().sign(&msg).to_bytes();
485
        let ml = self
486
            .ml()
487
            .expanded_key()
488
            .sign_deterministic(&msg, b"")
489
            .expect("empty context is valid")
490
            .encode()
491
            .as_slice()
492
            .to_vec();
493
        Signature { key: *key, ed, ml }
494
    }
495
496
    pub fn encode(&self, key: &KeyId) -> Vec<u8> {
497
        cbor::encode(&Value::map([
498
            (0, Value::Uint(FORMAT_VERSION)),
499
            (1, Value::Bytes(key.0.to_vec())),
500
            (2, Value::Bytes(self.ed_seed.to_vec())),
501
            (3, Value::Bytes(self.ml_seed.to_vec())),
502
        ]))
503
    }
504
505
    pub fn decode(b: &[u8]) -> Result<(KeyId, SecretKey), ObjectError> {
506
        let v = cbor::decode(b)?;
507
        let m = v
508
            .as_map()
509
            .ok_or_else(|| ObjectError::Schema("secret key: expected map".into()))?;
510
        check_version(m)?;
511
        let seed = |k: u64| -> Result<[u8; 32], ObjectError> {
512
            bytes(field(m, k, "seed")?, "seed")?
513
                .try_into()
514
                .map_err(|_| ObjectError::Schema("seed: expected 32 bytes".into()))
515
        };
516
        Ok((
517
            oref(field(m, 1, "key")?, "key")?,
518
            SecretKey {
519
                ed_seed: seed(2)?,
520
                ml_seed: seed(3)?,
521
            },
522
        ))
523
    }
524
}
525
526
#[cfg(test)]
527
mod tests {
528
    use super::*;
529
530
    fn fixed_key() -> SecretKey {
531
        SecretKey {
532
            ed_seed: [1; 32],
533
            ml_seed: [2; 32],
534
        }
535
    }
536
537
    #[test]
538
    fn identity_round_trip_and_sizes() {
539
        let sk = fixed_key();
540
        let id = sk.identity("Ada", "[email protected]", 1_700_000_000_000);
541
        assert_eq!(id.mldsa65_pk.len(), MLDSA65_PK_LEN);
542
        let d = Identity::decode(&id.encode()).unwrap();
543
        assert_eq!(d, id);
544
        assert_eq!(d.hash(), id.hash());
545
        // Deterministic from seeds.
546
        assert_eq!(
547
            fixed_key()
548
                .identity("Ada", "[email protected]", 1_700_000_000_000)
549
                .hash(),
550
            id.hash()
551
        );
552
        let mut other = id.clone();
553
        other.delegates.push(Delegate::full(ObjectRef([9; 32])));
554
        assert_ne!(other.hash(), id.hash());
555
    }
556
557
    #[test]
558
    fn delegates_carry_scope_and_expiry_and_bare_keys_mean_every_scope() {
559
        let sk = fixed_key();
560
        let mut id = sk.identity("Ada", "[email protected]", 1_700_000_000_000);
561
        let agent = ObjectRef([7; 32]);
562
        let host = ObjectRef([3; 32]);
563
        id.delegates = vec![
564
            Delegate {
565
                key: agent,
566
                scope: Scope::CHANGES,
567
                expires: Some(2_000),
568
            },
569
            Delegate {
570
                key: host,
571
                scope: Scope::CHANGES | Scope::REFS,
572
                expires: None,
573
            },
574
        ];
575
        let d = Identity::decode(&id.encode()).unwrap();
576
        assert_eq!(d.delegates.len(), 2);
577
        assert!(d.delegates_to(&agent, Scope::CHANGES, 1_000));
578
        assert!(!d.delegates_to(&agent, Scope::CHANGES, 2_001), "expired");
579
        assert!(!d.delegates_to(&agent, Scope::REFS, 1_000));
580
        assert!(!d.delegates_to(&agent, Scope::SEAL, 1_000));
581
        assert!(d.delegates_to(&host, Scope::REFS, u64::MAX));
582
        assert!(!d.delegates_to(&host, Scope::SEAL, 0));
583
        assert!(!d.delegates_to(&ObjectRef([1; 32]), Scope::CHANGES, 0));
584
        assert_eq!(
585
            Scope::parse("changes, refs").unwrap(),
586
            Scope::CHANGES | Scope::REFS
587
        );
588
        assert_eq!(Scope::parse("all").unwrap(), Scope::ALL);
589
        assert_eq!((Scope::CHANGES | Scope::SEAL).to_string(), "changes,seal");
590
        assert!(Scope::parse("push").is_err() && Scope::parse("").is_err());
591
        // An identity written before scopes existed lists bare KeyIds.
592
        let mut v = id.to_value();
593
        if let Value::Map(m) = &mut v {
594
            m.insert(8, Value::Array(vec![Value::Bytes(host.0.to_vec())]));
595
        }
596
        let old = Identity::decode(&cbor::encode(&v)).unwrap();
597
        assert_eq!(old.delegates, vec![Delegate::full(host)]);
598
        assert!(old.delegates_to(&host, Scope::ALL, u64::MAX));
599
    }
600
601
    #[test]
602
    fn sign_and_verify() {
603
        let sk = fixed_key();
604
        let id = sk.identity("Ada", "[email protected]", 1);
605
        let key = id.hash();
606
        let target = ObjectRef([7; 32]);
607
        let sig = sk.sign(Domain::Change, &key, &target);
608
        assert_eq!(sig.ml.len(), MLDSA65_SIG_LEN);
609
        assert_eq!(verify(&id, &sig, Domain::Change, &target), Ok(()));
610
        // Different target, different domain: invalid.
611
        assert_eq!(
612
            verify(&id, &sig, Domain::Change, &ObjectRef([8; 32])),
613
            Err(VerifyError::Ed25519)
614
        );
615
        assert_eq!(
616
            verify(&id, &sig, Domain::Attest, &target),
617
            Err(VerifyError::Ed25519)
618
        );
619
        // Deterministic signatures.
620
        assert_eq!(sk.sign(Domain::Change, &key, &target), sig);
621
        // Signature list round trip.
622
        let l =
623
            Signature::decode_list(&Signature::encode_list(std::slice::from_ref(&sig))).unwrap();
624
        assert_eq!(l, vec![sig]);
625
    }
626
627
    #[test]
628
    fn stripping_or_forging_either_half_fails() {
629
        let sk = fixed_key();
630
        let id = sk.identity("Ada", "a@b", 1);
631
        let key = id.hash();
632
        let target = ObjectRef([7; 32]);
633
        let good = sk.sign(Domain::Change, &key, &target);
634
635
        let mut no_ml = good.clone();
636
        no_ml.ml = vec![0; MLDSA65_SIG_LEN];
637
        assert_eq!(
638
            verify(&id, &no_ml, Domain::Change, &target),
639
            Err(VerifyError::MlDsa)
640
        );
641
642
        let mut bad_ed = good.clone();
643
        bad_ed.ed[10] ^= 1;
644
        assert_eq!(
645
            verify(&id, &bad_ed, Domain::Change, &target),
646
            Err(VerifyError::Ed25519)
647
        );
648
649
        // A signature made for another KeyId over the same target does not transfer.
650
        let other = SecretKey {
651
            ed_seed: [3; 32],
652
            ml_seed: [4; 32],
653
        };
654
        let other_id = other.identity("Bob", "b@b", 1);
655
        let theirs = other.sign(Domain::Change, &other_id.hash(), &target);
656
        assert_eq!(
657
            verify(&id, &theirs, Domain::Change, &target),
658
            Err(VerifyError::KeyMismatch)
659
        );
660
        let mut relabelled = theirs.clone();
661
        relabelled.key = key;
662
        assert_eq!(
663
            verify(&id, &relabelled, Domain::Change, &target),
664
            Err(VerifyError::Ed25519)
665
        );
666
667
        // Wrong length is rejected at decode time.
668
        let mut short = good.to_value();
669
        if let Value::Map(m) = &mut short {
670
            m.insert(3, Value::Bytes(vec![0; 10]));
671
        }
672
        assert!(Signature::from_value(&short).is_err());
673
    }
674
675
    #[test]
676
    fn secret_key_round_trip() {
677
        let sk = fixed_key();
678
        let key = sk.identity("x", "y", 0).hash();
679
        let (k, d) = SecretKey::decode(&sk.encode(&key)).unwrap();
680
        assert_eq!(k, key);
681
        assert_eq!(d.ed_seed, sk.ed_seed);
682
        assert_eq!(d.ml_seed, sk.ml_seed);
683
        assert_ne!(SecretKey::generate().ed_seed, SecretKey::generate().ed_seed);
684
    }
685
}
686
687
/// The signing target of a challenge: `BLAKE3-256("oxy1 challenge " || bytes)`,
688
/// so a challenge can never collide with a stored object's reference.
689
pub fn challenge_target(challenge: &[u8]) -> ObjectRef {
690
    let mut h = blake3::Hasher::new();
691
    h.update(b"oxy1 challenge ");
692
    h.update(challenge);
693
    ObjectRef(*h.finalize().as_bytes())
694
}
695
696
impl SecretKey {
697
    /// Sign a host's challenge (at least 16 bytes) with this key.
698
    pub fn sign_challenge(&self, key: &KeyId, challenge: &[u8]) -> Result<Signature, VerifyError> {
699
        if challenge.len() < 16 {
700
            return Err(VerifyError::ShortChallenge);
701
        }
702
        Ok(self.sign(Domain::Challenge, key, &challenge_target(challenge)))
703
    }
704
}
705
706
/// Check a challenge signature against the identity that claims it.
707
pub fn verify_challenge(
708
    identity: &Identity,
709
    sig: &Signature,
710
    challenge: &[u8],
711
) -> Result<(), VerifyError> {
712
    if challenge.len() < 16 {
713
        return Err(VerifyError::ShortChallenge);
714
    }
715
    if sig.key != identity.hash() {
716
        return Err(VerifyError::KeyMismatch);
717
    }
718
    verify(
719
        identity,
720
        sig,
721
        Domain::Challenge,
722
        &challenge_target(challenge),
723
    )
724
}
725
726
#[cfg(test)]
727
mod challenge_tests {
728
    use super::*;
729
730
    #[test]
731
    fn a_challenge_signature_binds_key_and_bytes() {
732
        let sk = SecretKey::generate();
733
        let id = sk.identity("A", "a@example", 1);
734
        let key = id.hash();
735
        let challenge = [7u8; 32];
736
        let sig = sk.sign_challenge(&key, &challenge).unwrap();
737
        assert!(verify_challenge(&id, &sig, &challenge).is_ok());
738
        assert!(
739
            verify_challenge(&id, &sig, &[8u8; 32]).is_err(),
740
            "other bytes"
741
        );
742
        let other = SecretKey::generate().identity("B", "b@example", 1);
743
        assert!(
744
            verify_challenge(&other, &sig, &challenge).is_err(),
745
            "other identity"
746
        );
747
        assert!(sk.sign_challenge(&key, b"short").is_err());
748
        // A challenge target never equals a change signature's target for the same bytes.
749
        assert_ne!(challenge_target(&challenge), ObjectRef(challenge));
750
    }
751
}