OXYGENHUB

Coverage / crates/oxy-core/src/attest.rs 93.9%

200 of 213 lines run, 23 of 28 functions · run #357 on main · run missed

1
//! Attestations (spec §14.4): signed statements about references and batches
2
//! of changes, and runs (receipts, §14.6).
3
4
use crate::cbor::{self, Value};
5
use crate::hash::{hash_object, ChangeHash, KeyId, ObjectRef, ObjectType};
6
use crate::objects::{
7
    array, bytes, check_version, field, map, oref, text, uint, Hlc, ObjectError, FORMAT_VERSION,
8
};
9
10
pub const MAX_SEAL_HASHES: usize = 4096;
11
12
#[derive(Clone, Debug, PartialEq, Eq)]
13
pub enum AttestBody {
14
    /// A bookmark moved from `old_state` to `new_state` (spec §10.2).
15
    Ref {
16
        name: String,
17
        old_state: ObjectRef,
18
        new_state: ObjectRef,
19
        serial: u64,
20
    },
21
    /// One signature covering a batch of changes (spec §14.4).
22
    Seal { hashes: Vec<ChangeHash> },
23
    /// An immutable named state (spec §10.1).
24
    Tag {
25
        name: String,
26
        state: ObjectRef,
27
        message: String,
28
    },
29
    /// The signing key's identity was replaced by `new` (spec §14.2).
30
    Rotate { new: KeyId },
31
    /// `key` must no longer be trusted (spec §14.2).
32
    Revoke { key: KeyId, reason: String },
33
    /// A runner ran the job of `receipt` on `state` (spec §14.6); `run`
34
    /// names the run, usually by URL.
35
    Receipt {
36
        receipt: ObjectRef,
37
        state: ObjectRef,
38
        run: String,
39
    },
40
    /// A person approved (or rejected) one job of one run (OxygenFlow
41
    /// approval gates; oxygenhub#235): the job as hashed with its sandbox,
42
    /// on that state, taking exactly those input blobs (a reviewed plan),
43
    /// for that environment. It approves nothing else.
44
    Approval {
45
        run: String,
46
        job: String,
47
        job_hash: ObjectRef,
48
        state: ObjectRef,
49
        inputs: Vec<ObjectRef>,
50
        environment: String,
51
        approve: bool,
52
    },
53
    /// A host accepted the reference attestation `attest`, at this
54
    /// attestation's own time, the host's clock (§14.7): the time a
55
    /// certificate of a short-lived key is checked at on a fetch.
56
    Accepted { attest: ObjectRef },
57
}
58
59
#[derive(Clone, Debug, PartialEq, Eq)]
60
pub struct Attest {
61
    /// Repository ID chosen at init.
62
    pub repo: [u8; 16],
63
    pub hlc: Hlc,
64
    pub body: AttestBody,
65
}
66
67
impl Attest {
68902×
    pub fn kind(&self) -> &'static str {
69902×
        match self.body {
70612×
            AttestBody::Ref { .. } => "ref",
71157×
            AttestBody::Seal { .. } => "seal",
7250×
            AttestBody::Tag { .. } => "tag",
7317×
            AttestBody::Rotate { .. } => "rotate",
744×
            AttestBody::Revoke { .. } => "revoke",
7541×
            AttestBody::Receipt { .. } => "receipt",
7612×
            AttestBody::Approval { .. } => "approval",
779×
            AttestBody::Accepted { .. } => "accepted",
78
        }
79902×
    }
80
8149×
    pub fn seal(repo: [u8; 16], mut hashes: Vec<ChangeHash>) -> Attest {
8249×
        hashes.sort();
8349×
        hashes.dedup();
8449×
        Attest {
8549×
            repo,
8649×
            hlc: Hlc::now(),
8749×
            body: AttestBody::Seal { hashes },
8849×
        }
8949×
    }
90
91900×
    pub fn to_value(&self) -> Value {
92900×
        let body = match &self.body {
93
            AttestBody::Ref {
94611×
                name,
95611×
                old_state,
96611×
                new_state,
97611×
                serial,
98611×
            } => Value::map([
99611×
                (0, Value::Text(name.clone())),
100611×
                (1, Value::Bytes(old_state.0.to_vec())),
101611×
                (2, Value::Bytes(new_state.0.to_vec())),
102611×
                (3, Value::Uint(*serial)),
103611×
            ]),
104157×
            AttestBody::Seal { hashes } => Value::map([(
105
                0,
106168×
                Value::Array(hashes.iter().map(|h| Value::Bytes(h.0.to_vec())).collect()),
107
            )]),
108
            AttestBody::Tag {
10949×
                name,
11049×
                state,
11149×
                message,
11249×
            } => Value::map([
11349×
                (0, Value::Text(name.clone())),
11449×
                (1, Value::Bytes(state.0.to_vec())),
11549×
                (2, Value::Text(message.clone())),
11649×
            ]),
11717×
            AttestBody::Rotate { new } => Value::map([(0, Value::Bytes(new.0.to_vec()))]),
1184×
            AttestBody::Revoke { key, reason } => Value::map([
1194×
                (0, Value::Bytes(key.0.to_vec())),
1204×
                (1, Value::Text(reason.clone())),
1214×
            ]),
122
            AttestBody::Receipt {
12341×
                receipt,
12441×
                state,
12541×
                run,
12641×
            } => Value::map([
12741×
                (0, Value::Bytes(receipt.0.to_vec())),
12841×
                (1, Value::Bytes(state.0.to_vec())),
12941×
                (2, Value::Text(run.clone())),
13041×
            ]),
1319×
            AttestBody::Accepted { attest } => Value::map([(0, Value::Bytes(attest.0.to_vec()))]),
132
            AttestBody::Approval {
13312×
                run,
13412×
                job,
13512×
                job_hash,
13612×
                state,
13712×
                inputs,
13812×
                environment,
13912×
                approve,
14012×
            } => Value::map([
14112×
                (0, Value::Text(run.clone())),
14212×
                (1, Value::Text(job.clone())),
14312×
                (2, Value::Bytes(job_hash.0.to_vec())),
14412×
                (3, Value::Bytes(state.0.to_vec())),
145
                (
146
                    4,
14718×
                    Value::Array(inputs.iter().map(|i| Value::Bytes(i.0.to_vec())).collect()),
148
                ),
14912×
                (5, Value::Text(environment.clone())),
15012×
                (6, Value::Uint(u64::from(*approve))),
151
            ]),
152
        };
153900×
        Value::map([
154900×
            (0, Value::Uint(FORMAT_VERSION)),
155900×
            (1, Value::Text(self.kind().into())),
156900×
            (2, Value::Bytes(self.repo.to_vec())),
157900×
            (3, self.hlc.to_value()),
158900×
            (4, body),
159900×
        ])
160900×
    }
161
162900×
    pub fn encode(&self) -> Vec<u8> {
163900×
        cbor::encode(&self.to_value())
164900×
    }
165
166425×
    pub fn hash(&self) -> ObjectRef {
167425×
        hash_object(ObjectType::Attest, &self.encode())
168425×
    }
169
170967×
    pub fn decode(b: &[u8]) -> Result<Attest, ObjectError> {
171967×
        let v = cbor::decode(b)?;
172967×
        let m = map(&v, "attest")?;
173967×
        check_version(m)?;
174967×
        let kind = text(field(m, 1, "kind")?, "kind")?;
175967×
        let repo: [u8; 16] = bytes(field(m, 2, "repo")?, "repo")?
176967×
            .try_into()
177967×
            .map_err(|_| ObjectError::Schema("repo: expected 16 bytes".into()))?;
178967×
        let hlc = Hlc::from_value(field(m, 3, "hlc")?)?;
179967×
        let b = map(field(m, 4, "body")?, "body")?;
180967×
        let body = match kind {
181967×
            "ref" => AttestBody::Ref {
182422×
                name: text(field(b, 0, "name")?, "name")?.to_owned(),
183422×
                old_state: oref(field(b, 1, "old_state")?, "old_state")?,
184422×
                new_state: oref(field(b, 2, "new_state")?, "new_state")?,
185422×
                serial: uint(field(b, 3, "serial")?, "serial")?,
186
            },
187545×
            "seal" => {
188368×
                let hashes = array(field(b, 0, "hashes")?, "hashes")?
189368×
                    .iter()
190404×
                    .map(|h| oref(h, "hash"))
191368×
                    .collect::<Result<Vec<_>, _>>()?;
192368×
                if hashes.is_empty()
193367×
                    || hashes.len() > MAX_SEAL_HASHES
194367×
                    || !hashes.windows(2).all(|w| w[0] < w[1])
195
                {
1962×
                    return Err(ObjectError::Schema(
1972×
                        "seal: hashes must be 1..4096, sorted and unique".into(),
1982×
                    ));
199366×
                }
200366×
                AttestBody::Seal { hashes }
201
            }
202177×
            "tag" => AttestBody::Tag {
203143×
                name: text(field(b, 0, "name")?, "name")?.to_owned(),
204143×
                state: oref(field(b, 1, "state")?, "state")?,
205143×
                message: text(field(b, 2, "message")?, "message")?.to_owned(),
206
            },
20734×
            "rotate" => AttestBody::Rotate {
2080×
                new: oref(field(b, 0, "new")?, "new")?,
209
            },
21034×
            "revoke" => AttestBody::Revoke {
2110×
                key: oref(field(b, 0, "key")?, "key")?,
2120×
                reason: text(field(b, 1, "reason")?, "reason")?.to_owned(),
213
            },
21434×
            "receipt" => AttestBody::Receipt {
21521×
                receipt: oref(field(b, 0, "receipt")?, "receipt")?,
21621×
                state: oref(field(b, 1, "state")?, "state")?,
21721×
                run: text(field(b, 2, "run")?, "run")?.to_owned(),
218
            },
21913×
            "approval" => {
2203×
                let inputs = array(field(b, 4, "inputs")?, "inputs")?
2213×
                    .iter()
2224×
                    .map(|h| oref(h, "input"))
2233×
                    .collect::<Result<Vec<_>, _>>()?;
2243×
                if !inputs.windows(2).all(|w| w[0] < w[1]) {
2250×
                    return Err(ObjectError::Schema(
2260×
                        "approval: inputs must be sorted and unique".into(),
2270×
                    ));
2283×
                }
229
                AttestBody::Approval {
2303×
                    run: text(field(b, 0, "run")?, "run")?.to_owned(),
2313×
                    job: text(field(b, 1, "job")?, "job")?.to_owned(),
2323×
                    job_hash: oref(field(b, 2, "job_hash")?, "job_hash")?,
2333×
                    state: oref(field(b, 3, "state")?, "state")?,
2343×
                    inputs,
2353×
                    environment: text(field(b, 5, "environment")?, "environment")?.to_owned(),
2363×
                    approve: match uint(field(b, 6, "approve")?, "approve")? {
2370×
                        0 => false,
2383×
                        1 => true,
2390×
                        _ => return Err(ObjectError::Schema("approval: approve is 0 or 1".into())),
240
                    },
241
                }
242
            }
24310×
            "accepted" => AttestBody::Accepted {
24410×
                attest: oref(field(b, 0, "attest")?, "attest")?,
245
            },
2460×
            other => {
2470×
                return Err(ObjectError::Schema(format!(
2480×
                    "unknown attestation kind {other:?}"
2490×
                )))
250
            }
251
        };
252965×
        Ok(Attest { repo, hlc, body })
253967×
    }
254
}
255
256
#[cfg(test)]
257
mod tests {
258
    use super::*;
259
260
    #[test]
2611×
    fn round_trips() {
2621×
        let r = Attest {
2631×
            repo: [1; 16],
2641×
            hlc: Hlc {
2651×
                wall_ms: 3,
2661×
                logical: 0,
2671×
            },
2681×
            body: AttestBody::Ref {
2691×
                name: "main".into(),
2701×
                old_state: ObjectRef([1; 32]),
2711×
                new_state: ObjectRef([2; 32]),
2721×
                serial: 7,
2731×
            },
2741×
        };
2751×
        assert_eq!(Attest::decode(&r.encode()).unwrap(), r);
2761×
        assert_eq!(r.kind(), "ref");
2771×
        let s = Attest::seal(
2781×
            [1; 16],
2791×
            vec![ObjectRef([9; 32]), ObjectRef([3; 32]), ObjectRef([9; 32])],
280
        );
2811×
        let d = Attest::decode(&s.encode()).unwrap();
2821×
        assert!(
2831×
            matches!(&d.body, AttestBody::Seal { hashes } if hashes == &vec![ObjectRef([3; 32]), ObjectRef([9; 32])])
284
        );
2851×
        assert_ne!(s.hash(), r.hash());
2861×
        let t = Attest {
2871×
            repo: [1; 16],
2881×
            hlc: Hlc::default(),
2891×
            body: AttestBody::Tag {
2901×
                name: "v1".into(),
2911×
                state: ObjectRef([5; 32]),
2921×
                message: "release".into(),
2931×
            },
2941×
        };
2951×
        assert_eq!(Attest::decode(&t.encode()).unwrap(), t);
2961×
        assert_eq!(t.kind(), "tag");
2971×
    }
298
299
    #[test]
3001×
    fn rejects_bad_seals() {
3011×
        let empty = Attest {
3021×
            repo: [0; 16],
3031×
            hlc: Hlc::default(),
3041×
            body: AttestBody::Seal { hashes: vec![] },
3051×
        };
3061×
        assert!(Attest::decode(&empty.encode()).is_err());
3071×
        let unsorted = Attest {
3081×
            repo: [0; 16],
3091×
            hlc: Hlc::default(),
3101×
            body: AttestBody::Seal {
3111×
                hashes: vec![ObjectRef([2; 32]), ObjectRef([1; 32])],
3121×
            },
3131×
        };
3141×
        assert!(Attest::decode(&unsorted.encode()).is_err());
3151×
    }
316
}