decision-cert 0.10.0

Verify and apply decision-certificate.v1: signed records of how a model's decisions were measured
Documentation
//! `decision-cert verify <cert.json> --keys <keys.json> [--tenant <tenant> [--flow <flow> --env <env>]] [--now <ts>]`
//!
//! Exit 0: the certificate verifies against the trusted keys and has not expired at `--now`
//! (default: the current time); its id is printed on stdout.
//! Exit 1: it does not verify, or it has expired; the reason is printed on stderr.
//! Exit 2: usage error, an unreadable file, or a keys file that is not a JSON object of strings
//! (with `--tenant`: of key entries, spec v1.5 §4).
//! With `--tenant`, the certificate is verified for that expected tenant (any spec; a v1.5
//! certificate needs it). With `--flow` and `--env` as well, it is verified as a v1.6 certificate for
//! that tenant, flow and environment (spec v1.6 §4; only a v1.6 certificate, which needs them).
//! `python -m decision_cert verify` behaves the same.
//!
//! `decision-cert verify-bundle <bundle.json> --trust <log-trust.json>` and
//! `decision-cert verify-consistency <consistency.json> --trust <log-trust.json>` check an inclusion
//! bundle or a consistency proof document (`decision-cert-inclusion.v1`) against one tenant's
//! log trust configuration, and print one JSON verdict line on stdout: `{"verdict": "accepted", ...}`
//! with exit 0, or `{"verdict": "refused", "error": <error name>, "detail": ...}` with exit 1 (the
//! reason also on stderr). Exit 2: usage error, an unreadable file, or a log trust configuration that
//! is not I-JSON or not well formed (`trust_form`, on stderr). `verify-bundle` does not verify the
//! bundle's certificate itself; `verify` does.

use std::{
    collections::BTreeMap,
    path::{Path, PathBuf},
    process::ExitCode,
};

use clap::{Parser, Subcommand};
use decision_cert::inclusion::{self, ErrorName, InclusionError, LogTrust};

#[derive(Parser)]
#[command(version, about = "Verify decision-certificate.v1 certificates")]
struct Cli {
    #[command(subcommand)]
    command: Command,
}

#[derive(Subcommand)]
enum Command {
    /// Verify a certificate against trusted keys and check its expiry.
    Verify {
        /// The certificate, a JSON object.
        cert: PathBuf,
        /// Trusted keys: a JSON object of key id -> base64url raw Ed25519 public key (with
        /// --tenant, an entry may also be {"key", "mode", "host"}).
        #[arg(long)]
        keys: PathBuf,
        /// The tenant the certificate must be for (spec v1.5); its keys are the --keys file.
        #[arg(long)]
        tenant: Option<String>,
        /// The flow a v1.6 certificate must be for (spec v1.6 §4); needs --tenant and --env.
        #[arg(long, requires_all = ["tenant", "env"])]
        flow: Option<String>,
        /// The environment a v1.6 certificate must be for (spec v1.6 §4); needs --tenant and --flow.
        #[arg(long, requires_all = ["tenant", "flow"])]
        env: Option<String>,
        /// The time to check expiry at, `YYYY-MM-DDTHH:MM:SSZ` (default: now).
        #[arg(long)]
        now: Option<String>,
    },
    /// Verify an inclusion bundle against a tenant's log trust configuration.
    VerifyBundle {
        /// The bundle, a `decision-cert-inclusion.v1` JSON object.
        bundle: PathBuf,
        /// The tenant's log trust configuration, a `decision-cert-log-trust.v1` JSON object.
        #[arg(long)]
        trust: PathBuf,
    },
    /// Verify a consistency proof document against a tenant's log trust configuration.
    VerifyConsistency {
        /// The document, a `decision-cert-consistency.v1` JSON object.
        doc: PathBuf,
        /// The tenant's log trust configuration, a `decision-cert-log-trust.v1` JSON object.
        #[arg(long)]
        trust: PathBuf,
    },
}

fn main() -> ExitCode {
    let cli = match Cli::try_parse() {
        Ok(c) => c,
        Err(e) => {
            let _ = e.print();
            return ExitCode::from(if e.use_stderr() { 2 } else { 0 });
        }
    };
    let (cert, keys, tenant, scope, now) = match cli.command {
        Command::Verify {
            cert,
            keys,
            tenant,
            flow,
            env,
            now,
        } => (cert, keys, tenant, flow.zip(env), now),
        Command::VerifyBundle { bundle, trust } => {
            return inclusion(
                &bundle,
                &trust,
                |v, t| decision_cert::inclusion::verify_bundle(v, t).map(|v| v.to_json()),
                ErrorName::BundleForm,
            )
        }
        Command::VerifyConsistency { doc, trust } => {
            return inclusion(
                &doc,
                &trust,
                |v, t| decision_cert::inclusion::verify_consistency(v, t).map(|v| v.to_json()),
                ErrorName::ConsistencyForm,
            )
        }
    };
    let scope = scope.as_ref().map(|(f, e)| (f.as_str(), e.as_str()));
    match run(&cert, &keys, tenant.as_deref(), scope, now.as_deref()) {
        Ok(id) => {
            println!("{id}");
            ExitCode::SUCCESS
        }
        Err(Failure::Rejected(m)) => {
            eprintln!("{}: {m}", cert.display());
            ExitCode::from(1)
        }
        Err(Failure::Usage(m)) => {
            eprintln!("decision-cert: {m}");
            ExitCode::from(2)
        }
    }
}

/// `verify-bundle` and `verify-consistency`: one JSON verdict line on stdout, exit 0 or 1; exit 2 for
/// an unreadable file or a configuration that is not well formed.
fn inclusion(
    doc: &Path,
    trust: &Path,
    check: impl Fn(&serde_json::Value, &LogTrust) -> Result<serde_json::Value, InclusionError>,
    form: ErrorName,
) -> ExitCode {
    let usage = |m: String| {
        eprintln!("decision-cert: {m}");
        ExitCode::from(2)
    };
    let trust = match std::fs::read(trust) {
        Err(e) => return usage(format!("{}: {e}", trust.display())),
        Ok(bytes) => match std::str::from_utf8(&bytes)
            .map_err(|e| e.to_string())
            .and_then(inclusion::parse_ijson)
            .map_err(|e| InclusionError::new(ErrorName::TrustForm, e))
            .and_then(|v| LogTrust::from_json(&v))
        {
            Ok(t) => t,
            Err(e) => return usage(format!("{}: {e}", trust.display())),
        },
    };
    let bytes = match std::fs::read(doc) {
        Ok(b) => b,
        Err(e) => return usage(format!("{}: {e}", doc.display())),
    };
    let verdict = std::str::from_utf8(&bytes)
        .map_err(|e| e.to_string())
        .and_then(inclusion::parse_ijson)
        .map_err(|e| InclusionError::new(form, format!("not I-JSON: {e}")))
        .and_then(|v| check(&v, &trust));
    match verdict {
        Ok(mut v) => {
            v["verdict"] = "accepted".into();
            println!("{v}");
            ExitCode::SUCCESS
        }
        Err(e) => {
            let v = serde_json::json!({
                "verdict": "refused",
                "error": e.name.as_str(),
                "detail": e.detail,
            });
            println!("{v}");
            eprintln!("{}: {e}", doc.display());
            ExitCode::from(1)
        }
    }
}

enum Failure {
    Rejected(String),
    Usage(String),
}

enum Keys {
    Flat(BTreeMap<String, String>),
    Tenant(String, decision_cert::TenantKeys),
}

fn run(
    cert: &std::path::Path,
    keys: &std::path::Path,
    tenant: Option<&str>,
    scope: Option<(&str, &str)>,
    now: Option<&str>,
) -> Result<String, Failure> {
    let read = |p: &std::path::Path| {
        std::fs::read_to_string(p).map_err(|e| Failure::Usage(format!("{}: {e}", p.display())))
    };
    let keys_text = read(keys)?;
    let keys = match tenant {
        None => Keys::Flat(serde_json::from_str(&keys_text).map_err(|e| {
            Failure::Usage(format!(
                "{}: not a JSON object of key id -> public key: {e}",
                keys.display()
            ))
        })?),
        Some(t) => {
            let usage = |e: String| {
                Failure::Usage(format!(
                    "{}: not a JSON object of key id -> key entry: {e}",
                    keys.display()
                ))
            };
            let v: serde_json::Value =
                serde_json::from_str(&keys_text).map_err(|e| usage(e.to_string()))?;
            let tk = decision_cert::tenant_keys_from_json(&v).map_err(|e| usage(e.to_string()))?;
            Keys::Tenant(t.to_string(), tk)
        }
    };
    let now = match now {
        Some(s) => decision_cert::timestamp(s)
            .map_err(|_| Failure::Usage(format!("--now {s:?} is not YYYY-MM-DDTHH:MM:SSZ")))?,
        None => decision_cert::UtcDateTime::now(),
    };
    let text = read(cert)?;
    let value: serde_json::Value = serde_json::from_str(&text).map_err(|e| {
        Failure::Rejected(format!(
            "certificate is not a valid decision certificate: not JSON: {e}"
        ))
    })?;
    let v = match &keys {
        Keys::Flat(k) => decision_cert::verify(&value, k),
        Keys::Tenant(t, k) => match scope {
            Some((flow, env)) => decision_cert::verify_sequential(&value, t, k, flow, env),
            None => decision_cert::verify_for_tenant(&value, t, k),
        },
    }
    .map_err(|e| Failure::Rejected(e.to_string()))?;
    if v.is_expired(now) {
        return Err(Failure::Rejected(format!(
            "certificate {} has expired (its expires_at is not after the check time)",
            v.id
        )));
    }
    Ok(v.id)
}