alien-signing 3.3.71

Signed statements, signer lists, signing settings and the install ledger for installs that run only what the vendor signed
Documentation
//! What an install has already accepted.
//!
//! Every enforcer of an install keeps the same small record: the trust root
//! it accepted state under and the highest signer list version. Setup creates the install's copy in the
//! customer's cloud non-empty, so a missing ledger is an error and never a
//! fresh start. Enforcers load it at start, take the maximum of it and their
//! own copy, and write the result back. Values only rise.
//!
//! The ledger is a trust anchor and a version floor, not a permission. What
//! keeps a release or config running after its signer leaves the list is the
//! signer list's `keep`, which the admins sign; the ledger never makes a
//! statement verify. Only enforcers write it; management has no access to it
//! (it is denied `/signed/*`).
//!
//! The ledger has to fit the smallest store an install uses (AWS SSM
//! Standard parameters hold 4 KB), so it is size-capped: it holds a fixed
//! set of small fields, and one that would pass [`MAX_LEDGER_BYTES`] is
//! refused.

use alien_error::AlienError;
use serde::{Deserialize, Serialize};

use crate::error::{ErrorData, Result};
use crate::release::is_sha256_digest;
use crate::settings::InstallId;
use crate::signer_list::{is_fingerprint, SignerChain};

/// One accepted statement.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct Entry {
    /// Its sequence, or the version of a signer list.
    pub sequence: u64,
    /// `sha256:<hex>` of its payload.
    pub digest: String,
}

/// The most bytes a ledger's JSON may take: AWS SSM Standard's parameter limit,
/// the smallest store an install keeps its ledger in.
pub const MAX_LEDGER_BYTES: usize = 4096;

/// The ledger of one install.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct Ledger {
    /// The install's prefix; it must equal where the ledger was found.
    pub prefix: String,
    /// Setup writes `true`, so an existing ledger is never read as no ledger.
    pub created: bool,
    /// The fingerprint the install first accepted state under.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub fingerprint: Option<String>,
    /// The install id the install first accepted state under.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub install: Option<String>,
    /// Highest signer list version accepted.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub signer_list: Option<Entry>,
}

impl Ledger {
    /// The ledger setup creates for `prefix`.
    pub fn new(prefix: &str) -> Self {
        Self {
            prefix: prefix.to_string(),
            created: true,
            fingerprint: None,
            install: None,
            signer_list: None,
        }
    }

    /// Parse a ledger found for `prefix`.
    pub fn parse(bytes: &[u8], prefix: &str) -> Result<Self> {
        let ledger: Ledger =
            serde_json::from_slice(bytes).map_err(|error| refused(format!("{error}")))?;
        if ledger.prefix != prefix {
            return Err(refused(format!(
                "the ledger found for '{prefix}' names prefix '{}'",
                ledger.prefix
            )));
        }
        if !ledger.created {
            return Err(refused("setup didn't create this ledger"));
        }
        if let Some(fingerprint) = &ledger.fingerprint {
            if !is_fingerprint(fingerprint) {
                return Err(refused(format!("'{fingerprint}' is not a fingerprint")));
            }
        }
        if let Some(install) = &ledger.install {
            InstallId::parse(install)?;
        }
        for entry in [&ledger.signer_list].into_iter().flatten() {
            if !is_sha256_digest(&entry.digest) {
                return Err(refused(format!("'{}' is not a digest", entry.digest)));
            }
        }
        if bytes.len() > MAX_LEDGER_BYTES {
            return Err(refused(format!(
                "it is {} bytes, over the {MAX_LEDGER_BYTES} its store holds",
                bytes.len()
            )));
        }
        Ok(ledger)
    }

    /// The JSON form enforcers write back.
    pub fn to_json(&self) -> String {
        serde_json::to_string(self).expect("a ledger always serializes")
    }

    /// Take the higher value of each entry from `other`. Two different
    /// statements with one sequence, or two trust roots, are a fork and an
    /// error.
    pub fn merge(&mut self, other: &Ledger) -> Result<()> {
        if other.prefix != self.prefix {
            return Err(refused(format!(
                "can't merge the ledger of '{}' into '{}'",
                other.prefix, self.prefix
            )));
        }
        merge_root(&mut self.fingerprint, &other.fingerprint)?;
        merge_root(&mut self.install, &other.install)?;
        merge_entry(&mut self.signer_list, &other.signer_list)?;
        self.check_size()
    }

    /// Refuse a trust root other than the one the install accepted state
    /// under, or none where it had one. Protection is sticky: removing or
    /// changing the settings, or moving the install, never makes an enforcer
    /// run something new.
    pub fn check_root(&self, fingerprint: Option<&str>, install: &InstallId) -> Result<()> {
        if let Some(accepted) = &self.fingerprint {
            if fingerprint != Some(accepted.as_str()) {
                return Err(AlienError::new(ErrorData::TrustRootChanged {
                    accepted: format!("fingerprint {accepted}"),
                    found: fingerprint
                        .map(|found| format!("fingerprint {found}"))
                        .unwrap_or_else(|| "no signing settings".to_string()),
                }));
            }
        }
        let install = install.to_string();
        if let Some(accepted) = &self.install {
            if *accepted != install {
                return Err(AlienError::new(ErrorData::TrustRootChanged {
                    accepted: format!("install {accepted}"),
                    found: format!("install {install}"),
                }));
            }
        }
        Ok(())
    }

    fn json_len(&self) -> usize {
        self.to_json().len()
    }

    /// Refuse a ledger that doesn't fit its store.
    pub fn check_size(&self) -> Result<()> {
        let len = self.json_len();
        if len > MAX_LEDGER_BYTES {
            return Err(refused(format!(
                "it would take {len} bytes, over the {MAX_LEDGER_BYTES} its store holds"
            )));
        }
        Ok(())
    }

    /// Whether the install ever accepted signed state.
    pub fn is_sticky(&self) -> bool {
        self.fingerprint.is_some()
    }

    /// Record the trust root, after [`Ledger::check_root`] passed.
    pub fn adopt_root(&mut self, fingerprint: &str, install: &InstallId) {
        self.fingerprint
            .get_or_insert_with(|| fingerprint.to_string());
        self.install.get_or_insert_with(|| install.to_string());
    }

    /// Refuse a chain that stops below the accepted version or forks from it.
    pub fn check_chain(&self, chain: &SignerChain) -> Result<()> {
        let Some(entry) = &self.signer_list else {
            return Ok(());
        };
        let current = chain.current().version;
        if current < entry.sequence {
            return Err(AlienError::new(ErrorData::SignerListMissing {
                needed: entry.sequence,
                current,
            }));
        }
        if chain.digest_of(entry.sequence) != Some(entry.digest.as_str()) {
            return Err(refused(format!(
                "signer list version {} differs from the one this install accepted",
                entry.sequence
            )));
        }
        Ok(())
    }

    /// Record the chain's current version.
    pub fn record_chain(&mut self, chain: &SignerChain) {
        let current = chain.current();
        let entry = Entry {
            sequence: current.version,
            digest: current.digest.clone(),
        };
        if self
            .signer_list
            .as_ref()
            .is_none_or(|held| held.sequence < entry.sequence)
        {
            self.signer_list = Some(entry);
        }
    }
}

fn merge_root(held: &mut Option<String>, other: &Option<String>) -> Result<()> {
    match (held.as_ref(), other) {
        (Some(mine), Some(theirs)) if mine != theirs => {
            Err(AlienError::new(ErrorData::TrustRootChanged {
                accepted: mine.clone(),
                found: theirs.clone(),
            }))
        }
        (None, Some(theirs)) => {
            *held = Some(theirs.clone());
            Ok(())
        }
        _ => Ok(()),
    }
}

fn merge_entry(held: &mut Option<Entry>, other: &Option<Entry>) -> Result<()> {
    let Some(theirs) = other else {
        return Ok(());
    };
    match held {
        Some(mine) if mine.sequence == theirs.sequence && mine.digest != theirs.digest => {
            Err(refused(format!(
                "two different signer lists were accepted with sequence {}",
                mine.sequence
            )))
        }
        Some(mine) if mine.sequence >= theirs.sequence => Ok(()),
        _ => {
            *held = Some(theirs.clone());
            Ok(())
        }
    }
}

fn refused(reason: impl Into<String>) -> AlienError<ErrorData> {
    AlienError::new(ErrorData::LedgerRefused {
        reason: reason.into(),
    })
}

#[cfg(test)]
mod tests {
    use super::*;

    fn digest(n: usize) -> String {
        format!("sha256:{n:064x}")
    }

    /// A fully populated ledger, as the largest root fields make it.
    fn full_root() -> Ledger {
        let mut ledger = Ledger::new(&"p".repeat(40));
        ledger.fingerprint = Some(format!("SHA256:{}", "a".repeat(64)));
        ledger.install = Some("aws:111122223333:us-east-1:acme-prod".to_string());
        ledger.signer_list = Some(Entry {
            sequence: u64::MAX,
            digest: digest(7),
        });
        ledger
    }

    #[test]
    fn a_full_ledger_fits_its_store() {
        let ledger = full_root();
        assert!(ledger.to_json().len() <= MAX_LEDGER_BYTES);
        ledger.check_size().unwrap();
        Ledger::parse(ledger.to_json().as_bytes(), &"p".repeat(40)).unwrap();
    }

    #[test]
    fn a_stored_ledger_over_the_cap_is_refused() {
        // Every field is valid; only the prefix makes it too big.
        let prefix = "p".repeat(MAX_LEDGER_BYTES);
        let mut ledger = full_root();
        ledger.prefix = prefix.clone();
        let text = ledger.to_json();
        assert!(text.len() > MAX_LEDGER_BYTES);
        let error = Ledger::parse(text.as_bytes(), &prefix).unwrap_err();
        assert!(format!("{error}").contains("bytes"), "{error}");
    }
}