Skip to main content

alien_signing/
verify.rs

1//! The checks every enforcer runs on every statement.
2
3use std::collections::BTreeSet;
4
5use alien_error::AlienError;
6use chrono::{DateTime, Utc};
7use serde::de::DeserializeOwned;
8
9use crate::config::ConfigBody;
10use crate::envelope::{Kind, Opened, SignedStatement};
11use crate::error::{ErrorData, Result};
12use crate::ledger::Ledger;
13use crate::release::ReleaseBody;
14use crate::settings::{InstallId, SigningSettings};
15use crate::signer_list::SignerChain;
16
17/// A statement that passed every check, with its body parsed.
18#[derive(Debug, Clone)]
19pub struct Verified<B> {
20    /// Kind.
21    pub kind: Kind,
22    /// Sequence.
23    pub sequence: u64,
24    /// `sha256:<hex>` of the payload.
25    pub digest: String,
26    /// Expiry.
27    pub not_after: Option<DateTime<Utc>>,
28    /// Whether the current signer list keeps this statement (`keep`), so no
29    /// signature was needed: its signer may have left the list.
30    pub kept: bool,
31    /// Signer ids whose signatures counted; none for a kept statement.
32    pub signers: BTreeSet<String>,
33    /// The body.
34    pub body: B,
35}
36
37/// What an enforcer trusts: the settings setup wrote, the install id it
38/// derived itself, and the signer chain that grows from the fingerprint.
39#[derive(Debug, Clone)]
40pub struct Trust {
41    settings: SigningSettings,
42    install: InstallId,
43    chain: SignerChain,
44}
45
46impl Trust {
47    /// Trust `chain`, which must start at the settings' fingerprint and reach
48    /// at least the signer list version `ledger` holds.
49    pub fn new(
50        settings: SigningSettings,
51        install: InstallId,
52        chain: &[SignedStatement],
53        ledger: &Ledger,
54    ) -> Result<Self> {
55        settings.validate()?;
56        install.validate()?;
57        ledger.check_root(Some(&settings.fingerprint), &install)?;
58        let chain = SignerChain::from_statements(&settings.fingerprint, chain)?;
59        ledger.check_chain(&chain)?;
60        Ok(Self {
61            settings,
62            install,
63            chain,
64        })
65    }
66
67    /// The settings.
68    pub fn settings(&self) -> &SigningSettings {
69        &self.settings
70    }
71
72    /// This install.
73    pub fn install(&self) -> &InstallId {
74        &self.install
75    }
76
77    /// The project, as signer list version 1 names it.
78    pub fn project(&self) -> &str {
79        self.chain.project()
80    }
81
82    /// The signer chain.
83    pub fn chain(&self) -> &SignerChain {
84        &self.chain
85    }
86
87    /// Accept newer signer list versions. Returns whether the chain grew.
88    pub fn extend_chain(&mut self, statements: &[SignedStatement]) -> Result<bool> {
89        self.chain.extend(statements)
90    }
91
92    /// Record this trust in `ledger`: the trust root and the chain's version.
93    pub fn record(&self, ledger: &mut Ledger) -> Result<()> {
94        ledger.check_root(Some(&self.settings.fingerprint), &self.install)?;
95        ledger.check_chain(&self.chain)?;
96        ledger.adopt_root(&self.settings.fingerprint, &self.install);
97        ledger.record_chain(&self.chain);
98        ledger.check_size()
99    }
100
101    /// Run the checks for a statement of `kind` and parse its body: project
102    /// and install, the statement's own expiry, the deny-list and signatures
103    /// by keys that hold the kind's role.
104    ///
105    /// Signatures are checked against the current signer list. A statement
106    /// signed by a key that has left the list is accepted only when the
107    /// current list's `keep` names its digest, kind and sequence: the admins
108    /// signed that entry with the list, so the ledger and the install's
109    /// history play no part, and a new machine or Operator instance accepts
110    /// it the same way. The deny-list refuses a statement first. Every
111    /// enforcer applies this one rule.
112    pub fn verify<B: DeserializeOwned>(
113        &self,
114        statement: &SignedStatement,
115        kind: Kind,
116        now: DateTime<Utc>,
117    ) -> Result<Verified<B>> {
118        if kind == Kind::SignerList {
119            return Err(AlienError::new(ErrorData::WrongKind {
120                expected: "a statement the signer list signs".to_string(),
121                actual: kind.as_str().to_string(),
122            }));
123        }
124        let opened = statement.open()?;
125        self.check_header(&opened, kind, now)?;
126        let current = self.chain.current();
127        if opened.signer_list_version > current.version {
128            return Err(AlienError::new(ErrorData::SignerListMissing {
129                needed: opened.signer_list_version,
130                current: current.version,
131            }));
132        }
133        if current.refuses(&opened) {
134            return Err(AlienError::new(ErrorData::Denied {
135                digest: opened.digest,
136            }));
137        }
138        if current.keeps(&opened) {
139            return finish(opened, BTreeSet::new(), true);
140        }
141        let signers = current.check_signatures(&opened, kind.role())?;
142        finish(opened, signers, false)
143    }
144
145    /// Verify a release for this install's channel and check its rules.
146    pub fn verify_release(
147        &self,
148        statement: &SignedStatement,
149        now: DateTime<Utc>,
150    ) -> Result<Verified<ReleaseBody>> {
151        let verified: Verified<ReleaseBody> = self.verify(statement, Kind::Release, now)?;
152        if verified.body.channel != self.settings.channel {
153            return Err(AlienError::new(ErrorData::WrongChannel {
154                expected: self.settings.channel.clone(),
155                actual: verified.body.channel.clone(),
156            }));
157        }
158        verified.body.validate()?;
159        Ok(verified)
160    }
161
162    /// Verify a config statement for this install against the release it
163    /// configures.
164    pub fn verify_config(
165        &self,
166        statement: &SignedStatement,
167        release: &ReleaseBody,
168        now: DateTime<Utc>,
169    ) -> Result<Verified<ConfigBody>> {
170        let verified: Verified<ConfigBody> = self.verify(statement, Kind::Config, now)?;
171        verified.body.check(release)?;
172        Ok(verified)
173    }
174
175    fn check_header(&self, opened: &Opened, kind: Kind, now: DateTime<Utc>) -> Result<()> {
176        if opened.kind != kind {
177            return Err(AlienError::new(ErrorData::WrongKind {
178                expected: kind.as_str().to_string(),
179                actual: opened.kind.as_str().to_string(),
180            }));
181        }
182        if opened.project != self.chain.project() {
183            return Err(AlienError::new(ErrorData::WrongProject {
184                expected: self.chain.project().to_string(),
185                actual: opened.project.clone(),
186            }));
187        }
188        let install = self.install.to_string();
189        let expected_install = kind.is_install_bound().then_some(install.as_str());
190        if opened.install.as_deref() != expected_install {
191            return Err(AlienError::new(ErrorData::WrongInstall {
192                expected: expected_install.unwrap_or("none").to_string(),
193                actual: opened.install.clone().unwrap_or_else(|| "none".to_string()),
194            }));
195        }
196        match opened.not_after {
197            Some(not_after) if now > not_after => Err(AlienError::new(ErrorData::Expired {
198                not_after: not_after.to_rfc3339(),
199            })),
200            _ => Ok(()),
201        }
202    }
203}
204
205fn finish<B: DeserializeOwned>(
206    opened: Opened,
207    signers: BTreeSet<String>,
208    kept: bool,
209) -> Result<Verified<B>> {
210    let body = opened.body()?;
211    Ok(Verified {
212        kind: opened.kind,
213        sequence: opened.sequence,
214        digest: opened.digest,
215        not_after: opened.not_after,
216        kept,
217        signers,
218        body,
219    })
220}