Skip to main content

alien_signing/
ledger.rs

1//! What an install has already accepted.
2//!
3//! Every enforcer of an install keeps the same small record: the trust root
4//! it accepted state under and the highest signer list version. Setup creates the install's copy in the
5//! customer's cloud non-empty, so a missing ledger is an error and never a
6//! fresh start. Enforcers load it at start, take the maximum of it and their
7//! own copy, and write the result back. Values only rise.
8//!
9//! The ledger is a trust anchor and a version floor, not a permission. What
10//! keeps a release or config running after its signer leaves the list is the
11//! signer list's `keep`, which the admins sign; the ledger never makes a
12//! statement verify. Only enforcers write it; management has no access to it
13//! (it is denied `/signed/*`).
14//!
15//! The ledger has to fit the smallest store an install uses (AWS SSM
16//! Standard parameters hold 4 KB), so it is size-capped: it holds a fixed
17//! set of small fields, and one that would pass [`MAX_LEDGER_BYTES`] is
18//! refused.
19
20use alien_error::AlienError;
21use serde::{Deserialize, Serialize};
22
23use crate::error::{ErrorData, Result};
24use crate::release::is_sha256_digest;
25use crate::settings::InstallId;
26use crate::signer_list::{is_fingerprint, SignerChain};
27
28/// One accepted statement.
29#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
30#[serde(rename_all = "camelCase", deny_unknown_fields)]
31pub struct Entry {
32    /// Its sequence, or the version of a signer list.
33    pub sequence: u64,
34    /// `sha256:<hex>` of its payload.
35    pub digest: String,
36}
37
38/// The most bytes a ledger's JSON may take: AWS SSM Standard's parameter limit,
39/// the smallest store an install keeps its ledger in.
40pub const MAX_LEDGER_BYTES: usize = 4096;
41
42/// The ledger of one install.
43#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
44#[serde(rename_all = "camelCase", deny_unknown_fields)]
45pub struct Ledger {
46    /// The install's prefix; it must equal where the ledger was found.
47    pub prefix: String,
48    /// Setup writes `true`, so an existing ledger is never read as no ledger.
49    pub created: bool,
50    /// The fingerprint the install first accepted state under.
51    #[serde(default, skip_serializing_if = "Option::is_none")]
52    pub fingerprint: Option<String>,
53    /// The install id the install first accepted state under.
54    #[serde(default, skip_serializing_if = "Option::is_none")]
55    pub install: Option<String>,
56    /// Highest signer list version accepted.
57    #[serde(default, skip_serializing_if = "Option::is_none")]
58    pub signer_list: Option<Entry>,
59}
60
61impl Ledger {
62    /// The ledger setup creates for `prefix`.
63    pub fn new(prefix: &str) -> Self {
64        Self {
65            prefix: prefix.to_string(),
66            created: true,
67            fingerprint: None,
68            install: None,
69            signer_list: None,
70        }
71    }
72
73    /// Parse a ledger found for `prefix`.
74    pub fn parse(bytes: &[u8], prefix: &str) -> Result<Self> {
75        let ledger: Ledger =
76            serde_json::from_slice(bytes).map_err(|error| refused(format!("{error}")))?;
77        if ledger.prefix != prefix {
78            return Err(refused(format!(
79                "the ledger found for '{prefix}' names prefix '{}'",
80                ledger.prefix
81            )));
82        }
83        if !ledger.created {
84            return Err(refused("setup didn't create this ledger"));
85        }
86        if let Some(fingerprint) = &ledger.fingerprint {
87            if !is_fingerprint(fingerprint) {
88                return Err(refused(format!("'{fingerprint}' is not a fingerprint")));
89            }
90        }
91        if let Some(install) = &ledger.install {
92            InstallId::parse(install)?;
93        }
94        for entry in [&ledger.signer_list].into_iter().flatten() {
95            if !is_sha256_digest(&entry.digest) {
96                return Err(refused(format!("'{}' is not a digest", entry.digest)));
97            }
98        }
99        if bytes.len() > MAX_LEDGER_BYTES {
100            return Err(refused(format!(
101                "it is {} bytes, over the {MAX_LEDGER_BYTES} its store holds",
102                bytes.len()
103            )));
104        }
105        Ok(ledger)
106    }
107
108    /// The JSON form enforcers write back.
109    pub fn to_json(&self) -> String {
110        serde_json::to_string(self).expect("a ledger always serializes")
111    }
112
113    /// Take the higher value of each entry from `other`. Two different
114    /// statements with one sequence, or two trust roots, are a fork and an
115    /// error.
116    pub fn merge(&mut self, other: &Ledger) -> Result<()> {
117        if other.prefix != self.prefix {
118            return Err(refused(format!(
119                "can't merge the ledger of '{}' into '{}'",
120                other.prefix, self.prefix
121            )));
122        }
123        merge_root(&mut self.fingerprint, &other.fingerprint)?;
124        merge_root(&mut self.install, &other.install)?;
125        merge_entry(&mut self.signer_list, &other.signer_list)?;
126        self.check_size()
127    }
128
129    /// Refuse a trust root other than the one the install accepted state
130    /// under, or none where it had one. Protection is sticky: removing or
131    /// changing the settings, or moving the install, never makes an enforcer
132    /// run something new.
133    pub fn check_root(&self, fingerprint: Option<&str>, install: &InstallId) -> Result<()> {
134        if let Some(accepted) = &self.fingerprint {
135            if fingerprint != Some(accepted.as_str()) {
136                return Err(AlienError::new(ErrorData::TrustRootChanged {
137                    accepted: format!("fingerprint {accepted}"),
138                    found: fingerprint
139                        .map(|found| format!("fingerprint {found}"))
140                        .unwrap_or_else(|| "no signing settings".to_string()),
141                }));
142            }
143        }
144        let install = install.to_string();
145        if let Some(accepted) = &self.install {
146            if *accepted != install {
147                return Err(AlienError::new(ErrorData::TrustRootChanged {
148                    accepted: format!("install {accepted}"),
149                    found: format!("install {install}"),
150                }));
151            }
152        }
153        Ok(())
154    }
155
156    fn json_len(&self) -> usize {
157        self.to_json().len()
158    }
159
160    /// Refuse a ledger that doesn't fit its store.
161    pub fn check_size(&self) -> Result<()> {
162        let len = self.json_len();
163        if len > MAX_LEDGER_BYTES {
164            return Err(refused(format!(
165                "it would take {len} bytes, over the {MAX_LEDGER_BYTES} its store holds"
166            )));
167        }
168        Ok(())
169    }
170
171    /// Whether the install ever accepted signed state.
172    pub fn is_sticky(&self) -> bool {
173        self.fingerprint.is_some()
174    }
175
176    /// Record the trust root, after [`Ledger::check_root`] passed.
177    pub fn adopt_root(&mut self, fingerprint: &str, install: &InstallId) {
178        self.fingerprint
179            .get_or_insert_with(|| fingerprint.to_string());
180        self.install.get_or_insert_with(|| install.to_string());
181    }
182
183    /// Refuse a chain that stops below the accepted version or forks from it.
184    pub fn check_chain(&self, chain: &SignerChain) -> Result<()> {
185        let Some(entry) = &self.signer_list else {
186            return Ok(());
187        };
188        let current = chain.current().version;
189        if current < entry.sequence {
190            return Err(AlienError::new(ErrorData::SignerListMissing {
191                needed: entry.sequence,
192                current,
193            }));
194        }
195        if chain.digest_of(entry.sequence) != Some(entry.digest.as_str()) {
196            return Err(refused(format!(
197                "signer list version {} differs from the one this install accepted",
198                entry.sequence
199            )));
200        }
201        Ok(())
202    }
203
204    /// Record the chain's current version.
205    pub fn record_chain(&mut self, chain: &SignerChain) {
206        let current = chain.current();
207        let entry = Entry {
208            sequence: current.version,
209            digest: current.digest.clone(),
210        };
211        if self
212            .signer_list
213            .as_ref()
214            .is_none_or(|held| held.sequence < entry.sequence)
215        {
216            self.signer_list = Some(entry);
217        }
218    }
219}
220
221fn merge_root(held: &mut Option<String>, other: &Option<String>) -> Result<()> {
222    match (held.as_ref(), other) {
223        (Some(mine), Some(theirs)) if mine != theirs => {
224            Err(AlienError::new(ErrorData::TrustRootChanged {
225                accepted: mine.clone(),
226                found: theirs.clone(),
227            }))
228        }
229        (None, Some(theirs)) => {
230            *held = Some(theirs.clone());
231            Ok(())
232        }
233        _ => Ok(()),
234    }
235}
236
237fn merge_entry(held: &mut Option<Entry>, other: &Option<Entry>) -> Result<()> {
238    let Some(theirs) = other else {
239        return Ok(());
240    };
241    match held {
242        Some(mine) if mine.sequence == theirs.sequence && mine.digest != theirs.digest => {
243            Err(refused(format!(
244                "two different signer lists were accepted with sequence {}",
245                mine.sequence
246            )))
247        }
248        Some(mine) if mine.sequence >= theirs.sequence => Ok(()),
249        _ => {
250            *held = Some(theirs.clone());
251            Ok(())
252        }
253    }
254}
255
256fn refused(reason: impl Into<String>) -> AlienError<ErrorData> {
257    AlienError::new(ErrorData::LedgerRefused {
258        reason: reason.into(),
259    })
260}
261
262#[cfg(test)]
263mod tests {
264    use super::*;
265
266    fn digest(n: usize) -> String {
267        format!("sha256:{n:064x}")
268    }
269
270    /// A fully populated ledger, as the largest root fields make it.
271    fn full_root() -> Ledger {
272        let mut ledger = Ledger::new(&"p".repeat(40));
273        ledger.fingerprint = Some(format!("SHA256:{}", "a".repeat(64)));
274        ledger.install = Some("aws:111122223333:us-east-1:acme-prod".to_string());
275        ledger.signer_list = Some(Entry {
276            sequence: u64::MAX,
277            digest: digest(7),
278        });
279        ledger
280    }
281
282    #[test]
283    fn a_full_ledger_fits_its_store() {
284        let ledger = full_root();
285        assert!(ledger.to_json().len() <= MAX_LEDGER_BYTES);
286        ledger.check_size().unwrap();
287        Ledger::parse(ledger.to_json().as_bytes(), &"p".repeat(40)).unwrap();
288    }
289
290    #[test]
291    fn a_stored_ledger_over_the_cap_is_refused() {
292        // Every field is valid; only the prefix makes it too big.
293        let prefix = "p".repeat(MAX_LEDGER_BYTES);
294        let mut ledger = full_root();
295        ledger.prefix = prefix.clone();
296        let text = ledger.to_json();
297        assert!(text.len() > MAX_LEDGER_BYTES);
298        let error = Ledger::parse(text.as_bytes(), &prefix).unwrap_err();
299        assert!(format!("{error}").contains("bytes"), "{error}");
300    }
301}