//! Public keys of rebuilders, whatever their kind. //! //! - OpenPGP certificates (guix.sigs): fingerprint as GnuPG prints it, 40 hex. //! - Ed25519 and ECDSA P-256 public keys as SPKI PEM (`-----BEGIN PUBLIC KEY-----`, //! what OpenSSL and cosign write): fingerprint is the SHA-256 //! of the key's DER encoding, 64 hex. use std::time::SystemTime; use anyhow::{Context, Result, bail}; use ed25519_dalek::pkcs8::DecodePublicKey; use sha2::{Digest, Sha256}; use crate::pgp; pub enum PubKey { Pgp(Box), Ed25519(ed25519_dalek::VerifyingKey), P256(p256::ecdsa::VerifyingKey), } impl PubKey { pub fn fingerprint(&self) -> String { match self { PubKey::Pgp(c) => c.fingerprint.clone(), PubKey::Ed25519(k) => spki_fingerprint(k), PubKey::P256(k) => spki_fingerprint(k), } } /// This key's fingerprint and, for OpenPGP, its subkeys': whatever a /// signature may name as its issuer. pub fn all_fingerprints(&self) -> Vec { match self { PubKey::Pgp(c) => c.all_fingerprints(), _ => vec![self.fingerprint()], } } pub fn kind(&self) -> &'static str { match self { PubKey::Pgp(_) => "OpenPGP", PubKey::Ed25519(_) => "Ed25519", PubKey::P256(_) => "ECDSA P-256", } } /// A user ID for OpenPGP; nothing for bare keys. pub fn label(&self) -> Option<&str> { match self { PubKey::Pgp(c) => c.user_ids.first().map(String::as_str), _ => None, } } /// "expires …", "REVOKED", or "no expiry": bare keys have neither. pub fn validity(&self, now: SystemTime) -> String { match self { PubKey::Pgp(c) if c.revoked => "REVOKED".into(), PubKey::Pgp(c) => match c.expires { Some(e) if e <= now => format!("expired {}", crate::date(e)), Some(e) => format!("expires {}", crate::date(e)), None => "no expiry".into(), }, _ => "no expiry".into(), } } } fn spki_fingerprint(k: &impl ed25519_dalek::pkcs8::EncodePublicKey) -> String { match k.to_public_key_der() { Ok(der) => hex::encode(Sha256::digest(der.as_bytes())), Err(_) => String::from("?"), } } /// Parses a key file: OpenPGP (armored or binary), or one or more SPKI PEM blocks. pub fn parse(data: &[u8]) -> Result> { let text = std::str::from_utf8(data).unwrap_or(""); if text.contains("-----BEGIN PUBLIC KEY-----") { let mut keys = Vec::new(); for block in pem_blocks(text, "PUBLIC KEY") { if let Ok(k) = ed25519_dalek::VerifyingKey::from_public_key_pem(&block) { keys.push(PubKey::Ed25519(k)); } else if let Ok(k) = p256::ecdsa::VerifyingKey::from_public_key_pem(&block) { keys.push(PubKey::P256(k)); } else { bail!("a public key that is neither Ed25519 nor ECDSA P-256"); } } return Ok(keys); } let certs = pgp::parse_certs(data).context("not an OpenPGP key, nor a PEM public key")?; Ok(certs .into_iter() .map(|c| PubKey::Pgp(Box::new(c))) .collect()) } /// Every `-----BEGIN