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. An older signed
8//! release or config may run again: what the ledger holds is trust, not a version floor.
9//!
10//! Each entry is the `(sequence, digest)` of a statement the enforcer can
11//! verify again, so a ledger written by someone without a signing key can
12//! cause refusals, but can't make anything unsigned run.
13
14use alien_error::AlienError;
15use serde::{Deserialize, Serialize};
16
17use crate::error::{ErrorData, Result};
18use crate::release::is_sha256_digest;
19use crate::settings::InstallId;
20use crate::signer_list::{is_fingerprint, SignerChain};
21
22/// One accepted statement.
23#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
24#[serde(rename_all = "camelCase", deny_unknown_fields)]
25pub struct Entry {
26    /// Its sequence, or the version of a signer list.
27    pub sequence: u64,
28    /// `sha256:<hex>` of its payload.
29    pub digest: String,
30}
31
32/// The ledger of one install.
33#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
34#[serde(rename_all = "camelCase", deny_unknown_fields)]
35pub struct Ledger {
36    /// The install's prefix; it must equal where the ledger was found.
37    pub prefix: String,
38    /// Setup writes `true`, so an existing ledger is never read as no ledger.
39    pub created: bool,
40    /// The fingerprint the install first accepted state under.
41    #[serde(default, skip_serializing_if = "Option::is_none")]
42    pub fingerprint: Option<String>,
43    /// The install id the install first accepted state under.
44    #[serde(default, skip_serializing_if = "Option::is_none")]
45    pub install: Option<String>,
46    /// Highest signer list version accepted.
47    #[serde(default, skip_serializing_if = "Option::is_none")]
48    pub signer_list: Option<Entry>,
49}
50
51impl Ledger {
52    /// The ledger setup creates for `prefix`.
53    pub fn new(prefix: &str) -> Self {
54        Self {
55            prefix: prefix.to_string(),
56            created: true,
57            fingerprint: None,
58            install: None,
59            signer_list: None,
60        }
61    }
62
63    /// Parse a ledger found for `prefix`.
64    pub fn parse(bytes: &[u8], prefix: &str) -> Result<Self> {
65        let ledger: Ledger =
66            serde_json::from_slice(bytes).map_err(|error| refused(format!("{error}")))?;
67        if ledger.prefix != prefix {
68            return Err(refused(format!(
69                "the ledger found for '{prefix}' names prefix '{}'",
70                ledger.prefix
71            )));
72        }
73        if !ledger.created {
74            return Err(refused("setup didn't create this ledger"));
75        }
76        if let Some(fingerprint) = &ledger.fingerprint {
77            if !is_fingerprint(fingerprint) {
78                return Err(refused(format!("'{fingerprint}' is not a fingerprint")));
79            }
80        }
81        if let Some(install) = &ledger.install {
82            InstallId::parse(install)?;
83        }
84        for entry in [&ledger.signer_list].into_iter().flatten() {
85            if !is_sha256_digest(&entry.digest) {
86                return Err(refused(format!("'{}' is not a digest", entry.digest)));
87            }
88        }
89        Ok(ledger)
90    }
91
92    /// The JSON form enforcers write back.
93    pub fn to_json(&self) -> String {
94        serde_json::to_string(self).expect("a ledger always serializes")
95    }
96
97    /// Take the higher value of each entry from `other`. Two different
98    /// statements with one sequence, or two trust roots, are a fork and an
99    /// error.
100    pub fn merge(&mut self, other: &Ledger) -> Result<()> {
101        if other.prefix != self.prefix {
102            return Err(refused(format!(
103                "can't merge the ledger of '{}' into '{}'",
104                other.prefix, self.prefix
105            )));
106        }
107        merge_root(&mut self.fingerprint, &other.fingerprint)?;
108        merge_root(&mut self.install, &other.install)?;
109        merge_entry(&mut self.signer_list, &other.signer_list)?;
110        Ok(())
111    }
112
113    /// Refuse a trust root other than the one the install accepted state
114    /// under, or none where it had one. Protection is sticky: removing or
115    /// changing the settings, or moving the install, never makes an enforcer
116    /// run something new.
117    pub fn check_root(&self, fingerprint: Option<&str>, install: &InstallId) -> Result<()> {
118        if let Some(accepted) = &self.fingerprint {
119            if fingerprint != Some(accepted.as_str()) {
120                return Err(AlienError::new(ErrorData::TrustRootChanged {
121                    accepted: format!("fingerprint {accepted}"),
122                    found: fingerprint
123                        .map(|found| format!("fingerprint {found}"))
124                        .unwrap_or_else(|| "no signing settings".to_string()),
125                }));
126            }
127        }
128        let install = install.to_string();
129        if let Some(accepted) = &self.install {
130            if *accepted != install {
131                return Err(AlienError::new(ErrorData::TrustRootChanged {
132                    accepted: format!("install {accepted}"),
133                    found: format!("install {install}"),
134                }));
135            }
136        }
137        Ok(())
138    }
139
140    /// Whether the install ever accepted signed state.
141    pub fn is_sticky(&self) -> bool {
142        self.fingerprint.is_some()
143    }
144
145    /// Record the trust root, after [`Ledger::check_root`] passed.
146    pub fn adopt_root(&mut self, fingerprint: &str, install: &InstallId) {
147        self.fingerprint
148            .get_or_insert_with(|| fingerprint.to_string());
149        self.install.get_or_insert_with(|| install.to_string());
150    }
151
152    /// Refuse a chain that stops below the accepted version or forks from it.
153    pub fn check_chain(&self, chain: &SignerChain) -> Result<()> {
154        let Some(entry) = &self.signer_list else {
155            return Ok(());
156        };
157        let current = chain.current().version;
158        if current < entry.sequence {
159            return Err(AlienError::new(ErrorData::SignerListMissing {
160                needed: entry.sequence,
161                current,
162            }));
163        }
164        if chain.digest_of(entry.sequence) != Some(entry.digest.as_str()) {
165            return Err(refused(format!(
166                "signer list version {} differs from the one this install accepted",
167                entry.sequence
168            )));
169        }
170        Ok(())
171    }
172
173    /// Record the chain's current version.
174    pub fn record_chain(&mut self, chain: &SignerChain) {
175        let current = chain.current();
176        let entry = Entry {
177            sequence: current.version,
178            digest: current.digest.clone(),
179        };
180        if self
181            .signer_list
182            .as_ref()
183            .is_none_or(|held| held.sequence < entry.sequence)
184        {
185            self.signer_list = Some(entry);
186        }
187    }
188}
189
190fn merge_root(held: &mut Option<String>, other: &Option<String>) -> Result<()> {
191    match (held.as_ref(), other) {
192        (Some(mine), Some(theirs)) if mine != theirs => {
193            Err(AlienError::new(ErrorData::TrustRootChanged {
194                accepted: mine.clone(),
195                found: theirs.clone(),
196            }))
197        }
198        (None, Some(theirs)) => {
199            *held = Some(theirs.clone());
200            Ok(())
201        }
202        _ => Ok(()),
203    }
204}
205
206fn merge_entry(held: &mut Option<Entry>, other: &Option<Entry>) -> Result<()> {
207    let Some(theirs) = other else {
208        return Ok(());
209    };
210    match held {
211        Some(mine) if mine.sequence == theirs.sequence && mine.digest != theirs.digest => {
212            Err(refused(format!(
213                "two different signer lists were accepted with sequence {}",
214                mine.sequence
215            )))
216        }
217        Some(mine) if mine.sequence >= theirs.sequence => Ok(()),
218        _ => {
219            *held = Some(theirs.clone());
220            Ok(())
221        }
222    }
223}
224
225fn refused(reason: impl Into<String>) -> AlienError<ErrorData> {
226    AlienError::new(ErrorData::LedgerRefused {
227        reason: reason.into(),
228    })
229}