OXYGENHUB
# b2ef93bb2366 oxygen / crates / oxy-core / src / attest.rs
5.7 KiB · Rust · last changed Tags: immutable named states with tag attestations, in views and on the wire, policy-governed, exported to Git (spec 0.6h) 1 month ago source blame history raw
1
//! Attestations (spec §14.4): signed statements about references and batches
2
//! of changes. Only the `ref` and `seal` kinds exist so far.
3
4
use crate::cbor::{self, Value};
5
use crate::hash::{hash_object, ChangeHash, ObjectRef, ObjectType};
6
use crate::objects::{array, bytes, check_version, field, map, oref, text, uint, Hlc, ObjectError, FORMAT_VERSION};
7
8
pub const MAX_SEAL_HASHES: usize = 4096;
9
10
#[derive(Clone, Debug, PartialEq, Eq)]
11
pub enum AttestBody {
12
    /// A bookmark moved from `old_state` to `new_state` (spec §10.2).
13
    Ref { name: String, old_state: ObjectRef, new_state: ObjectRef, serial: u64 },
14
    /// One signature covering a batch of changes (spec §14.4).
15
    Seal { hashes: Vec<ChangeHash> },
16
    /// An immutable named state (spec §10.1).
17
    Tag { name: String, state: ObjectRef, message: String },
18
}
19
20
#[derive(Clone, Debug, PartialEq, Eq)]
21
pub struct Attest {
22
    /// Repository ID chosen at init.
23
    pub repo: [u8; 16],
24
    pub hlc: Hlc,
25
    pub body: AttestBody,
26
}
27
28
impl Attest {
29
    pub fn kind(&self) -> &'static str {
30
        match self.body {
31
            AttestBody::Ref { .. } => "ref",
32
            AttestBody::Seal { .. } => "seal",
33
            AttestBody::Tag { .. } => "tag",
34
        }
35
    }
36
37
    pub fn seal(repo: [u8; 16], mut hashes: Vec<ChangeHash>) -> Attest {
38
        hashes.sort();
39
        hashes.dedup();
40
        Attest { repo, hlc: Hlc::now(), body: AttestBody::Seal { hashes } }
41
    }
42
43
    pub fn to_value(&self) -> Value {
44
        let body = match &self.body {
45
            AttestBody::Ref { name, old_state, new_state, serial } => Value::map([
46
                (0, Value::Text(name.clone())),
47
                (1, Value::Bytes(old_state.0.to_vec())),
48
                (2, Value::Bytes(new_state.0.to_vec())),
49
                (3, Value::Uint(*serial)),
50
            ]),
51
            AttestBody::Seal { hashes } => {
52
                Value::map([(0, Value::Array(hashes.iter().map(|h| Value::Bytes(h.0.to_vec())).collect()))])
53
            }
54
            AttestBody::Tag { name, state, message } => {
55
                Value::map([(0, Value::Text(name.clone())), (1, Value::Bytes(state.0.to_vec())), (2, Value::Text(message.clone()))])
56
            }
57
        };
58
        Value::map([
59
            (0, Value::Uint(FORMAT_VERSION)),
60
            (1, Value::Text(self.kind().into())),
61
            (2, Value::Bytes(self.repo.to_vec())),
62
            (3, self.hlc.to_value()),
63
            (4, body),
64
        ])
65
    }
66
67
    pub fn encode(&self) -> Vec<u8> {
68
        cbor::encode(&self.to_value())
69
    }
70
71
    pub fn hash(&self) -> ObjectRef {
72
        hash_object(ObjectType::Attest, &self.encode())
73
    }
74
75
    pub fn decode(b: &[u8]) -> Result<Attest, ObjectError> {
76
        let v = cbor::decode(b)?;
77
        let m = map(&v, "attest")?;
78
        check_version(m)?;
79
        let kind = text(field(m, 1, "kind")?, "kind")?;
80
        let repo: [u8; 16] = bytes(field(m, 2, "repo")?, "repo")?
81
            .try_into()
82
            .map_err(|_| ObjectError::Schema("repo: expected 16 bytes".into()))?;
83
        let hlc = Hlc::from_value(field(m, 3, "hlc")?)?;
84
        let b = map(field(m, 4, "body")?, "body")?;
85
        let body = match kind {
86
            "ref" => AttestBody::Ref {
87
                name: text(field(b, 0, "name")?, "name")?.to_owned(),
88
                old_state: oref(field(b, 1, "old_state")?, "old_state")?,
89
                new_state: oref(field(b, 2, "new_state")?, "new_state")?,
90
                serial: uint(field(b, 3, "serial")?, "serial")?,
91
            },
92
            "seal" => {
93
                let hashes = array(field(b, 0, "hashes")?, "hashes")?.iter().map(|h| oref(h, "hash")).collect::<Result<Vec<_>, _>>()?;
94
                if hashes.is_empty() || hashes.len() > MAX_SEAL_HASHES || !hashes.windows(2).all(|w| w[0] < w[1]) {
95
                    return Err(ObjectError::Schema("seal: hashes must be 1..4096, sorted and unique".into()));
96
                }
97
                AttestBody::Seal { hashes }
98
            }
99
            "tag" => AttestBody::Tag {
100
                name: text(field(b, 0, "name")?, "name")?.to_owned(),
101
                state: oref(field(b, 1, "state")?, "state")?,
102
                message: text(field(b, 2, "message")?, "message")?.to_owned(),
103
            },
104
            other => return Err(ObjectError::Schema(format!("unknown attestation kind {other:?}"))),
105
        };
106
        Ok(Attest { repo, hlc, body })
107
    }
108
}
109
110
#[cfg(test)]
111
mod tests {
112
    use super::*;
113
114
    #[test]
115
    fn round_trips() {
116
        let r = Attest {
117
            repo: [1; 16],
118
            hlc: Hlc { wall_ms: 3, logical: 0 },
119
            body: AttestBody::Ref { name: "main".into(), old_state: ObjectRef([1; 32]), new_state: ObjectRef([2; 32]), serial: 7 },
120
        };
121
        assert_eq!(Attest::decode(&r.encode()).unwrap(), r);
122
        assert_eq!(r.kind(), "ref");
123
        let s = Attest::seal([1; 16], vec![ObjectRef([9; 32]), ObjectRef([3; 32]), ObjectRef([9; 32])]);
124
        let d = Attest::decode(&s.encode()).unwrap();
125
        assert!(matches!(&d.body, AttestBody::Seal { hashes } if hashes == &vec![ObjectRef([3; 32]), ObjectRef([9; 32])]));
126
        assert_ne!(s.hash(), r.hash());
127
        let t = Attest { repo: [1; 16], hlc: Hlc::default(), body: AttestBody::Tag { name: "v1".into(), state: ObjectRef([5; 32]), message: "release".into() } };
128
        assert_eq!(Attest::decode(&t.encode()).unwrap(), t);
129
        assert_eq!(t.kind(), "tag");
130
    }
131
132
    #[test]
133
    fn rejects_bad_seals() {
134
        let empty = Attest { repo: [0; 16], hlc: Hlc::default(), body: AttestBody::Seal { hashes: vec![] } };
135
        assert!(Attest::decode(&empty.encode()).is_err());
136
        let unsorted = Attest { repo: [0; 16], hlc: Hlc::default(), body: AttestBody::Seal { hashes: vec![ObjectRef([2; 32]), ObjectRef([1; 32])] } };
137
        assert!(Attest::decode(&unsorted.encode()).is_err());
138
    }
139
}