stratum-node-config 0.1.0-alpha.2

Versioned stratum.toml schema, comment-preserving editor, semantic validator, change preview and public-config hash for Stratum nodes
Documentation
//! Structural validation of age post-quantum hybrid recipients (ADR D14).
//!
//! This crate does not depend on `age`; it checks the textual encoding that
//! `age` 0.13 (`age::pq::Recipient`) produces and accepts:
//!
//! - Bech32 as in BIP-173 (the original constant, not Bech32m) with the
//!   human-readable part `age1pq`, so the string begins `age1pq1`;
//! - no 90-character limit: `age` lifts it because a post-quantum recipient
//!   is 1959 characters long;
//! - lowercase only (`age` encodes lowercase and refuses an uppercase HRP);
//! - canonical zero padding of at most four bits;
//! - a payload of exactly 1216 bytes, the X-Wing public key (an ML-KEM-768
//!   encapsulation key of 1184 bytes followed by an X25519 public key of 32).
//!
//! What it cannot check without the `age` implementation: that the ML-KEM
//! key's coefficients are reduced and that the X25519 point is not of low
//! order. `age` refuses those when the recipient is parsed for encryption, so
//! a structurally valid but unusable key fails at backup time, not silently.

use bech32::primitives::decode::{
    CheckedHrpstring, CheckedHrpstringError, ChecksumError, PaddingError,
};

/// Human-readable part of an age post-quantum hybrid recipient.
const PQ_HRP: &str = "age1pq";

/// Human-readable part of a classical age X25519 recipient.
const CLASSICAL_HRP: &str = "age";

/// Decoded length of a post-quantum recipient: an X-Wing public key.
pub(crate) const PQ_KEY_BYTES: usize = 1216;

/// Decoded length of a classical X25519 recipient.
const CLASSICAL_KEY_BYTES: usize = 32;

/// The BIP-173 Bech32 checksum without the 90-character code length limit.
/// Identical constants to [`bech32::Bech32`]; `age-core` 0.13 defines the
/// same checksum for the same reason.
enum Bech32Long {}

impl bech32::Checksum for Bech32Long {
    type MidstateRepr = u32;
    type CorrectionField = <bech32::Bech32 as bech32::Checksum>::CorrectionField;
    const ROOT_GENERATOR: Self::CorrectionField = bech32::Bech32::ROOT_GENERATOR;
    const ROOT_EXPONENTS: core::ops::RangeInclusive<usize> = bech32::Bech32::ROOT_EXPONENTS;
    const CODE_LENGTH: usize = usize::MAX;
    const CHECKSUM_LENGTH: usize = bech32::Bech32::CHECKSUM_LENGTH;
    const GENERATOR_SH: [u32; 5] = bech32::Bech32::GENERATOR_SH;
    const TARGET_RESIDUE: u32 = bech32::Bech32::TARGET_RESIDUE;
}

/// Why a string is not an acceptable recipient. Messages never contain the
/// string itself.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum RecipientError {
    /// A well-formed classical X25519 recipient.
    Classical,
    /// Any other recipient type, or text that is not a recipient.
    NotPostQuantum,
    /// The `age1pq` prefix with uppercase characters.
    NotLowercase,
    /// The `age1pq` prefix with characters outside the Bech32 alphabet or an
    /// unparseable layout.
    Encoding,
    /// The Bech32 checksum does not match.
    Checksum,
    /// The trailing padding bits are not zero.
    Padding,
    /// The decoded key is not [`PQ_KEY_BYTES`] long.
    Length,
}

impl RecipientError {
    /// The message, completed by the caller with the entry number.
    pub(crate) fn message(self) -> String {
        match self {
            Self::Classical => format!(
                "is a classical age recipient; a post-quantum recipient beginning with \"{PQ_HRP}1\" is required"
            ),
            Self::NotPostQuantum => {
                format!("must be a post-quantum age recipient beginning with \"{PQ_HRP}1\"")
            }
            Self::NotLowercase => "must be lowercase".to_owned(),
            Self::Encoding => {
                "is not a valid post-quantum age recipient: invalid bech32 encoding".to_owned()
            }
            Self::Checksum => {
                "is not a valid post-quantum age recipient: bad bech32 checksum".to_owned()
            }
            Self::Padding => {
                "is not a valid post-quantum age recipient: non-zero padding bits".to_owned()
            }
            Self::Length => format!(
                "is not a valid post-quantum age recipient: key must be {PQ_KEY_BYTES} bytes"
            ),
        }
    }
}

/// Checks that `s` is a structurally valid age post-quantum recipient.
pub(crate) fn check_post_quantum(s: &str) -> Result<(), RecipientError> {
    // Bech32 data characters never include '1', so the last '1' separates
    // the human-readable part.
    let Some((hrp, _)) = s.rsplit_once('1') else {
        return Err(RecipientError::NotPostQuantum);
    };
    if hrp.eq_ignore_ascii_case(CLASSICAL_HRP) {
        return Err(if decode(s, CLASSICAL_KEY_BYTES).is_ok() {
            RecipientError::Classical
        } else {
            RecipientError::NotPostQuantum
        });
    }
    if !hrp.eq_ignore_ascii_case(PQ_HRP) {
        return Err(RecipientError::NotPostQuantum);
    }
    if s.bytes().any(|b| b.is_ascii_uppercase()) {
        return Err(RecipientError::NotLowercase);
    }
    decode(s, PQ_KEY_BYTES)
}

/// Decodes `s` with the long Bech32 checksum and checks its padding and
/// payload length.
fn decode(s: &str, key_bytes: usize) -> Result<(), RecipientError> {
    let parsed = CheckedHrpstring::new::<Bech32Long>(s).map_err(|e| match e {
        CheckedHrpstringError::Checksum(ChecksumError::InvalidResidue(_)) => {
            RecipientError::Checksum
        }
        _ => RecipientError::Encoding,
    })?;
    // Five or more padding bits mean the data is not a whole number of
    // bytes of any length, so that case is reported as a length error.
    parsed.validate_segwit_padding().map_err(|e| match e {
        PaddingError::NonZero => RecipientError::Padding,
        _ => RecipientError::Length,
    })?;
    if parsed.byte_iter().len() == key_bytes {
        Ok(())
    } else {
        Err(RecipientError::Length)
    }
}