OXYGENHUB

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

170 of 182 lines run, 20 of 40 functions · run #308 on main · 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
}
38
39
impl Certificate {
4010×
    pub fn to_value(&self) -> Value {
4110×
        let mut claims = self.claims.clone();
4210×
        claims.sort();
4310×
        Value::map([
4410×
            (0, Value::Uint(1)),
4510×
            (1, Value::Bytes(self.key.encode())),
4610×
            (2, Value::Bytes(self.issuer.0.to_vec())),
4710×
            (3, Value::Text(self.subject.clone())),
48
            (
49
                4,
50
                Value::Array(
5110×
                    claims
5210×
                        .into_iter()
5320×
                        .map(|(k, v)| Value::Array(vec![Value::Text(k), Value::Text(v)]))
5410×
                        .collect(),
55
                ),
56
            ),
57
            (
58
                5,
59
                Value::Array(
6010×
                    self.scope
6110×
                        .names()
6210×
                        .into_iter()
6320×
                        .map(|n| Value::Text(n.to_string()))
6410×
                        .collect(),
65
                ),
66
            ),
6710×
            (6, Value::Uint(self.not_before)),
6810×
            (7, Value::Uint(self.expires)),
69
        ])
7010×
    }
71
7210×
    pub fn encode(&self) -> Vec<u8> {
7310×
        cbor::encode(&self.to_value())
7410×
    }
75
769×
    pub fn hash(&self) -> ObjectRef {
779×
        hash_object(ObjectType::Certificate, &self.encode())
789×
    }
79
80
    /// The short-lived key's KeyId: what its signatures name.
812×
    pub fn key_id(&self) -> KeyId {
822×
        self.key.hash()
832×
    }
84
851×
    pub fn decode(b: &[u8]) -> Result<Certificate, ObjectError> {
861×
        let v = cbor::decode(b)?;
871×
        let m = map(&v, "certificate")?;
881×
        check_version(m)?;
891×
        let key = Identity::decode(bytes(field(m, 1, "key")?, "key")?)?;
901×
        let mut claims = Vec::new();
912×
        for c in array(field(m, 4, "claims")?, "claims")? {
922×
            let pair = array(c, "claim")?;
932×
            if pair.len() != 2 {
940×
                return Err(ObjectError::Schema("claim: expected [name, value]".into()));
952×
            }
962×
            claims.push((
972×
                text(&pair[0], "claim name")?.to_owned(),
982×
                text(&pair[1], "claim value")?.to_owned(),
99
            ));
100
        }
1011×
        let mut scope = Scope::NONE;
1022×
        for n in array(field(m, 5, "scope")?, "scope")? {
1032×
            let n = text(n, "scope")?;
1042×
            scope = scope
1052×
                | Scope::named(n).ok_or_else(|| {
1060×
                    ObjectError::Schema(format!("certificate: unknown scope {n:?}"))
1070×
                })?;
108
        }
109
        Ok(Certificate {
1101×
            key,
1111×
            issuer: oref(field(m, 2, "issuer")?, "issuer")?,
1121×
            subject: text(field(m, 3, "subject")?, "subject")?.to_owned(),
1131×
            claims,
1141×
            scope,
1151×
            not_before: uint(field(m, 6, "not_before")?, "not_before")?,
1161×
            expires: uint(field(m, 7, "expires")?, "expires")?,
117
        })
1181×
    }
119
120
    /// Whether the key may sign within `scope` at `at_ms`, a time the
121
    /// signer did not choose.
1226×
    pub fn covers(&self, scope: Scope, at_ms: u64) -> bool {
1236×
        !scope.is_empty()
1245×
            && self.scope.has(scope)
1254×
            && self.not_before <= at_ms
1263×
            && at_ms <= self.expires
1276×
    }
128
129
    /// The claim called `name`, if the certificate has one.
1301×
    pub fn claim(&self, name: &str) -> Option<&str> {
1311×
        self.claims
1321×
            .iter()
1332×
            .find(|(k, _)| k == name)
1341×
            .map(|(_, v)| v.as_str())
1351×
    }
136
}
137
138
#[derive(Clone, Debug, PartialEq, Eq, thiserror::Error)]
139
pub enum CertError {
140
    #[error("the certificate names issuer {0}, not this one")]
141
    WrongIssuer(String),
142
    #[error("the issuer's signature does not verify: {0}")]
143
    BadSignature(String),
144
    #[error("the certificate is valid for no time, or for longer than an hour")]
145
    BadLifetime,
146
    #[error("the certificate gives no scope")]
147
    NoScope,
148
    #[error("{0}")]
149
    Schema(String),
150
}
151
152
impl From<ObjectError> for CertError {
1530×
    fn from(e: ObjectError) -> Self {
1540×
        CertError::Schema(e.to_string())
1550×
    }
156
}
157
158
/// A certificate with its issuer's signature over its ObjectRef.
159
#[derive(Clone, Debug, PartialEq, Eq)]
160
pub struct SignedCertificate {
161
    pub cert: Certificate,
162
    pub sig: Signature,
163
}
164
165
impl SignedCertificate {
166
    /// Issue `cert`, signed by the issuer `issuer` holds the secret of.
1674×
    pub fn sign(mut cert: Certificate, issuer: &Identity, sk: &SecretKey) -> SignedCertificate {
168
        // Claims in their canonical order, as encoded.
1694×
        cert.claims.sort();
1704×
        let sig = sk.sign(Domain::Certificate, &issuer.hash(), &cert.hash());
1714×
        SignedCertificate { cert, sig }
1724×
    }
173
174
    /// Signed by `issuer`, which it names, and well formed. Whether to
175
    /// trust the issuer for its subject is the policy's question.
1765×
    pub fn verify(&self, issuer: &Identity) -> Result<(), CertError> {
1775×
        let c = &self.cert;
1785×
        if issuer.hash() != c.issuer || self.sig.key != c.issuer {
1791×
            return Err(CertError::WrongIssuer(c.issuer.short(12)));
1804×
        }
1814×
        verify(issuer, &self.sig, Domain::Certificate, &c.hash())
1824×
            .map_err(|e| CertError::BadSignature(e.to_string()))?;
1832×
        if c.expires <= c.not_before || c.expires - c.not_before > MAX_LIFETIME_MS {
1841×
            return Err(CertError::BadLifetime);
1851×
        }
1861×
        if c.scope.is_empty() {
1870×
            return Err(CertError::NoScope);
1881×
        }
1891×
        Ok(())
1905×
    }
191
192
    /// `[certificate bytes, signature]`.
1931×
    pub fn encode(&self) -> Vec<u8> {
1941×
        cbor::encode(&Value::Array(vec![
1951×
            Value::Bytes(self.cert.encode()),
1961×
            self.sig.to_value(),
1971×
        ]))
1981×
    }
199
2001×
    pub fn decode(b: &[u8]) -> Result<SignedCertificate, CertError> {
2011×
        let v = cbor::decode(b).map_err(ObjectError::from)?;
2021×
        let a = array(&v, "signed certificate")?;
2031×
        if a.len() != 2 {
2040×
            return Err(CertError::Schema(
2050×
                "signed certificate: expected [certificate, signature]".into(),
2060×
            ));
2071×
        }
208
        Ok(SignedCertificate {
2091×
            cert: Certificate::decode(bytes(&a[0], "certificate")?)?,
2101×
            sig: Signature::from_value(&a[1])?,
211
        })
2121×
    }
213
}
214
215
#[cfg(test)]
216
mod tests {
217
    use super::*;
218
2194×
    fn issue(
2204×
        issuer_sk: &SecretKey,
2214×
        issuer: &Identity,
2224×
        minutes: u64,
2234×
    ) -> (SecretKey, SignedCertificate) {
2244×
        let job_sk = SecretKey::generate();
2254×
        let cert = Certificate {
2264×
            key: job_sk.identity("job 12 build", "[email protected]", 1_000),
2274×
            issuer: issuer.hash(),
2284×
            subject: "repo:andy/demo:bookmark:main".into(),
2294×
            claims: vec![
2304×
                ("run".into(), "12".into()),
2314×
                ("environment".into(), "prod".into()),
2324×
            ],
2334×
            scope: Scope::CHANGES | Scope::REFS,
2344×
            not_before: 1_000,
2354×
            expires: 1_000 + minutes * 60_000,
2364×
        };
2374×
        (job_sk, SignedCertificate::sign(cert, issuer, issuer_sk))
2384×
    }
239
240
    #[test]
2411×
    fn a_certificate_round_trips_and_verifies_with_its_issuer_only() {
2421×
        let hub_sk = SecretKey::generate();
2431×
        let hub = hub_sk.identity("oxygenhub.io", "[email protected]", 1);
2441×
        let (_, sc) = issue(&hub_sk, &hub, 10);
2451×
        let back = SignedCertificate::decode(&sc.encode()).unwrap();
2461×
        assert_eq!(back, sc);
2471×
        assert_eq!(back.cert.claims[0].0, "environment", "claims kept sorted");
2481×
        assert_eq!(back.cert.claim("run"), Some("12"));
2491×
        assert!(back.verify(&hub).is_ok());
2501×
        let other_sk = SecretKey::generate();
2511×
        let other = other_sk.identity("elsewhere", "[email protected]", 1);
2521×
        assert!(matches!(
2531×
            back.verify(&other),
254
            Err(CertError::WrongIssuer(_))
255
        ));
256
        // Changed after signing: the signature no longer covers it.
2571×
        let mut forged = back.clone();
2581×
        forged.cert.subject = "repo:andy/demo:bookmark:release".into();
2591×
        assert!(matches!(
2601×
            forged.verify(&hub),
261
            Err(CertError::BadSignature(_))
262
        ));
263
        // Signed by another key in the issuer's name.
2641×
        let mut stolen = back.clone();
2651×
        stolen.sig = other_sk.sign(Domain::Certificate, &hub.hash(), &back.cert.hash());
2661×
        assert!(matches!(
2671×
            stolen.verify(&hub),
268
            Err(CertError::BadSignature(_))
269
        ));
2701×
    }
271
272
    #[test]
2731×
    fn it_covers_its_scope_and_window_only() {
2741×
        let hub_sk = SecretKey::generate();
2751×
        let hub = hub_sk.identity("oxygenhub.io", "[email protected]", 1);
2761×
        let (_, sc) = issue(&hub_sk, &hub, 10);
2771×
        let c = &sc.cert;
2781×
        assert!(c.covers(Scope::CHANGES, 1_000) && c.covers(Scope::REFS, 1_000 + 10 * 60_000));
2791×
        assert!(!c.covers(Scope::SEAL, 2_000), "not a scope it gives");
2801×
        assert!(!c.covers(Scope::CHANGES, 999), "before it");
2811×
        assert!(
2821×
            !c.covers(Scope::CHANGES, 1_000 + 10 * 60_000 + 1),
283
            "after it"
284
        );
2851×
        assert!(!c.covers(Scope::NONE, 2_000));
2861×
        let (_, long) = issue(&hub_sk, &hub, 61);
2871×
        assert_eq!(long.verify(&hub), Err(CertError::BadLifetime));
2881×
    }
289
290
    #[test]
2911×
    fn a_signature_by_the_short_lived_key_names_it() {
2921×
        let hub_sk = SecretKey::generate();
2931×
        let hub = hub_sk.identity("oxygenhub.io", "[email protected]", 1);
2941×
        let (job_sk, sc) = issue(&hub_sk, &hub, 10);
2951×
        let target = ObjectRef([5; 32]);
2961×
        let sig = job_sk.sign(Domain::Change, &sc.cert.key_id(), &target);
2971×
        assert_eq!(sig.key, sc.cert.key_id());
2981×
        assert!(verify(&sc.cert.key, &sig, Domain::Change, &target).is_ok());
2991×
    }
300
}