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