OXYGENHUB

Coverage / crates/oxy-core/src/cert.rs 93.8%

305 of 325 lines run, 33 of 70 functions · run #348 on paths-for-resolutions-and-amend · run missed

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
11
//! in (a host's acceptance now, the transparency log's later).
12
13
use crate::cbor::{self, Value};
14
use crate::hash::{hash_object, KeyId, ObjectRef, ObjectType};
15
use crate::identity::{verify, Domain, Identity, Scope, SecretKey, Signature};
16
use crate::objects::{array, bytes, check_version, field, map, oref, text, uint, ObjectError};
17
18
/// The longest a certificate may be valid. Jobs get ten minutes; an hour
19
/// leaves room for an issuer that rounds up, and no more.
20
pub const MAX_LIFETIME_MS: u64 = 60 * 60 * 1000;
21
22
#[derive(Clone, Debug, PartialEq, Eq)]
23
pub struct Certificate {
24
    /// The short-lived key's public identity.
25
    pub key: Identity,
26
    /// The issuer's KeyId (a hub's key).
27
    pub issuer: KeyId,
28
    /// Who proved it: `repo:OWNER/NAME:bookmark:B`, `agent:NAME@ACCOUNT`.
29
    pub subject: String,
30
    /// What else the proof said (environment, run, job), sorted by name.
31
    pub claims: Vec<(String, String)>,
32
    /// What the key may sign: changes, refs, seals.
33
    pub scope: Scope,
34
    /// Valid from and until, in wall milliseconds.
35
    pub not_before: u64,
36
    pub expires: u64,
37
    /// The grant that lets the subject act for an author, when an agent
38
    /// asked with one (field 8, only when present).
39
    pub grant: Option<SignedGrant>,
40
}
41
42
impl Certificate {
43110×
    pub fn to_value(&self) -> Value {
44110×
        let mut claims = self.claims.clone();
45110×
        claims.sort();
46110×
        let mut v = Value::map([
47110×
            (0, Value::Uint(1)),
48110×
            (1, Value::Bytes(self.key.encode())),
49110×
            (2, Value::Bytes(self.issuer.0.to_vec())),
50110×
            (3, Value::Text(self.subject.clone())),
51
            (
52
                4,
53
                Value::Array(
54110×
                    claims
55110×
                        .into_iter()
56110×
                        .map(|(k, v)| Value::Array(vec![Value::Text(k), Value::Text(v)]))
57110×
                        .collect(),
58
                ),
59
            ),
60
            (
61
                5,
62
                Value::Array(
63110×
                    self.scope
64110×
                        .names()
65110×
                        .into_iter()
66247×
                        .map(|n| Value::Text(n.to_string()))
67110×
                        .collect(),
68
                ),
69
            ),
70110×
            (6, Value::Uint(self.not_before)),
71110×
            (7, Value::Uint(self.expires)),
72
        ]);
73110×
        if let (Some(g), Value::Map(m)) = (&self.grant, &mut v) {
7442×
            m.insert(8, Value::Bytes(g.encode()));
7568×
        }
76110×
        v
77110×
    }
78
79110×
    pub fn encode(&self) -> Vec<u8> {
80110×
        cbor::encode(&self.to_value())
81110×
    }
82
8383×
    pub fn hash(&self) -> ObjectRef {
8483×
        hash_object(ObjectType::Certificate, &self.encode())
8583×
    }
86
87
    /// The short-lived key's KeyId: what its signatures name.
8844×
    pub fn key_id(&self) -> KeyId {
8944×
        self.key.hash()
9044×
    }
91
9266×
    pub fn decode(b: &[u8]) -> Result<Certificate, ObjectError> {
9366×
        let v = cbor::decode(b)?;
9466×
        let m = map(&v, "certificate")?;
9566×
        check_version(m)?;
9666×
        let key = Identity::decode(bytes(field(m, 1, "key")?, "key")?)?;
9766×
        let mut claims = Vec::new();
9866×
        for c in array(field(m, 4, "claims")?, "claims")? {
995×
            let pair = array(c, "claim")?;
1005×
            if pair.len() != 2 {
1010×
                return Err(ObjectError::Schema("claim: expected [name, value]".into()));
1025×
            }
1035×
            claims.push((
1045×
                text(&pair[0], "claim name")?.to_owned(),
1055×
                text(&pair[1], "claim value")?.to_owned(),
106
            ));
107
        }
10866×
        let mut scope = Scope::NONE;
109155×
        for n in array(field(m, 5, "scope")?, "scope")? {
110155×
            let n = text(n, "scope")?;
111155×
            scope = scope
112155×
                | Scope::named(n).ok_or_else(|| {
1130×
                    ObjectError::Schema(format!("certificate: unknown scope {n:?}"))
1140×
                })?;
115
        }
116
        Ok(Certificate {
11766×
            key,
11866×
            issuer: oref(field(m, 2, "issuer")?, "issuer")?,
11966×
            subject: text(field(m, 3, "subject")?, "subject")?.to_owned(),
12066×
            claims,
12166×
            scope,
12266×
            not_before: uint(field(m, 6, "not_before")?, "not_before")?,
12366×
            expires: uint(field(m, 7, "expires")?, "expires")?,
12466×
            grant: match m.get(&8) {
12527×
                Some(g) => Some(
12627×
                    SignedGrant::decode(bytes(g, "grant")?)
12727×
                        .map_err(|e| ObjectError::Schema(format!("grant: {e}")))?,
128
                ),
12939×
                None => None,
130
            },
131
        })
13266×
    }
133
134
    /// Whether the key may sign within `scope` at `at_ms`, a time the
135
    /// signer did not choose.
13625×
    pub fn covers(&self, scope: Scope, at_ms: u64) -> bool {
13725×
        !scope.is_empty()
13824×
            && self.scope.has(scope)
13922×
            && self.not_before <= at_ms
14021×
            && at_ms <= self.expires
14125×
    }
142
143
    /// The claim called `name`, if the certificate has one.
1441×
    pub fn claim(&self, name: &str) -> Option<&str> {
1451×
        self.claims
1461×
            .iter()
1472×
            .find(|(k, _)| k == name)
1481×
            .map(|(_, v)| v.as_str())
1491×
    }
150
}
151
152
/// An author's grant (spec §14.7): it lets the keys an issuer certifies
153
/// for `subject` act for the author, as a delegate does, without a key of
154
/// their own. An agent's fresh keys then sign and seal changes in the
155
/// author's name while the grant lasts; the grant travels inside their
156
/// certificates, so a verifier needs nothing else. Signed by the author.
157
#[derive(Clone, Debug, PartialEq, Eq)]
158
pub struct Grant {
159
    /// The author's KeyId, which signs the grant.
160
    pub grantor: KeyId,
161
    /// The subject whose certified keys act for it: `agent:NAME@ACCOUNT`.
162
    pub subject: String,
163
    /// The issuer whose certificates count.
164
    pub issuer: KeyId,
165
    /// What they may do for the author: changes, seal.
166
    pub scope: Scope,
167
    /// Valid from and until, in wall milliseconds.
168
    pub not_before: u64,
169
    pub expires: u64,
170
}
171
172
impl Grant {
17353×
    pub fn to_value(&self) -> Value {
17453×
        Value::map([
17553×
            (0, Value::Uint(1)),
17653×
            (1, Value::Bytes(self.grantor.0.to_vec())),
17753×
            (2, Value::Text(self.subject.clone())),
17853×
            (3, Value::Bytes(self.issuer.0.to_vec())),
179
            (
180
                4,
181
                Value::Array(
18253×
                    self.scope
18353×
                        .names()
18453×
                        .into_iter()
185106×
                        .map(|n| Value::Text(n.to_string()))
18653×
                        .collect(),
187
                ),
188
            ),
18953×
            (5, Value::Uint(self.not_before)),
19053×
            (6, Value::Uint(self.expires)),
191
        ])
19253×
    }
193
19453×
    pub fn encode(&self) -> Vec<u8> {
19553×
        cbor::encode(&self.to_value())
19653×
    }
197
19811×
    pub fn hash(&self) -> ObjectRef {
19911×
        hash_object(ObjectType::Grant, &self.encode())
20011×
    }
201
20227×
    pub fn decode(b: &[u8]) -> Result<Grant, ObjectError> {
20327×
        let v = cbor::decode(b)?;
20427×
        let m = map(&v, "grant")?;
20527×
        check_version(m)?;
20627×
        let mut scope = Scope::NONE;
20754×
        for n in array(field(m, 4, "scope")?, "scope")? {
20854×
            let n = text(n, "scope")?;
20954×
            scope = scope
21054×
                | Scope::named(n)
21154×
                    .ok_or_else(|| ObjectError::Schema(format!("grant: unknown scope {n:?}")))?;
212
        }
213
        Ok(Grant {
21427×
            grantor: oref(field(m, 1, "grantor")?, "grantor")?,
21527×
            subject: text(field(m, 2, "subject")?, "subject")?.to_owned(),
21627×
            issuer: oref(field(m, 3, "issuer")?, "issuer")?,
21727×
            scope,
21827×
            not_before: uint(field(m, 5, "not_before")?, "not_before")?,
21927×
            expires: uint(field(m, 6, "expires")?, "expires")?,
220
        })
22127×
    }
222
223
    /// Whether it lets its subject do `scope` for the author at `at_ms`
224
    /// (the change's own time, as for a delegation).
2259×
    pub fn covers(&self, scope: Scope, at_ms: u64) -> bool {
2269×
        !scope.is_empty()
2279×
            && self.scope.has(scope)
2288×
            && self.not_before <= at_ms
2298×
            && at_ms <= self.expires
2309×
    }
231
}
232
233
/// A grant with its author's signature over its ObjectRef.
234
#[derive(Clone, Debug, PartialEq, Eq)]
235
pub struct SignedGrant {
236
    pub grant: Grant,
237
    pub sig: Signature,
238
}
239
240
impl SignedGrant {
241
    /// Grant `grant`, signed by the author `grantor` holds the secret of.
2424×
    pub fn sign(grant: Grant, grantor: &Identity, sk: &SecretKey) -> SignedGrant {
2434×
        let sig = sk.sign(Domain::Grant, &grantor.hash(), &grant.hash());
2444×
        SignedGrant { grant, sig }
2454×
    }
246
247
    /// Signed by `grantor`, which it names, and well formed.
2488×
    pub fn verify(&self, grantor: &Identity) -> Result<(), CertError> {
2498×
        let g = &self.grant;
2508×
        if grantor.hash() != g.grantor || self.sig.key != g.grantor {
2511×
            return Err(CertError::WrongIssuer(g.grantor.short(12)));
2527×
        }
2537×
        verify(grantor, &self.sig, Domain::Grant, &g.hash())
2547×
            .map_err(|e| CertError::BadSignature(e.to_string()))?;
2557×
        if g.expires <= g.not_before {
2560×
            return Err(CertError::BadLifetime);
2577×
        }
2587×
        if g.scope.is_empty() {
2590×
            return Err(CertError::NoScope);
2607×
        }
2617×
        Ok(())
2628×
    }
263
264
    /// `[grant bytes, signature]`.
26542×
    pub fn encode(&self) -> Vec<u8> {
26642×
        cbor::encode(&Value::Array(vec![
26742×
            Value::Bytes(self.grant.encode()),
26842×
            self.sig.to_value(),
26942×
        ]))
27042×
    }
271
27227×
    pub fn decode(b: &[u8]) -> Result<SignedGrant, CertError> {
27327×
        let v = cbor::decode(b).map_err(ObjectError::from)?;
27427×
        let a = array(&v, "signed grant")?;
27527×
        if a.len() != 2 {
2760×
            return Err(CertError::Schema(
2770×
                "signed grant: expected [grant, signature]".into(),
2780×
            ));
27927×
        }
280
        Ok(SignedGrant {
28127×
            grant: Grant::decode(bytes(&a[0], "grant")?)?,
28227×
            sig: Signature::from_value(&a[1])?,
283
        })
28427×
    }
285
}
286
287
/// What a fresh key signs (a challenge, §14.3) to show its holder asks for
288
/// the certificate: bound to the credential it is asked with, so the
289
/// proof cannot be replayed with another.
2903×
pub fn certify_challenge(credential: &str) -> Vec<u8> {
2913×
    let mut c = b"oxy1 certify ".to_vec();
2923×
    c.extend_from_slice(blake3::hash(credential.as_bytes()).as_bytes());
2933×
    c
2943×
}
295
296
#[derive(Clone, Debug, PartialEq, Eq, thiserror::Error)]
297
pub enum CertError {
298
    #[error("the certificate names issuer {0}, not this one")]
299
    WrongIssuer(String),
300
    #[error("the issuer's signature does not verify: {0}")]
301
    BadSignature(String),
302
    #[error("the certificate is valid for no time, or for longer than an hour")]
303
    BadLifetime,
304
    #[error("the certificate gives no scope")]
305
    NoScope,
306
    #[error("{0}")]
307
    Schema(String),
308
}
309
310
impl From<ObjectError> for CertError {
3110×
    fn from(e: ObjectError) -> Self {
3120×
        CertError::Schema(e.to_string())
3130×
    }
314
}
315
316
/// A certificate with its issuer's signature over its ObjectRef.
317
#[derive(Clone, Debug, PartialEq, Eq)]
318
pub struct SignedCertificate {
319
    pub cert: Certificate,
320
    pub sig: Signature,
321
}
322
323
impl SignedCertificate {
324
    /// Issue `cert`, signed by the issuer `issuer` holds the secret of.
32520×
    pub fn sign(mut cert: Certificate, issuer: &Identity, sk: &SecretKey) -> SignedCertificate {
326
        // Claims in their canonical order, as encoded.
32720×
        cert.claims.sort();
32820×
        let sig = sk.sign(Domain::Certificate, &issuer.hash(), &cert.hash());
32920×
        SignedCertificate { cert, sig }
33020×
    }
331
332
    /// Signed by `issuer`, which it names, and well formed. Whether to
333
    /// trust the issuer for its subject is the policy's question.
33448×
    pub fn verify(&self, issuer: &Identity) -> Result<(), CertError> {
33548×
        let c = &self.cert;
33648×
        if issuer.hash() != c.issuer || self.sig.key != c.issuer {
3372×
            return Err(CertError::WrongIssuer(c.issuer.short(12)));
33846×
        }
33946×
        verify(issuer, &self.sig, Domain::Certificate, &c.hash())
34046×
            .map_err(|e| CertError::BadSignature(e.to_string()))?;
34144×
        if c.expires <= c.not_before || c.expires - c.not_before > MAX_LIFETIME_MS {
3421×
            return Err(CertError::BadLifetime);
34343×
        }
34443×
        if c.scope.is_empty() {
3450×
            return Err(CertError::NoScope);
34643×
        }
34743×
        Ok(())
34848×
    }
349
350
    /// `[certificate bytes, signature]`.
3514×
    pub fn encode(&self) -> Vec<u8> {
3524×
        cbor::encode(&Value::Array(vec![
3534×
            Value::Bytes(self.cert.encode()),
3544×
            self.sig.to_value(),
3554×
        ]))
3564×
    }
357
3584×
    pub fn decode(b: &[u8]) -> Result<SignedCertificate, CertError> {
3594×
        let v = cbor::decode(b).map_err(ObjectError::from)?;
3604×
        let a = array(&v, "signed certificate")?;
3614×
        if a.len() != 2 {
3620×
            return Err(CertError::Schema(
3630×
                "signed certificate: expected [certificate, signature]".into(),
3640×
            ));
3654×
        }
366
        Ok(SignedCertificate {
3674×
            cert: Certificate::decode(bytes(&a[0], "certificate")?)?,
3684×
            sig: Signature::from_value(&a[1])?,
369
        })
3704×
    }
371
}
372
373
#[cfg(test)]
374
mod tests {
375
    use super::*;
376
3775×
    fn issue(
3785×
        issuer_sk: &SecretKey,
3795×
        issuer: &Identity,
3805×
        minutes: u64,
3815×
    ) -> (SecretKey, SignedCertificate) {
3825×
        let job_sk = SecretKey::generate();
3835×
        let cert = Certificate {
3845×
            key: job_sk.identity("job 12 build", "[email protected]", 1_000),
3855×
            issuer: issuer.hash(),
3865×
            subject: "repo:andy/demo:bookmark:main".into(),
3875×
            claims: vec![
3885×
                ("run".into(), "12".into()),
3895×
                ("environment".into(), "prod".into()),
3905×
            ],
3915×
            scope: Scope::CHANGES | Scope::REFS,
3925×
            not_before: 1_000,
3935×
            expires: 1_000 + minutes * 60_000,
3945×
            grant: None,
3955×
        };
3965×
        (job_sk, SignedCertificate::sign(cert, issuer, issuer_sk))
3975×
    }
398
399
    #[test]
4001×
    fn a_certificate_round_trips_and_verifies_with_its_issuer_only() {
4011×
        let hub_sk = SecretKey::generate();
4021×
        let hub = hub_sk.identity("oxygenhub.io", "[email protected]", 1);
4031×
        let (_, sc) = issue(&hub_sk, &hub, 10);
4041×
        let back = SignedCertificate::decode(&sc.encode()).unwrap();
4051×
        assert_eq!(back, sc);
4061×
        assert_eq!(back.cert.claims[0].0, "environment", "claims kept sorted");
4071×
        assert_eq!(back.cert.claim("run"), Some("12"));
4081×
        assert!(back.verify(&hub).is_ok());
4091×
        let other_sk = SecretKey::generate();
4101×
        let other = other_sk.identity("elsewhere", "[email protected]", 1);
4111×
        assert!(matches!(
4121×
            back.verify(&other),
413
            Err(CertError::WrongIssuer(_))
414
        ));
415
        // Changed after signing: the signature no longer covers it.
4161×
        let mut forged = back.clone();
4171×
        forged.cert.subject = "repo:andy/demo:bookmark:release".into();
4181×
        assert!(matches!(
4191×
            forged.verify(&hub),
420
            Err(CertError::BadSignature(_))
421
        ));
422
        // Signed by another key in the issuer's name.
4231×
        let mut stolen = back.clone();
4241×
        stolen.sig = other_sk.sign(Domain::Certificate, &hub.hash(), &back.cert.hash());
4251×
        assert!(matches!(
4261×
            stolen.verify(&hub),
427
            Err(CertError::BadSignature(_))
428
        ));
4291×
    }
430
431
    #[test]
4321×
    fn a_grant_rides_in_its_certificate_and_verifies_with_its_author_only() {
4331×
        let hub_sk = SecretKey::generate();
4341×
        let hub = hub_sk.identity("oxygenhub.io", "[email protected]", 1);
4351×
        let ada_sk = SecretKey::generate();
4361×
        let ada = ada_sk.identity("Ada", "[email protected]", 1);
4371×
        let g = SignedGrant::sign(
4381×
            Grant {
4391×
                grantor: ada.hash(),
4401×
                subject: "agent:claude@ada".into(),
4411×
                issuer: hub.hash(),
4421×
                scope: Scope::CHANGES | Scope::SEAL,
4431×
                not_before: 1_000,
4441×
                expires: 2_000,
4451×
            },
4461×
            &ada,
4471×
            &ada_sk,
448
        );
4491×
        assert!(g.verify(&ada).is_ok());
4501×
        assert!(g.verify(&hub).is_err(), "only its author's");
4511×
        assert!(g.grant.covers(Scope::SEAL, 1_500));
4521×
        assert!(!g.grant.covers(Scope::REFS, 1_500));
4531×
        assert!(!g.grant.covers(Scope::SEAL, 2_001));
4541×
        let (_, plain) = issue(&hub_sk, &hub, 10);
4551×
        assert!(
4561×
            !matches!(cbor::decode(&plain.cert.encode()).unwrap(), Value::Map(m) if m.contains_key(&8)),
457
            "no grant, no field 8"
458
        );
4591×
        let mut with = plain.cert.clone();
4601×
        with.grant = Some(g.clone());
4611×
        let sc = SignedCertificate::sign(with, &hub, &hub_sk);
4621×
        let back = SignedCertificate::decode(&sc.encode()).unwrap();
4631×
        assert_eq!(back.cert.grant, Some(g));
4641×
        assert!(back.verify(&hub).is_ok());
4651×
        assert_ne!(back.cert.hash(), plain.cert.hash());
4661×
    }
467
468
    #[test]
4691×
    fn it_covers_its_scope_and_window_only() {
4701×
        let hub_sk = SecretKey::generate();
4711×
        let hub = hub_sk.identity("oxygenhub.io", "[email protected]", 1);
4721×
        let (_, sc) = issue(&hub_sk, &hub, 10);
4731×
        let c = &sc.cert;
4741×
        assert!(c.covers(Scope::CHANGES, 1_000) && c.covers(Scope::REFS, 1_000 + 10 * 60_000));
4751×
        assert!(!c.covers(Scope::SEAL, 2_000), "not a scope it gives");
4761×
        assert!(!c.covers(Scope::CHANGES, 999), "before it");
4771×
        assert!(
4781×
            !c.covers(Scope::CHANGES, 1_000 + 10 * 60_000 + 1),
479
            "after it"
480
        );
4811×
        assert!(!c.covers(Scope::NONE, 2_000));
4821×
        let (_, long) = issue(&hub_sk, &hub, 61);
4831×
        assert_eq!(long.verify(&hub), Err(CertError::BadLifetime));
4841×
    }
485
486
    #[test]
4871×
    fn the_proof_of_possession_is_bound_to_its_credential() {
4881×
        let sk = SecretKey::generate();
4891×
        let id = sk.identity("job", "[email protected]", 1);
4901×
        let proof = sk
4911×
            .sign_challenge(&id.hash(), &certify_challenge("flowjob_aaa"))
4921×
            .unwrap();
4931×
        assert!(
4941×
            crate::identity::verify_challenge(&id, &proof, &certify_challenge("flowjob_aaa"))
4951×
                .is_ok()
496
        );
4971×
        assert!(
4981×
            crate::identity::verify_challenge(&id, &proof, &certify_challenge("flowjob_bbb"))
4991×
                .is_err()
500
        );
5011×
    }
502
503
    #[test]
5041×
    fn a_signature_by_the_short_lived_key_names_it() {
5051×
        let hub_sk = SecretKey::generate();
5061×
        let hub = hub_sk.identity("oxygenhub.io", "[email protected]", 1);
5071×
        let (job_sk, sc) = issue(&hub_sk, &hub, 10);
5081×
        let target = ObjectRef([5; 32]);
5091×
        let sig = job_sk.sign(Domain::Change, &sc.cert.key_id(), &target);
5101×
        assert_eq!(sig.key, sc.cert.key_id());
5111×
        assert!(verify(&sc.cert.key, &sig, Domain::Change, &target).is_ok());
5121×
    }
513
}