pqr 0.1.0

Post-quantum resistant encryption, decryption, and key generation from the command line. Easy to use, with sane defaults.
//! Recipient public keys: parsing, validation, and the classical-key refusal.

use std::fs;
use std::path::Path;

use pgp::composed::{Deserializable, SignedPublicKey, SignedPublicSubKey};
use pgp::crypto::public_key::PublicKeyAlgorithm;
use pgp::packet::SignatureType;
use pgp::types::{KeyDetails, Timestamp};

use crate::shared::{Failure, Result};

/// Parse an armored or binary public key and verify its self-signatures.
pub fn parse_public(data: &[u8]) -> Result<SignedPublicKey> {
    let (key, _) = SignedPublicKey::from_reader_single(data)
        .map_err(|_| Failure::usage("cannot read public key: not a valid PGP public key"))?;
    key.verify_bindings()
        .map_err(|e| Failure::usage(format!("invalid public key: {e}")))?;
    Ok(key)
}

/// Load the `-r` value: the armored key text itself, else a public key file path.
pub fn load(value: &str) -> Result<SignedPublicKey> {
    if value
        .trim_start()
        .starts_with("-----BEGIN PGP PUBLIC KEY BLOCK-----")
    {
        return parse_public(value.as_bytes());
    }
    let path = Path::new(value);
    let data = fs::read(path)
        .map_err(|e| Failure::usage(format!("cannot read recipient {}: {e}", path.display())))?;
    parse_public(&data)
}

/// True when the subkey has a revocation signature, or its newest binding says it has expired.
fn is_dead(sub: &SignedPublicSubKey) -> bool {
    if sub
        .signatures
        .iter()
        .any(|sig| sig.typ() == Some(SignatureType::SubkeyRevocation))
    {
        return true;
    }
    let newest = sub
        .signatures
        .iter()
        .filter(|sig| sig.typ() == Some(SignatureType::SubkeyBinding))
        .max_by_key(|sig| sig.created());
    let Some(lifetime) = newest.and_then(|sig| sig.key_expiration_time()) else {
        return false;
    };
    let ends = u64::from(sub.created_at().as_secs()) + u64::from(lifetime.as_secs());
    lifetime.as_secs() != 0 && Timestamp::now().as_secs() as u64 >= ends
}

/// The usable ML-KEM-768+X25519 encryption subkey of `key`, or a refusal for classical, expired, or revoked keys.
pub fn pq_subkey(key: &SignedPublicKey) -> Result<&SignedPublicSubKey> {
    let mut pq = key
        .public_subkeys
        .iter()
        .filter(|sub| sub.algorithm() == PublicKeyAlgorithm::MlKem768X25519)
        .peekable();
    if pq.peek().is_none() {
        return Err(Failure::usage(
            "classical keys are refused: the recipient has no ML-KEM-768+X25519 encryption subkey",
        ));
    }
    pq.find(|sub| !is_dead(sub))
        .ok_or_else(|| Failure::usage("this public key's encryption key is expired or revoked"))
}