OXYGENHUB

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

196 of 209 lines run, 23 of 28 functions · run #307 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
}
54
55
#[derive(Clone, Debug, PartialEq, Eq)]
56
pub struct Attest {
57
    /// Repository ID chosen at init.
58
    pub repo: [u8; 16],
59
    pub hlc: Hlc,
60
    pub body: AttestBody,
61
}
62
63
impl Attest {
64521×
    pub fn kind(&self) -> &'static str {
65521×
        match self.body {
66296×
            AttestBody::Ref { .. } => "ref",
67116×
            AttestBody::Seal { .. } => "seal",
6850×
            AttestBody::Tag { .. } => "tag",
6916×
            AttestBody::Rotate { .. } => "rotate",
704×
            AttestBody::Revoke { .. } => "revoke",
7127×
            AttestBody::Receipt { .. } => "receipt",
7212×
            AttestBody::Approval { .. } => "approval",
73
        }
74521×
    }
75
7639×
    pub fn seal(repo: [u8; 16], mut hashes: Vec<ChangeHash>) -> Attest {
7739×
        hashes.sort();
7839×
        hashes.dedup();
7939×
        Attest {
8039×
            repo,
8139×
            hlc: Hlc::now(),
8239×
            body: AttestBody::Seal { hashes },
8339×
        }
8439×
    }
85
86519×
    pub fn to_value(&self) -> Value {
87519×
        let body = match &self.body {
88
            AttestBody::Ref {
89295×
                name,
90295×
                old_state,
91295×
                new_state,
92295×
                serial,
93295×
            } => Value::map([
94295×
                (0, Value::Text(name.clone())),
95295×
                (1, Value::Bytes(old_state.0.to_vec())),
96295×
                (2, Value::Bytes(new_state.0.to_vec())),
97295×
                (3, Value::Uint(*serial)),
98295×
            ]),
99116×
            AttestBody::Seal { hashes } => Value::map([(
100
                0,
101127×
                Value::Array(hashes.iter().map(|h| Value::Bytes(h.0.to_vec())).collect()),
102
            )]),
103
            AttestBody::Tag {
10449×
                name,
10549×
                state,
10649×
                message,
10749×
            } => Value::map([
10849×
                (0, Value::Text(name.clone())),
10949×
                (1, Value::Bytes(state.0.to_vec())),
11049×
                (2, Value::Text(message.clone())),
11149×
            ]),
11216×
            AttestBody::Rotate { new } => Value::map([(0, Value::Bytes(new.0.to_vec()))]),
1134×
            AttestBody::Revoke { key, reason } => Value::map([
1144×
                (0, Value::Bytes(key.0.to_vec())),
1154×
                (1, Value::Text(reason.clone())),
1164×
            ]),
117
            AttestBody::Receipt {
11827×
                receipt,
11927×
                state,
12027×
                run,
12127×
            } => Value::map([
12227×
                (0, Value::Bytes(receipt.0.to_vec())),
12327×
                (1, Value::Bytes(state.0.to_vec())),
12427×
                (2, Value::Text(run.clone())),
12527×
            ]),
126
            AttestBody::Approval {
12712×
                run,
12812×
                job,
12912×
                job_hash,
13012×
                state,
13112×
                inputs,
13212×
                environment,
13312×
                approve,
13412×
            } => Value::map([
13512×
                (0, Value::Text(run.clone())),
13612×
                (1, Value::Text(job.clone())),
13712×
                (2, Value::Bytes(job_hash.0.to_vec())),
13812×
                (3, Value::Bytes(state.0.to_vec())),
139
                (
140
                    4,
14118×
                    Value::Array(inputs.iter().map(|i| Value::Bytes(i.0.to_vec())).collect()),
142
                ),
14312×
                (5, Value::Text(environment.clone())),
14412×
                (6, Value::Uint(u64::from(*approve))),
145
            ]),
146
        };
147519×
        Value::map([
148519×
            (0, Value::Uint(FORMAT_VERSION)),
149519×
            (1, Value::Text(self.kind().into())),
150519×
            (2, Value::Bytes(self.repo.to_vec())),
151519×
            (3, self.hlc.to_value()),
152519×
            (4, body),
153519×
        ])
154519×
    }
155
156519×
    pub fn encode(&self) -> Vec<u8> {
157519×
        cbor::encode(&self.to_value())
158519×
    }
159
160157×
    pub fn hash(&self) -> ObjectRef {
161157×
        hash_object(ObjectType::Attest, &self.encode())
162157×
    }
163
164810×
    pub fn decode(b: &[u8]) -> Result<Attest, ObjectError> {
165810×
        let v = cbor::decode(b)?;
166810×
        let m = map(&v, "attest")?;
167810×
        check_version(m)?;
168810×
        let kind = text(field(m, 1, "kind")?, "kind")?;
169810×
        let repo: [u8; 16] = bytes(field(m, 2, "repo")?, "repo")?
170810×
            .try_into()
171810×
            .map_err(|_| ObjectError::Schema("repo: expected 16 bytes".into()))?;
172810×
        let hlc = Hlc::from_value(field(m, 3, "hlc")?)?;
173810×
        let b = map(field(m, 4, "body")?, "body")?;
174810×
        let body = match kind {
175810×
            "ref" => AttestBody::Ref {
176331×
                name: text(field(b, 0, "name")?, "name")?.to_owned(),
177331×
                old_state: oref(field(b, 1, "old_state")?, "old_state")?,
178331×
                new_state: oref(field(b, 2, "new_state")?, "new_state")?,
179331×
                serial: uint(field(b, 3, "serial")?, "serial")?,
180
            },
181479×
            "seal" => {
182319×
                let hashes = array(field(b, 0, "hashes")?, "hashes")?
183319×
                    .iter()
184355×
                    .map(|h| oref(h, "hash"))
185319×
                    .collect::<Result<Vec<_>, _>>()?;
186319×
                if hashes.is_empty()
187318×
                    || hashes.len() > MAX_SEAL_HASHES
188318×
                    || !hashes.windows(2).all(|w| w[0] < w[1])
189
                {
1902×
                    return Err(ObjectError::Schema(
1912×
                        "seal: hashes must be 1..4096, sorted and unique".into(),
1922×
                    ));
193317×
                }
194317×
                AttestBody::Seal { hashes }
195
            }
196160×
            "tag" => AttestBody::Tag {
197143×
                name: text(field(b, 0, "name")?, "name")?.to_owned(),
198143×
                state: oref(field(b, 1, "state")?, "state")?,
199143×
                message: text(field(b, 2, "message")?, "message")?.to_owned(),
200
            },
20117×
            "rotate" => AttestBody::Rotate {
2020×
                new: oref(field(b, 0, "new")?, "new")?,
203
            },
20417×
            "revoke" => AttestBody::Revoke {
2050×
                key: oref(field(b, 0, "key")?, "key")?,
2060×
                reason: text(field(b, 1, "reason")?, "reason")?.to_owned(),
207
            },
20817×
            "receipt" => AttestBody::Receipt {
20914×
                receipt: oref(field(b, 0, "receipt")?, "receipt")?,
21014×
                state: oref(field(b, 1, "state")?, "state")?,
21114×
                run: text(field(b, 2, "run")?, "run")?.to_owned(),
212
            },
2133×
            "approval" => {
2143×
                let inputs = array(field(b, 4, "inputs")?, "inputs")?
2153×
                    .iter()
2164×
                    .map(|h| oref(h, "input"))
2173×
                    .collect::<Result<Vec<_>, _>>()?;
2183×
                if !inputs.windows(2).all(|w| w[0] < w[1]) {
2190×
                    return Err(ObjectError::Schema(
2200×
                        "approval: inputs must be sorted and unique".into(),
2210×
                    ));
2223×
                }
223
                AttestBody::Approval {
2243×
                    run: text(field(b, 0, "run")?, "run")?.to_owned(),
2253×
                    job: text(field(b, 1, "job")?, "job")?.to_owned(),
2263×
                    job_hash: oref(field(b, 2, "job_hash")?, "job_hash")?,
2273×
                    state: oref(field(b, 3, "state")?, "state")?,
2283×
                    inputs,
2293×
                    environment: text(field(b, 5, "environment")?, "environment")?.to_owned(),
2303×
                    approve: match uint(field(b, 6, "approve")?, "approve")? {
2310×
                        0 => false,
2323×
                        1 => true,
2330×
                        _ => return Err(ObjectError::Schema("approval: approve is 0 or 1".into())),
234
                    },
235
                }
236
            }
2370×
            other => {
2380×
                return Err(ObjectError::Schema(format!(
2390×
                    "unknown attestation kind {other:?}"
2400×
                )))
241
            }
242
        };
243808×
        Ok(Attest { repo, hlc, body })
244810×
    }
245
}
246
247
#[cfg(test)]
248
mod tests {
249
    use super::*;
250
251
    #[test]
2521×
    fn round_trips() {
2531×
        let r = Attest {
2541×
            repo: [1; 16],
2551×
            hlc: Hlc {
2561×
                wall_ms: 3,
2571×
                logical: 0,
2581×
            },
2591×
            body: AttestBody::Ref {
2601×
                name: "main".into(),
2611×
                old_state: ObjectRef([1; 32]),
2621×
                new_state: ObjectRef([2; 32]),
2631×
                serial: 7,
2641×
            },
2651×
        };
2661×
        assert_eq!(Attest::decode(&r.encode()).unwrap(), r);
2671×
        assert_eq!(r.kind(), "ref");
2681×
        let s = Attest::seal(
2691×
            [1; 16],
2701×
            vec![ObjectRef([9; 32]), ObjectRef([3; 32]), ObjectRef([9; 32])],
271
        );
2721×
        let d = Attest::decode(&s.encode()).unwrap();
2731×
        assert!(
2741×
            matches!(&d.body, AttestBody::Seal { hashes } if hashes == &vec![ObjectRef([3; 32]), ObjectRef([9; 32])])
275
        );
2761×
        assert_ne!(s.hash(), r.hash());
2771×
        let t = Attest {
2781×
            repo: [1; 16],
2791×
            hlc: Hlc::default(),
2801×
            body: AttestBody::Tag {
2811×
                name: "v1".into(),
2821×
                state: ObjectRef([5; 32]),
2831×
                message: "release".into(),
2841×
            },
2851×
        };
2861×
        assert_eq!(Attest::decode(&t.encode()).unwrap(), t);
2871×
        assert_eq!(t.kind(), "tag");
2881×
    }
289
290
    #[test]
2911×
    fn rejects_bad_seals() {
2921×
        let empty = Attest {
2931×
            repo: [0; 16],
2941×
            hlc: Hlc::default(),
2951×
            body: AttestBody::Seal { hashes: vec![] },
2961×
        };
2971×
        assert!(Attest::decode(&empty.encode()).is_err());
2981×
        let unsorted = Attest {
2991×
            repo: [0; 16],
3001×
            hlc: Hlc::default(),
3011×
            body: AttestBody::Seal {
3021×
                hashes: vec![ObjectRef([2; 32]), ObjectRef([1; 32])],
3031×
            },
3041×
        };
3051×
        assert!(Attest::decode(&unsorted.encode()).is_err());
3061×
    }
307
}