OXYGENHUB
# 2aa1854b0d13 oxygen / crates / oxy-core / src / cert.rs
18.5 KiB · Rust · last changed Trusted time: judge a fetched attestation at its integrated time 18 days ago source blame history raw
02e69188 Andy McCall ↶ 1
//! Certificates for short-lived keys (spec §14.7, oxygenhub#241,
2
//! oxygenhub docs/keyless.md). An issuer, a hub's key, binds a fresh key
3
//! to the identity that proved itself (an OIDC subject) for minutes: a Flow
4
//! job or an agent signs with that key and throws it away. The certificate
5
//! is signed with the issuer's composite key, so it is post-quantum like
6
//! every other signature in Oxygen.
7
//!
8
//! Whether to trust an issuer, and for which subjects, is the trust
9
//! policy's (§14.5); whether a signature was made inside the certificate's
10
//! window needs time the signer does not choose, which the caller passes
028545df Andy McCall ↶ 11
//! in (the transparency log's integrated time, §14.8, else a host's
12
//! acceptance).
02e69188 Andy McCall ↶ 13
14
use crate::cbor::{self, Value};
15
use crate::hash::{hash_object, KeyId, ObjectRef, ObjectType};
16
use crate::identity::{verify, Domain, Identity, Scope, SecretKey, Signature};
17
use crate::objects::{array, bytes, check_version, field, map, oref, text, uint, ObjectError};
18
19
/// The longest a certificate may be valid. Jobs get ten minutes; an hour
20
/// leaves room for an issuer that rounds up, and no more.
21
pub const MAX_LIFETIME_MS: u64 = 60 * 60 * 1000;
22
23
#[derive(Clone, Debug, PartialEq, Eq)]
24
pub struct Certificate {
25
    /// The short-lived key's public identity.
26
    pub key: Identity,
27
    /// The issuer's KeyId (a hub's key).
28
    pub issuer: KeyId,
29
    /// Who proved it: `repo:OWNER/NAME:bookmark:B`, `agent:NAME@ACCOUNT`.
30
    pub subject: String,
31
    /// What else the proof said (environment, run, job), sorted by name.
32
    pub claims: Vec<(String, String)>,
33
    /// What the key may sign: changes, refs, seals.
34
    pub scope: Scope,
35
    /// Valid from and until, in wall milliseconds.
36
    pub not_before: u64,
37
    pub expires: u64,
a2387d54 Andy McCall ↶ 38
    /// The grant that lets the subject act for an author, when an agent
39
    /// asked with one (field 8, only when present).
40
    pub grant: Option<SignedGrant>,
02e69188 Andy McCall ↶ 41
}
42
43
impl Certificate {
44
    pub fn to_value(&self) -> Value {
45
        let mut claims = self.claims.clone();
46
        claims.sort();
a2387d54 Andy McCall ↶ 47
        let mut v = Value::map([
02e69188 Andy McCall ↶ 48
            (0, Value::Uint(1)),
49
            (1, Value::Bytes(self.key.encode())),
50
            (2, Value::Bytes(self.issuer.0.to_vec())),
51
            (3, Value::Text(self.subject.clone())),
52
            (
53
                4,
54
                Value::Array(
55
                    claims
56
                        .into_iter()
57
                        .map(|(k, v)| Value::Array(vec![Value::Text(k), Value::Text(v)]))
58
                        .collect(),
59
                ),
60
            ),
61
            (
62
                5,
63
                Value::Array(
64
                    self.scope
65
                        .names()
66
                        .into_iter()
67
                        .map(|n| Value::Text(n.to_string()))
68
                        .collect(),
69
                ),
70
            ),
71
            (6, Value::Uint(self.not_before)),
72
            (7, Value::Uint(self.expires)),
a2387d54 Andy McCall ↶ 73
        ]);
74
        if let (Some(g), Value::Map(m)) = (&self.grant, &mut v) {
75
            m.insert(8, Value::Bytes(g.encode()));
76
        }
77
        v
02e69188 Andy McCall ↶ 78
    }
79
80
    pub fn encode(&self) -> Vec<u8> {
81
        cbor::encode(&self.to_value())
82
    }
83
84
    pub fn hash(&self) -> ObjectRef {
85
        hash_object(ObjectType::Certificate, &self.encode())
86
    }
87
88
    /// The short-lived key's KeyId: what its signatures name.
89
    pub fn key_id(&self) -> KeyId {
90
        self.key.hash()
91
    }
92
93
    pub fn decode(b: &[u8]) -> Result<Certificate, ObjectError> {
94
        let v = cbor::decode(b)?;
95
        let m = map(&v, "certificate")?;
96
        check_version(m)?;
97
        let key = Identity::decode(bytes(field(m, 1, "key")?, "key")?)?;
98
        let mut claims = Vec::new();
99
        for c in array(field(m, 4, "claims")?, "claims")? {
100
            let pair = array(c, "claim")?;
101
            if pair.len() != 2 {
102
                return Err(ObjectError::Schema("claim: expected [name, value]".into()));
103
            }
104
            claims.push((
105
                text(&pair[0], "claim name")?.to_owned(),
106
                text(&pair[1], "claim value")?.to_owned(),
107
            ));
108
        }
109
        let mut scope = Scope::NONE;
110
        for n in array(field(m, 5, "scope")?, "scope")? {
111
            let n = text(n, "scope")?;
112
            scope = scope
113
                | Scope::named(n).ok_or_else(|| {
114
                    ObjectError::Schema(format!("certificate: unknown scope {n:?}"))
115
                })?;
116
        }
117
        Ok(Certificate {
118
            key,
119
            issuer: oref(field(m, 2, "issuer")?, "issuer")?,
120
            subject: text(field(m, 3, "subject")?, "subject")?.to_owned(),
121
            claims,
122
            scope,
123
            not_before: uint(field(m, 6, "not_before")?, "not_before")?,
124
            expires: uint(field(m, 7, "expires")?, "expires")?,
a2387d54 Andy McCall ↶ 125
            grant: match m.get(&8) {
126
                Some(g) => Some(
127
                    SignedGrant::decode(bytes(g, "grant")?)
128
                        .map_err(|e| ObjectError::Schema(format!("grant: {e}")))?,
129
                ),
130
                None => None,
131
            },
02e69188 Andy McCall ↶ 132
        })
133
    }
134
135
    /// Whether the key may sign within `scope` at `at_ms`, a time the
136
    /// signer did not choose.
137
    pub fn covers(&self, scope: Scope, at_ms: u64) -> bool {
138
        !scope.is_empty()
139
            && self.scope.has(scope)
140
            && self.not_before <= at_ms
141
            && at_ms <= self.expires
142
    }
143
144
    /// The claim called `name`, if the certificate has one.
145
    pub fn claim(&self, name: &str) -> Option<&str> {
146
        self.claims
147
            .iter()
148
            .find(|(k, _)| k == name)
149
            .map(|(_, v)| v.as_str())
150
    }
a2387d54 Andy McCall ↶ 151
}
152
153
/// An author's grant (spec §14.7): it lets the keys an issuer certifies
154
/// for `subject` act for the author, as a delegate does, without a key of
155
/// their own. An agent's fresh keys then sign and seal changes in the
156
/// author's name while the grant lasts; the grant travels inside their
157
/// certificates, so a verifier needs nothing else. Signed by the author.
158
#[derive(Clone, Debug, PartialEq, Eq)]
159
pub struct Grant {
160
    /// The author's KeyId, which signs the grant.
161
    pub grantor: KeyId,
162
    /// The subject whose certified keys act for it: `agent:NAME@ACCOUNT`.
163
    pub subject: String,
164
    /// The issuer whose certificates count.
165
    pub issuer: KeyId,
166
    /// What they may do for the author: changes, seal.
167
    pub scope: Scope,
168
    /// Valid from and until, in wall milliseconds.
169
    pub not_before: u64,
170
    pub expires: u64,
02e69188 Andy McCall ↶ 171
}
a2387d54 Andy McCall ↶ 172
173
impl Grant {
174
    pub fn to_value(&self) -> Value {
175
        Value::map([
176
            (0, Value::Uint(1)),
177
            (1, Value::Bytes(self.grantor.0.to_vec())),
178
            (2, Value::Text(self.subject.clone())),
179
            (3, Value::Bytes(self.issuer.0.to_vec())),
180
            (
181
                4,
182
                Value::Array(
183
                    self.scope
184
                        .names()
185
                        .into_iter()
186
                        .map(|n| Value::Text(n.to_string()))
187
                        .collect(),
188
                ),
189
            ),
190
            (5, Value::Uint(self.not_before)),
191
            (6, Value::Uint(self.expires)),
192
        ])
193
    }
194
195
    pub fn encode(&self) -> Vec<u8> {
196
        cbor::encode(&self.to_value())
197
    }
198
199
    pub fn hash(&self) -> ObjectRef {
200
        hash_object(ObjectType::Grant, &self.encode())
201
    }
02e69188 Andy McCall ↶ 202
a2387d54 Andy McCall ↶ 203
    pub fn decode(b: &[u8]) -> Result<Grant, ObjectError> {
204
        let v = cbor::decode(b)?;
205
        let m = map(&v, "grant")?;
206
        check_version(m)?;
207
        let mut scope = Scope::NONE;
208
        for n in array(field(m, 4, "scope")?, "scope")? {
209
            let n = text(n, "scope")?;
210
            scope = scope
211
                | Scope::named(n)
212
                    .ok_or_else(|| ObjectError::Schema(format!("grant: unknown scope {n:?}")))?;
213
        }
214
        Ok(Grant {
215
            grantor: oref(field(m, 1, "grantor")?, "grantor")?,
216
            subject: text(field(m, 2, "subject")?, "subject")?.to_owned(),
217
            issuer: oref(field(m, 3, "issuer")?, "issuer")?,
218
            scope,
219
            not_before: uint(field(m, 5, "not_before")?, "not_before")?,
220
            expires: uint(field(m, 6, "expires")?, "expires")?,
221
        })
222
    }
223
224
    /// Whether it lets its subject do `scope` for the author at `at_ms`
225
    /// (the change's own time, as for a delegation).
226
    pub fn covers(&self, scope: Scope, at_ms: u64) -> bool {
227
        !scope.is_empty()
228
            && self.scope.has(scope)
229
            && self.not_before <= at_ms
230
            && at_ms <= self.expires
231
    }
232
}
233
234
/// A grant with its author's signature over its ObjectRef.
235
#[derive(Clone, Debug, PartialEq, Eq)]
236
pub struct SignedGrant {
237
    pub grant: Grant,
238
    pub sig: Signature,
239
}
240
241
impl SignedGrant {
242
    /// Grant `grant`, signed by the author `grantor` holds the secret of.
243
    pub fn sign(grant: Grant, grantor: &Identity, sk: &SecretKey) -> SignedGrant {
244
        let sig = sk.sign(Domain::Grant, &grantor.hash(), &grant.hash());
245
        SignedGrant { grant, sig }
246
    }
247
248
    /// Signed by `grantor`, which it names, and well formed.
249
    pub fn verify(&self, grantor: &Identity) -> Result<(), CertError> {
250
        let g = &self.grant;
251
        if grantor.hash() != g.grantor || self.sig.key != g.grantor {
252
            return Err(CertError::WrongIssuer(g.grantor.short(12)));
253
        }
254
        verify(grantor, &self.sig, Domain::Grant, &g.hash())
255
            .map_err(|e| CertError::BadSignature(e.to_string()))?;
256
        if g.expires <= g.not_before {
257
            return Err(CertError::BadLifetime);
258
        }
259
        if g.scope.is_empty() {
260
            return Err(CertError::NoScope);
261
        }
262
        Ok(())
263
    }
264
265
    /// `[grant bytes, signature]`.
266
    pub fn encode(&self) -> Vec<u8> {
267
        cbor::encode(&Value::Array(vec![
268
            Value::Bytes(self.grant.encode()),
269
            self.sig.to_value(),
270
        ]))
271
    }
272
273
    pub fn decode(b: &[u8]) -> Result<SignedGrant, CertError> {
274
        let v = cbor::decode(b).map_err(ObjectError::from)?;
275
        let a = array(&v, "signed grant")?;
276
        if a.len() != 2 {
277
            return Err(CertError::Schema(
278
                "signed grant: expected [grant, signature]".into(),
279
            ));
280
        }
281
        Ok(SignedGrant {
282
            grant: Grant::decode(bytes(&a[0], "grant")?)?,
283
            sig: Signature::from_value(&a[1])?,
284
        })
285
    }
286
}
287
098227d4 Andy McCall ↶ 288
/// What a fresh key signs (a challenge, §14.3) to show its holder asks for
289
/// the certificate: bound to the credential it is asked with, so the
290
/// proof cannot be replayed with another.
291
pub fn certify_challenge(credential: &str) -> Vec<u8> {
292
    let mut c = b"oxy1 certify ".to_vec();
293
    c.extend_from_slice(blake3::hash(credential.as_bytes()).as_bytes());
294
    c
295
}
296
02e69188 Andy McCall ↶ 297
#[derive(Clone, Debug, PartialEq, Eq, thiserror::Error)]
298
pub enum CertError {
299
    #[error("the certificate names issuer {0}, not this one")]
300
    WrongIssuer(String),
301
    #[error("the issuer's signature does not verify: {0}")]
302
    BadSignature(String),
303
    #[error("the certificate is valid for no time, or for longer than an hour")]
304
    BadLifetime,
305
    #[error("the certificate gives no scope")]
306
    NoScope,
307
    #[error("{0}")]
308
    Schema(String),
309
}
310
311
impl From<ObjectError> for CertError {
312
    fn from(e: ObjectError) -> Self {
313
        CertError::Schema(e.to_string())
314
    }
315
}
316
317
/// A certificate with its issuer's signature over its ObjectRef.
318
#[derive(Clone, Debug, PartialEq, Eq)]
319
pub struct SignedCertificate {
320
    pub cert: Certificate,
321
    pub sig: Signature,
322
}
323
324
impl SignedCertificate {
325
    /// Issue `cert`, signed by the issuer `issuer` holds the secret of.
326
    pub fn sign(mut cert: Certificate, issuer: &Identity, sk: &SecretKey) -> SignedCertificate {
327
        // Claims in their canonical order, as encoded.
328
        cert.claims.sort();
329
        let sig = sk.sign(Domain::Certificate, &issuer.hash(), &cert.hash());
330
        SignedCertificate { cert, sig }
331
    }
332
333
    /// Signed by `issuer`, which it names, and well formed. Whether to
334
    /// trust the issuer for its subject is the policy's question.
335
    pub fn verify(&self, issuer: &Identity) -> Result<(), CertError> {
336
        let c = &self.cert;
337
        if issuer.hash() != c.issuer || self.sig.key != c.issuer {
338
            return Err(CertError::WrongIssuer(c.issuer.short(12)));
339
        }
340
        verify(issuer, &self.sig, Domain::Certificate, &c.hash())
341
            .map_err(|e| CertError::BadSignature(e.to_string()))?;
342
        if c.expires <= c.not_before || c.expires - c.not_before > MAX_LIFETIME_MS {
343
            return Err(CertError::BadLifetime);
344
        }
345
        if c.scope.is_empty() {
346
            return Err(CertError::NoScope);
347
        }
348
        Ok(())
349
    }
350
351
    /// `[certificate bytes, signature]`.
352
    pub fn encode(&self) -> Vec<u8> {
353
        cbor::encode(&Value::Array(vec![
354
            Value::Bytes(self.cert.encode()),
355
            self.sig.to_value(),
356
        ]))
357
    }
358
359
    pub fn decode(b: &[u8]) -> Result<SignedCertificate, CertError> {
360
        let v = cbor::decode(b).map_err(ObjectError::from)?;
361
        let a = array(&v, "signed certificate")?;
362
        if a.len() != 2 {
363
            return Err(CertError::Schema(
364
                "signed certificate: expected [certificate, signature]".into(),
365
            ));
366
        }
367
        Ok(SignedCertificate {
368
            cert: Certificate::decode(bytes(&a[0], "certificate")?)?,
369
            sig: Signature::from_value(&a[1])?,
370
        })
371
    }
372
}
373
374
#[cfg(test)]
375
mod tests {
376
    use super::*;
377
378
    fn issue(
379
        issuer_sk: &SecretKey,
380
        issuer: &Identity,
381
        minutes: u64,
382
    ) -> (SecretKey, SignedCertificate) {
383
        let job_sk = SecretKey::generate();
384
        let cert = Certificate {
385
            key: job_sk.identity("job 12 build", "[email protected]", 1_000),
386
            issuer: issuer.hash(),
387
            subject: "repo:andy/demo:bookmark:main".into(),
388
            claims: vec![
389
                ("run".into(), "12".into()),
390
                ("environment".into(), "prod".into()),
391
            ],
392
            scope: Scope::CHANGES | Scope::REFS,
393
            not_before: 1_000,
394
            expires: 1_000 + minutes * 60_000,
a2387d54 Andy McCall ↶ 395
            grant: None,
02e69188 Andy McCall ↶ 396
        };
397
        (job_sk, SignedCertificate::sign(cert, issuer, issuer_sk))
398
    }
399
400
    #[test]
401
    fn a_certificate_round_trips_and_verifies_with_its_issuer_only() {
402
        let hub_sk = SecretKey::generate();
403
        let hub = hub_sk.identity("oxygenhub.io", "[email protected]", 1);
404
        let (_, sc) = issue(&hub_sk, &hub, 10);
405
        let back = SignedCertificate::decode(&sc.encode()).unwrap();
406
        assert_eq!(back, sc);
407
        assert_eq!(back.cert.claims[0].0, "environment", "claims kept sorted");
408
        assert_eq!(back.cert.claim("run"), Some("12"));
409
        assert!(back.verify(&hub).is_ok());
410
        let other_sk = SecretKey::generate();
411
        let other = other_sk.identity("elsewhere", "[email protected]", 1);
412
        assert!(matches!(
413
            back.verify(&other),
414
            Err(CertError::WrongIssuer(_))
415
        ));
416
        // Changed after signing: the signature no longer covers it.
417
        let mut forged = back.clone();
418
        forged.cert.subject = "repo:andy/demo:bookmark:release".into();
419
        assert!(matches!(
420
            forged.verify(&hub),
421
            Err(CertError::BadSignature(_))
422
        ));
423
        // Signed by another key in the issuer's name.
424
        let mut stolen = back.clone();
425
        stolen.sig = other_sk.sign(Domain::Certificate, &hub.hash(), &back.cert.hash());
426
        assert!(matches!(
427
            stolen.verify(&hub),
428
            Err(CertError::BadSignature(_))
429
        ));
a2387d54 Andy McCall ↶ 430
    }
431
432
    #[test]
433
    fn a_grant_rides_in_its_certificate_and_verifies_with_its_author_only() {
434
        let hub_sk = SecretKey::generate();
435
        let hub = hub_sk.identity("oxygenhub.io", "[email protected]", 1);
436
        let ada_sk = SecretKey::generate();
437
        let ada = ada_sk.identity("Ada", "[email protected]", 1);
438
        let g = SignedGrant::sign(
439
            Grant {
440
                grantor: ada.hash(),
441
                subject: "agent:claude@ada".into(),
442
                issuer: hub.hash(),
443
                scope: Scope::CHANGES | Scope::SEAL,
444
                not_before: 1_000,
445
                expires: 2_000,
446
            },
447
            &ada,
448
            &ada_sk,
449
        );
450
        assert!(g.verify(&ada).is_ok());
451
        assert!(g.verify(&hub).is_err(), "only its author's");
452
        assert!(g.grant.covers(Scope::SEAL, 1_500));
453
        assert!(!g.grant.covers(Scope::REFS, 1_500));
454
        assert!(!g.grant.covers(Scope::SEAL, 2_001));
455
        let (_, plain) = issue(&hub_sk, &hub, 10);
456
        assert!(
457
            !matches!(cbor::decode(&plain.cert.encode()).unwrap(), Value::Map(m) if m.contains_key(&8)),
458
            "no grant, no field 8"
459
        );
460
        let mut with = plain.cert.clone();
461
        with.grant = Some(g.clone());
462
        let sc = SignedCertificate::sign(with, &hub, &hub_sk);
463
        let back = SignedCertificate::decode(&sc.encode()).unwrap();
464
        assert_eq!(back.cert.grant, Some(g));
465
        assert!(back.verify(&hub).is_ok());
466
        assert_ne!(back.cert.hash(), plain.cert.hash());
02e69188 Andy McCall ↶ 467
    }
468
469
    #[test]
470
    fn it_covers_its_scope_and_window_only() {
471
        let hub_sk = SecretKey::generate();
472
        let hub = hub_sk.identity("oxygenhub.io", "[email protected]", 1);
473
        let (_, sc) = issue(&hub_sk, &hub, 10);
474
        let c = &sc.cert;
475
        assert!(c.covers(Scope::CHANGES, 1_000) && c.covers(Scope::REFS, 1_000 + 10 * 60_000));
476
        assert!(!c.covers(Scope::SEAL, 2_000), "not a scope it gives");
477
        assert!(!c.covers(Scope::CHANGES, 999), "before it");
478
        assert!(
479
            !c.covers(Scope::CHANGES, 1_000 + 10 * 60_000 + 1),
480
            "after it"
481
        );
482
        assert!(!c.covers(Scope::NONE, 2_000));
483
        let (_, long) = issue(&hub_sk, &hub, 61);
484
        assert_eq!(long.verify(&hub), Err(CertError::BadLifetime));
098227d4 Andy McCall ↶ 485
    }
486
487
    #[test]
488
    fn the_proof_of_possession_is_bound_to_its_credential() {
489
        let sk = SecretKey::generate();
490
        let id = sk.identity("job", "[email protected]", 1);
491
        let proof = sk
492
            .sign_challenge(&id.hash(), &certify_challenge("flowjob_aaa"))
493
            .unwrap();
494
        assert!(
495
            crate::identity::verify_challenge(&id, &proof, &certify_challenge("flowjob_aaa"))
496
                .is_ok()
497
        );
498
        assert!(
499
            crate::identity::verify_challenge(&id, &proof, &certify_challenge("flowjob_bbb"))
500
                .is_err()
501
        );
02e69188 Andy McCall ↶ 502
    }
503
504
    #[test]
505
    fn a_signature_by_the_short_lived_key_names_it() {
506
        let hub_sk = SecretKey::generate();
507
        let hub = hub_sk.identity("oxygenhub.io", "[email protected]", 1);
508
        let (job_sk, sc) = issue(&hub_sk, &hub, 10);
509
        let target = ObjectRef([5; 32]);
510
        let sig = job_sk.sign(Domain::Change, &sc.cert.key_id(), &target);
511
        assert_eq!(sig.key, sc.cert.key_id());
512
        assert!(verify(&sc.cert.key, &sig, Domain::Change, &target).is_ok());
513
    }
514
}