ostrya 0.5.0

Pure-Rust async reimplementation of the ostree repository library
Documentation
//! The reader of the trust groups and the key groups, and the build of the
//! receive policy of each client group.
//!
//! The reader makes two passes. The first pass checks each trust group and
//! each key group, and refuses each key and each value outside the syntax.
//! This pass reads no file and runs no program.
//!
//! The second pass builds each key group and each trust group once, in file
//! order. It also builds a group that no client group names. The policies get
//! shared handles to these objects.

use std::collections::HashMap;
use std::path::Path;
use std::sync::Arc;

use ostrya_core::KeyFile;

use crate::access::{ClientAccess, Group, classify};
use crate::config::{Remote, SignVerify};
use crate::error::{Error, Result};
use crate::pull::DetachedMetadataFilter;
use crate::repo::Repo;
use crate::sign::{MAX_KEY_FILE, key_text, read_key_path};

use super::{ReceivePolicy, ReceiveVerify, ServerSigner, TrustedKeys};

/// The name prefix of a key group, before the quoted name.
const KEY_PREFIX: &str = "ex-ostrya key \"";
/// The sign-api engines that a trust group can name.
const TRUST_ENGINES: &[&str] = &["ed25519", "spki"];

/// One key group as the first pass reads it.
enum KeySpec {
    Ed25519 {
        file: String,
    },
    #[cfg(feature = "sign-spki")]
    Spki {
        file: String,
    },
    #[cfg(feature = "sign-gpg")]
    Gpg {
        key: String,
        homedir: Option<String>,
    },
}

/// Reads the client groups of the config of `repo`, and returns them with the
/// receive policy of each group, in the order of the groups.
pub(crate) async fn read(repo: &Repo) -> Result<(ClientAccess, Vec<Arc<ReceivePolicy>>)> {
    let config = repo.config();
    let access = ClientAccess::from_config(config, repo.path())?;
    let keyfile = config.keyfile();

    // The first pass checks each key group, then each trust group. The
    // access reader refused each other group name with the extension prefix.
    let mut builds: Vec<(Group<'_>, &str)> = Vec::new();
    for group in keyfile.groups() {
        if let Some(found @ (Group::Trust(_) | Group::Key(_))) = classify(group)? {
            builds.push((found, group));
        }
    }
    let mut keys: HashMap<&str, KeySpec> = HashMap::new();
    for (build, group) in &builds {
        if let Group::Key(name) = build {
            keys.insert(name, parse_key(keyfile, group)?);
        }
    }
    for (build, group) in &builds {
        if let Group::Trust(_) = build {
            check_trust(keyfile, group)?;
        }
    }

    // The second pass builds each key group and each trust group once, in
    // file order.
    let mut signers: HashMap<&str, Arc<ServerSigner>> = HashMap::new();
    let mut trusts: HashMap<&str, Arc<TrustedKeys>> = HashMap::new();
    for (build, group) in builds {
        match build {
            Group::Key(name) => {
                let signer = build_signer(name, &keys[name]).await?;
                signers.insert(name, Arc::new(signer));
            }
            Group::Trust(name) => {
                let keys = TrustedKeys::for_trust_group(repo, keyfile, name, group).await?;
                trusts.insert(name, Arc::new(keys));
            }
            _ => {}
        }
    }

    let named = |names: &[String]| -> Vec<Arc<ServerSigner>> {
        names
            .iter()
            .map(|name| Arc::clone(&signers[name.as_str()]))
            .collect()
    };
    let summary_signers = named(access.server().sign_summary.as_deref().unwrap_or_default());
    let update_summary = config.auto_update_summary()?;
    let exclude = config.detached_metadata_exclude()?;
    let detached_metadata_filter =
        (!exclude.is_empty()).then(|| DetachedMetadataFilter::excluding(exclude));
    let policies = access
        .groups()
        .iter()
        .map(|group| {
            Arc::new(ReceivePolicy {
                scope: group.scope().clone(),
                rules: group.rules().clone(),
                verify: match group.verify_trust() {
                    Some(name) => ReceiveVerify::Keys(Arc::clone(&trusts[name])),
                    None => ReceiveVerify::Off,
                },
                allow_unsigned: group.allow_unsigned(),
                signers: named(group.sign()),
                allow_privileged: group.allow_privileged(),
                summary_signers: summary_signers.clone(),
                update_summary,
                detached_metadata_filter: detached_metadata_filter.clone(),
                group: Some(group.name().to_owned()),
            })
        })
        .collect();
    Ok((access, policies))
}

/// Checks the trust group `group`.
///
/// Each key must be one that an axis reads. The group must turn on at least
/// one axis.
fn check_trust(keyfile: &KeyFile, group: &str) -> Result<()> {
    let mut engine_keys: Vec<(&str, &str)> = Vec::new();
    for key in keyfile.keys(group) {
        match key {
            "gpg-verify" | "gpgkeypath" | "sign-verify" => {}
            "gpg-verify-summary" | "sign-verify-summary" => {
                return Err(Error::InvalidFormat(format!(
                    "[{group}] holds '{key}', and a push carries no summary"
                )));
            }
            _ => match verification_engine(key) {
                Some(engine) if TRUST_ENGINES.contains(&engine) => {
                    engine_keys.push((key, engine));
                }
                Some(engine) => {
                    return Err(Error::InvalidFormat(format!(
                        "[{group}] holds '{key}', and '{engine}' is not ed25519 or spki"
                    )));
                }
                None => return Err(unknown_key(group, key)),
            },
        }
    }

    let gpg = keyfile.get_bool(group, "gpg-verify")?.unwrap_or(false);
    let sign = Remote::view(keyfile, group.to_owned()).sign_verify()?;
    let engines: Vec<&str> = match &sign {
        SignVerify::Off => Vec::new(),
        SignVerify::All => TRUST_ENGINES.to_vec(),
        SignVerify::Engines(names) => names.iter().map(String::as_str).collect(),
    };
    for engine in &engines {
        if !TRUST_ENGINES.contains(engine) {
            return Err(Error::InvalidFormat(format!(
                "[{group}] sign-verify names '{engine}', which is not ed25519 or spki"
            )));
        }
    }
    if !gpg && engines.is_empty() {
        return Err(Error::InvalidFormat(format!(
            "[{group}] turns on no signature check: set gpg-verify=true or sign-verify"
        )));
    }

    let keypath = keyfile.get_value(group, "gpgkeypath").is_some();
    if keypath && !gpg {
        return Err(Error::InvalidFormat(format!(
            "[{group}] sets gpgkeypath, and gpg-verify is not true, so no check reads it"
        )));
    }
    // `sign-verify=true` names every engine of the build, so it names spki
    // only in a build that has it.
    let names_spki = matches!(&sign, SignVerify::Engines(names) if names.iter().any(|n| n == "spki"))
        || engine_keys.iter().any(|(_, engine)| *engine == "spki");
    if cfg!(not(feature = "sign-spki")) && names_spki {
        return Err(Error::Unsupported(format!(
            "[{group}] names the spki engine, which this build has no engine for; \
             build with the sign-spki feature"
        )));
    }
    for (key, engine) in engine_keys {
        if !engines.contains(&engine) {
            return Err(Error::InvalidFormat(format!(
                "[{group}] holds '{key}', and sign-verify does not select {engine}, so \
                 no check reads it"
            )));
        }
    }
    if gpg {
        if cfg!(not(feature = "verify-gpg")) {
            return Err(Error::Unsupported(format!(
                "[{group}] asks for GPG verification, which this build has no engine \
                 for; build with the verify-gpg feature"
            )));
        }
        if Remote::view(keyfile, group.to_owned())
            .gpgkeypath()?
            .is_empty()
        {
            return Err(Error::InvalidFormat(format!(
                "[{group}] sets gpg-verify=true, and gpgkeypath names no keyring"
            )));
        }
    }
    Ok(())
}

/// Returns the engine that a `verification-ENGINE-key` or
/// `verification-ENGINE-file` key names, or `None` for another key.
fn verification_engine(key: &str) -> Option<&str> {
    let rest = key.strip_prefix("verification-")?;
    rest.strip_suffix("-key")
        .or_else(|| rest.strip_suffix("-file"))
}

/// Reads the key group `group`.
fn parse_key(keyfile: &KeyFile, group: &str) -> Result<KeySpec> {
    for key in keyfile.keys(group) {
        if !matches!(key, "type" | "secret-key-file" | "gpg-key" | "gpg-homedir") {
            return Err(unknown_key(group, key));
        }
    }
    let foreign = |kind: &str, keys: &[&str]| -> Result<()> {
        match keys
            .iter()
            .find(|key| keyfile.get_value(group, key).is_some())
        {
            Some(key) => Err(Error::InvalidFormat(format!(
                "[{group}] holds '{key}', which a key of type {kind} does not take"
            ))),
            None => Ok(()),
        }
    };
    let required = |key: &str| -> Result<String> {
        match keyfile.get_string(group, key)? {
            Some(value) if !value.is_empty() => Ok(value),
            _ => Err(Error::InvalidFormat(format!("[{group}] needs {key}"))),
        }
    };
    let Some(kind) = keyfile.get_string(group, "type")? else {
        return Err(Error::InvalidFormat(format!(
            "[{group}] needs type: ed25519, spki, or gpg"
        )));
    };
    match kind.as_str() {
        "ed25519" => {
            foreign(&kind, &["gpg-key", "gpg-homedir"])?;
            Ok(KeySpec::Ed25519 {
                file: required("secret-key-file")?,
            })
        }
        "spki" => {
            foreign(&kind, &["gpg-key", "gpg-homedir"])?;
            spki_key(group, required("secret-key-file")?)
        }
        "gpg" => {
            foreign(&kind, &["secret-key-file"])?;
            let key = required("gpg-key")?;
            gpg_key(group, key, keyfile.get_string(group, "gpg-homedir")?)
        }
        "dummy" => Err(Error::InvalidFormat(format!(
            "malformed [{group}] type 'dummy': the dummy engine is not a signing key, \
             its signature is its key"
        ))),
        other => Err(Error::InvalidFormat(format!(
            "malformed [{group}] type '{other}': the type is ed25519, spki, or gpg"
        ))),
    }
}

/// Returns the spec of an spki key group whose keys passed their checks.
#[cfg(feature = "sign-spki")]
fn spki_key(_group: &str, file: String) -> Result<KeySpec> {
    Ok(KeySpec::Spki { file })
}

/// Refuses an spki key group with [`Error::Unsupported`] in a build without
/// the spki engine.
///
/// The build cannot sign with the key, so the refusal stops the policy before
/// it accepts a session.
#[cfg(not(feature = "sign-spki"))]
fn spki_key(group: &str, _file: String) -> Result<KeySpec> {
    Err(Error::Unsupported(format!(
        "[{group}] is an spki key, which this build cannot sign with; build with \
         the sign-spki feature"
    )))
}

/// Returns the spec of a GPG key group whose keys passed their checks.
#[cfg(feature = "sign-gpg")]
fn gpg_key(_group: &str, key: String, homedir: Option<String>) -> Result<KeySpec> {
    Ok(KeySpec::Gpg { key, homedir })
}

/// Refuses a GPG key group with [`Error::Unsupported`] in a build without
/// GPG signing.
///
/// The build cannot sign with the key, so the refusal stops the policy before
/// it accepts a session.
#[cfg(not(feature = "sign-gpg"))]
fn gpg_key(group: &str, _key: String, _homedir: Option<String>) -> Result<KeySpec> {
    Err(Error::Unsupported(format!(
        "[{group}] is a GPG key, which this build cannot sign with; build with the \
         sign-gpg feature"
    )))
}

/// Builds the signer of the key group `name`.
async fn build_signer(name: &str, spec: &KeySpec) -> Result<ServerSigner> {
    let label = format!("[{KEY_PREFIX}{name}\"]");
    let in_group = |e: Error| match e {
        Error::Signature(message) => Error::Signature(format!("{label}: {message}")),
        other => other,
    };
    match spec {
        KeySpec::Ed25519 { file } => {
            let line = secret_key_line(file).await.map_err(in_group)?;
            ServerSigner::ed25519(&ostrya_core::base64::decode(&line)?).map_err(in_group)
        }
        #[cfg(feature = "sign-spki")]
        KeySpec::Spki { file } => {
            let line = secret_key_line(file).await.map_err(in_group)?;
            ServerSigner::spki(crate::spki::SpkiSigner::from_base64(&line)?).map_err(in_group)
        }
        #[cfg(feature = "sign-gpg")]
        KeySpec::Gpg { key, homedir } => {
            let mut signer = crate::gpg::GpgSigner::new(key.as_str());
            if let Some(dir) = homedir {
                signer = signer.with_homedir(dir);
            }
            ServerSigner::gpg(signer).await.map_err(in_group)
        }
    }
}

/// Returns the one secret key that the file at `path` holds, as its base64
/// line.
///
/// The read runs on the blocking pool.
async fn secret_key_line(path: &str) -> Result<String> {
    let path = path.to_owned();
    ostrya_rt::unblock(move || read_secret_key_line(&path)).await
}

/// Reads the one secret key line of the file at `path`, the blocking half of
/// `secret_key_line`.
///
/// The read obeys the rule of every key source: a regular file alone, of at
/// most [`MAX_KEY_FILE`] bytes. The function skips blank lines. The file must
/// hold exactly one other line.
fn read_secret_key_line(path: &str) -> Result<String> {
    let subject = format!("the secret key file '{path}'");
    let Some(bytes) = read_key_path(Path::new(path), &subject, MAX_KEY_FILE)? else {
        return Err(Error::Signature(format!("{subject} does not exist")));
    };
    let text = key_text(bytes, &subject)?;
    let mut lines = text.lines().map(str::trim).filter(|line| !line.is_empty());
    match (lines.next(), lines.next()) {
        (Some(line), None) => Ok(line.to_owned()),
        (None, _) => Err(Error::Signature(format!("{subject} holds no key"))),
        (Some(_), Some(_)) => Err(Error::Signature(format!(
            "{subject} holds more than one key"
        ))),
    }
}

/// Returns the error for a key that `group` does not take.
fn unknown_key(group: &str, key: &str) -> Error {
    Error::InvalidFormat(format!("[{group}] holds the unknown key '{key}'"))
}

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

    /// `verification_engine` returns the engine that a verification key
    /// names.
    #[test]
    fn verification_keys_name_their_engine() {
        assert_eq!(
            verification_engine("verification-ed25519-key"),
            Some("ed25519")
        );
        assert_eq!(verification_engine("verification-spki-file"), Some("spki"));
        assert_eq!(verification_engine("verification-x-y"), None);
        assert_eq!(verification_engine("gpgkeypath"), None);
    }
}