OXYGENHUB
◆ show-stat oxygen / crates / oxy-core / src / repo / receipts.rs
7.0 KiB · Rust · last changed The issuer countersigns when it accepted a certified update (keyless step 4c) 19 days ago source blame history raw
fc1a466a Andy McCall ↶ 1
//! Execution receipts in a repository (spec §14.6): kept beside the state
2
//! they were made on, with the runner's identity and signature.
3
4
use super::*;
5
use crate::receipt::SignedReceipt;
6
7
/// A stored receipt and what verifying it found.
8
#[derive(Clone, Debug)]
9
pub struct ReceiptInfo {
10
    /// The receipt attestation's ObjectRef, which names it.
11
    pub attest: ObjectRef,
12
    pub signed: SignedReceipt,
13
    /// Why it does not verify, if it does not.
14
    pub problem: Option<String>,
15
    /// The runner's key was revoked (spec §14.2).
16
    pub revoked: bool,
17
}
18
19
impl Repo {
20
    /// Verify `sr` and keep it: the receipt, the attestation with its
21
    /// signatures, and the runner's identity. Returns the attestation's
22
    /// ObjectRef. Receipts for another repository are refused.
23
    pub fn add_receipt(&self, sr: &SignedReceipt) -> Result<ObjectRef> {
24
        sr.verify()
25
            .map_err(|e| RepoError::Msg(format!("receipt does not verify: {e}")))?;
26
        if sr.attest.repo != self.id()? {
27
            return fail("that receipt is for another repository");
28
        }
29
        self.store.put_identity(&sr.runner)?;
c63fed2e Andy McCall ↶ 30
        if let Some(c) = &sr.certificate {
31
            self.store.put_identity(&c.issuer)?;
32
            self.store.put_certificate(&c.cert)?;
33
        }
fc1a466a Andy McCall ↶ 34
        self.store.put_receipt(&sr.receipt)?;
35
        let r = self.store.put_attest(&sr.attest)?;
36
        for sig in &sr.sigs {
37
            self.store.put_signature(&r, sig)?;
38
        }
39
        self.store.index_receipt(&sr.state(), &r)?;
40
        Ok(r)
41
    }
42
43
    /// The receipt named by attestation `r`, verified again from the store.
44
    pub fn receipt(&self, r: &ObjectRef) -> Result<ReceiptInfo> {
45
        let attest = self.store.get_attest(r)?;
46
        let AttestBody::Receipt { receipt, .. } = &attest.body else {
47
            return fail(format!("#{} is not a receipt", r.short(12)));
48
        };
49
        let receipt = self.store.get_receipt(receipt)?;
50
        let sigs = self.store.signatures(r)?;
51
        let Some(key) = sigs.first().map(|s| s.key) else {
52
            return fail(format!("receipt #{} has no signature", r.short(12)));
53
        };
54
        let runner = self.store.get_identity(&key)?;
c63fed2e Andy McCall ↶ 55
        // Signed by a short-lived key: its certificate and issuer too.
56
        let certificate = match self.store.certificate_of(&key)? {
57
            Some(c) => {
58
                let cert = self.store.get_certificate(&c)?;
59
                let issuer = self.store.get_identity(&cert.cert.issuer)?;
60
                Some(crate::receipt::CertifiedBy { cert, issuer })
61
            }
62
            None => None,
63
        };
fc1a466a Andy McCall ↶ 64
        let signed = SignedReceipt {
65
            receipt,
66
            attest,
67
            sigs,
68
            runner,
c63fed2e Andy McCall ↶ 69
            certificate,
fc1a466a Andy McCall ↶ 70
        };
71
        let problem = signed.verify().err().map(|e| e.to_string());
72
        Ok(ReceiptInfo {
73
            attest: *r,
74
            revoked: self.is_revoked(&key)?,
75
            signed,
76
            problem,
77
        })
78
    }
79
80
    /// Every receipt kept for the state of `heads`, oldest first.
81
    pub fn receipts(&self, heads: &[ChangeHash]) -> Result<Vec<ReceiptInfo>> {
82
        let state = hash_object(
83
            ObjectType::State,
84
            &StateObject::new(heads.to_vec()).encode(),
85
        );
86
        let mut out = self
87
            .store
88
            .receipts_for(&state)?
89
            .iter()
90
            .map(|r| self.receipt(r))
91
            .collect::<Result<Vec<_>>>()?;
92
        out.sort_by_key(|i| i.signed.attest.hlc);
93
        Ok(out)
94
    }
95
96
    /// Receipts to keep through garbage collection: those whose state's
97
    /// heads `keep` holds, with their receipts, runners and outputs.
3a4b3e01 Andy McCall ↶ 98
    /// Keep a signed approval (oxygenhub#235): verified, for this repository,
99
    /// with the signer's identity and indexed by the state it approves, so
100
    /// garbage collection keeps it while that state lives. Who may approve is
101
    /// the caller's rule.
102
    pub fn add_approval(&self, sa: &crate::approval::SignedApproval) -> Result<ObjectRef> {
103
        sa.verify()
104
            .map_err(|e| RepoError::Msg(format!("approval does not verify: {e}")))?;
105
        if sa.attest.repo != self.id()? {
106
            return fail("that approval is for another repository");
107
        }
108
        let state = sa
109
            .statement()
110
            .map_err(|e| RepoError::Msg(e.to_string()))?
111
            .state;
112
        self.store.put_identity(&sa.signer)?;
113
        let r = self.store.put_attest(&sa.attest)?;
114
        for sig in &sa.sigs {
115
            self.store.put_signature(&r, sig)?;
116
        }
117
        self.store.index_approval(&state, &r)?;
118
        Ok(r)
119
    }
120
121
    /// Approvals of states garbage collection keeps are kept, with their
122
    /// signatures and signers.
123
    pub(crate) fn reachable_approvals(&self, keep: &mut HashSet<ObjectRef>) -> Result<()> {
124
        for state in self.store.approval_states()? {
125
            if !keep.contains(&state) {
126
                let heads = match self.store.get_state(&state) {
127
                    Ok(s) => s.heads,
128
                    Err(StoreError::NotFound(_)) => vec![],
129
                    Err(e) => return Err(e.into()),
130
                };
131
                if !heads.iter().all(|h| keep.contains(h)) {
132
                    continue;
133
                }
134
                keep.insert(state);
135
            }
136
            for a in self.store.approvals_for(&state)? {
137
                keep.insert(a);
138
                for sig in self.store.signatures(&a)? {
139
                    keep.insert(sig.key);
140
                }
141
            }
142
        }
143
        Ok(())
144
    }
145
fc1a466a Andy McCall ↶ 146
    pub(crate) fn reachable_receipts(&self, keep: &mut HashSet<ObjectRef>) -> Result<()> {
147
        for state in self.store.receipt_states()? {
148
            let heads = match self.store.get_state(&state) {
149
                Ok(s) => s.heads,
150
                // A receipt may arrive before its state object; its heads
151
                // are unknown, so keep it.
152
                Err(StoreError::NotFound(_)) => vec![],
153
                Err(e) => return Err(e.into()),
154
            };
155
            if !heads.iter().all(|h| keep.contains(h)) {
156
                continue;
157
            }
158
            keep.insert(state);
159
            for a in self.store.receipts_for(&state)? {
160
                keep.insert(a);
161
                for sig in self.store.signatures(&a)? {
f53cbe7a Andy McCall ↶ 162
                    self.keep_signer(keep, sig.key)?;
fc1a466a Andy McCall ↶ 163
                }
164
                let Ok(attest) = self.store.get_attest(&a) else {
165
                    continue;
166
                };
167
                let AttestBody::Receipt { receipt, .. } = attest.body else {
168
                    continue;
169
                };
170
                keep.insert(receipt);
171
                let Ok(r) = self.store.get_receipt(&receipt) else {
172
                    continue;
173
                };
174
                for b in r.outputs.iter().chain(&r.inputs) {
175
                    if keep.insert(*b) {
176
                        if let Ok(bytes) = self.store.get_typed(b, ObjectType::Blob) {
177
                            keep.extend(Blob::decode(&bytes)?.chunks);
178
                        }
179
                    }
180
                }
181
            }
182
        }
183
        Ok(())
184
    }
185
}