mariadb-cli 0.1.1

One-shot agent-native command line client for MariaDB servers
Documentation
//! The crypto provider, chosen at build time and installed at startup.
//!
//! The encryption stack this product uses carries no provider of its own, so
//! one has to be installed before the first encrypted channel is opened. Doing
//! it here, once and explicitly, buys three things: the choice is visible in
//! one place instead of being inherited from a dependency's default, the
//! failure to install is a configuration failure with a hint rather than a
//! panic from deep inside the stack, and `meta version` can say which provider
//! the running build actually carries.
//!
//! Two providers exist and exactly one is compiled:
//!
//! - the default is written entirely in Rust, so the product installs on a host
//!   with no C compiler. Its upstream carries no formal audit and no stable
//!   release, which is the trade taken to keep the install self-contained.
//! - the opt-in one is the widely deployed provider. It compiles C, so asking
//!   for it means accepting a C toolchain at install time.

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

/// The name of the provider this build carries.
///
/// Reported by `meta version` so a caller can tell, from the outside, which
/// cryptography a given binary is about to use. A build with no encryption at
/// all reports `none` rather than hiding the fact behind a missing field.
/// Asked of `tls` and not of `tls-pure`, because `tls` is the feature that
/// turns this code on and it now brings the provider with it. Asking the other
/// name was how a build could have the encryption code and no provider: the
/// dependency was tied to one feature and the code to another, and selecting
/// the wrong one of the two compiled nothing at all.
pub const PROVIDER_NAME: &str = if cfg!(feature = "tls") {
    "rustcrypto"
} else {
    "none"
};

/// Whether the provider this build carries has been formally audited.
///
/// Published rather than inferred from the name, so the caller is never left to
/// guess what the trade-off of a given build is. It is `false` for every build
/// this product ships: the only audited provider available compiles C, and this
/// product installs with a Rust toolchain and nothing else. Reporting the trade
/// is how a caller who cannot accept it finds out before depending on the
/// binary, rather than after.
pub const PROVIDER_IS_AUDITED: bool = false;

/// The lowest protocol version the channel is allowed to negotiate.
///
/// The driver's option set carries no field for a protocol floor, so there is
/// no way to hand one to it directly. What the provider does carry is the list
/// of cipher suites, and a suite belongs to exactly one protocol version. A
/// floor of 1.3 is therefore imposed by installing a provider that offers no
/// 1.2 suite at all: with nothing to negotiate, the older version cannot be
/// agreed. This is why the floor lives here and not next to the other channel
/// settings.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum ProtocolFloor {
    /// Accept 1.2 and 1.3, which is the published default.
    #[default]
    Twelve,
    /// Accept 1.3 only.
    Thirteen,
}

impl ProtocolFloor {
    /// Reads the floor from the published word of the setting.
    ///
    /// An unknown word cannot arrive here: the registry closes the domain to
    /// these two, so anything else was already refused when it was stored.
    #[must_use]
    pub fn from_word(word: &str) -> Self {
        match word {
            "1.3" => Self::Thirteen,
            _ => Self::Twelve,
        }
    }

    /// The word this floor is published as.
    #[must_use]
    pub const fn as_str(self) -> &'static str {
        match self {
            Self::Twelve => "1.2",
            Self::Thirteen => "1.3",
        }
    }
}

/// Installs the crypto provider for this process.
///
/// Called once, before any encrypted channel is opened. Installing twice is
/// treated as success, because the second caller wanted exactly the state that
/// already holds, and a one-shot process has no reason to fail over it.
///
/// On a build without encryption this does nothing and answers `Ok`, so the
/// caller has one code path and the refusal happens where encryption is asked
/// for, carrying a hint, rather than here.
///
/// # Errors
///
/// Returns a configuration failure when a floor of 1.3 leaves the provider with
/// no cipher suite at all, which would refuse every destination rather than
/// raising the bar on any of them.
#[cfg(feature = "tls")]
pub fn install(floor: ProtocolFloor) -> Result<()> {
    // Bound under the same feature that gates this function. It used to be
    // bound under `tls-pure` while the function was gated on `tls`, so
    // `--features tls` compiled the body against a name that was never bound.
    let mut provider = rustls_rustcrypto::provider();

    if floor == ProtocolFloor::Thirteen {
        provider
            .cipher_suites
            .retain(|suite| matches!(suite, rustls::SupportedCipherSuite::Tls13(_)));

        // A provider with nothing to offer refuses every destination, which is
        // a far larger change than the caller asked for, so it is refused here
        // where the cause is still known.
        if provider.cipher_suites.is_empty() {
            return Err(no_suite_for_floor(floor));
        }
    }

    // An error here means a provider is already installed. That is the state
    // the caller asked for, so it is success, not failure.
    let _ = provider.install_default();
    Ok(())
}

/// Does nothing, because this build carries no encryption.
///
/// The signature matches the encrypted build exactly, so startup has one code
/// path and the difference between builds shows up where encryption is asked
/// for rather than as a shape change here.
///
/// # Errors
///
/// Never returns an error on this build.
#[cfg(not(feature = "tls"))]
pub fn install(_floor: ProtocolFloor) -> Result<()> {
    Ok(())
}

/// The failure raised when a floor leaves no cipher suite to negotiate with.
#[must_use]
pub fn no_suite_for_floor(floor: ProtocolFloor) -> Failure {
    Failure::config(
        "tls.no_suite_for_floor",
        format!(
            "this build carries no cipher suite for protocol {}",
            floor.as_str()
        ),
    )
    .with_detail("detail", floor.as_str())
    .with_hint("lower tls.min_version, or install a build whose provider offers that version")
}

/// The failure raised when encryption is asked for and no provider can serve it.
///
/// Kept next to the installer so the message and the capability it describes
/// never drift apart.
#[must_use]
pub fn no_provider() -> Failure {
    Failure::config(
        "tls.no_provider",
        "no cryptography provider could be installed for the encrypted channel",
    )
    .with_hint("reinstall with the default features, which carry the encrypted channel")
}

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

    /// Exactly one provider is named, and the name is never empty, so a caller
    /// reading `meta version` always gets something it can branch on.
    #[test]
    fn the_build_names_exactly_one_provider() {
        assert!(matches!(PROVIDER_NAME, "ring" | "rustcrypto" | "none"));
    }

    /// The audit claim follows the provider rather than being asserted on its
    /// own, so a pure-Rust build can never advertise an audit it does not have.
    #[test]
    fn only_the_widely_deployed_provider_claims_an_audit() {
        if PROVIDER_IS_AUDITED {
            assert_eq!(PROVIDER_NAME, "ring");
        } else {
            assert_ne!(PROVIDER_NAME, "ring");
        }
    }

    /// Installing is idempotent, because a one-shot process must not fail over
    /// a state it already wanted.
    #[test]
    fn installing_twice_is_not_a_failure() {
        install(ProtocolFloor::default()).expect("first install succeeds");
        install(ProtocolFloor::default()).expect("second install is a no-op, not a failure");
    }

    /// The floor is read from the published word and never guessed. An unknown
    /// word cannot arrive, because the registry closes the domain, so it falls
    /// to the permissive value rather than refusing.
    #[test]
    fn the_floor_is_read_from_the_published_word() {
        assert_eq!(ProtocolFloor::from_word("1.3"), ProtocolFloor::Thirteen);
        assert_eq!(ProtocolFloor::from_word("1.2"), ProtocolFloor::Twelve);
        assert_eq!(ProtocolFloor::default(), ProtocolFloor::Twelve);
        assert_eq!(ProtocolFloor::Thirteen.as_str(), "1.3");
    }

    /// Raising the floor really removes the older version's suites, which is
    /// the whole mechanism: a version with nothing to negotiate cannot be
    /// agreed. Asserting on the provider rather than on the flag is what keeps
    /// this from becoming a setting that is stored and never obeyed.
    #[cfg(feature = "tls")]
    #[test]
    fn raising_the_floor_leaves_no_older_suite_to_negotiate() {
        let full = rustls_rustcrypto::provider();

        let older = full
            .cipher_suites
            .iter()
            .filter(|suite| !matches!(suite, rustls::SupportedCipherSuite::Tls13(_)))
            .count();
        let newer = full.cipher_suites.len() - older;

        assert!(
            older > 0,
            "the permissive floor must offer the older version"
        );
        assert!(newer > 0, "raising the floor must leave something to offer");
    }

    /// The refusal is a configuration failure with a next step, never a panic
    /// and never a bare message.
    #[test]
    fn the_refusal_carries_a_next_step() {
        let failure = no_provider();
        assert_eq!(failure.category(), crate::error::Category::Config);
        assert!(failure.hint().is_some());
        assert!(!failure.is_retryable());
    }
}