use super::profile::Profile;
use crate::error::{Failure, Result};
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub struct Verification {
pub accept_unknown_authority: bool,
pub accept_address_mismatch: bool,
}
impl Verification {
#[must_use]
pub const fn is_strict(self) -> bool {
!self.accept_unknown_authority && !self.accept_address_mismatch
}
pub fn parse(word: &str) -> Result<Self> {
match word {
"full" => Ok(Self {
accept_unknown_authority: false,
accept_address_mismatch: false,
}),
"ca" => Ok(Self {
accept_unknown_authority: false,
accept_address_mismatch: true,
}),
"none" => Ok(Self {
accept_unknown_authority: true,
accept_address_mismatch: true,
}),
other => Err(Failure::config(
"config.unknown_tls_verify",
format!("`{other}` is not a level this build checks a certificate at"),
)
.with_detail("detail", other)
.with_hint("set tls.verify to full, to ca or to none")),
}
}
}
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub enum RootStore {
#[default]
System,
Bundled,
File,
}
impl RootStore {
pub fn parse(word: &str) -> Result<Self> {
match word {
"system" => Ok(Self::System),
"bundled" => Ok(Self::Bundled),
"file" => Ok(Self::File),
other => Err(Failure::config(
"config.unknown_root_store",
format!("`{other}` is not a source of trusted authorities"),
)
.with_detail("detail", other)
.with_hint("set tls.root_store to system, to bundled or to file")),
}
}
#[must_use]
pub const fn trusts_the_built_in_authorities(self) -> bool {
matches!(self, Self::System | Self::Bundled)
}
#[must_use]
pub const fn trusts_the_named_authority(self) -> bool {
matches!(self, Self::System | Self::File)
}
}
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub struct Encryption {
pub demanded: bool,
pub verification: Verification,
pub root_store: RootStore,
}
#[must_use]
pub fn wants_encryption(profile: &Profile, encryption: &Encryption) -> bool {
if profile.ca.is_some() || profile.client_cert.is_some() || profile.client_key.is_some() {
return true;
}
profile.require_tls.unwrap_or(encryption.demanded)
}
#[must_use]
pub fn unavailable() -> Failure {
Failure::config(
"tls.not_available",
"this build carries no network encryption",
)
.with_hint(
"install a build with the encryption feature enabled, or drop the encryption request",
)
}
fn ensure_identity_is_complete(profile: &Profile) -> Result<()> {
match (&profile.client_cert, &profile.client_key) {
(Some(_), None) => Err(Failure::config(
"tls.key_missing",
"a client certificate was named without its key",
)
.with_hint("name the matching key with --client-key")),
(None, Some(_)) => Err(Failure::config(
"tls.certificate_missing",
"a client key was named without its certificate",
)
.with_hint("name the matching certificate with --client-cert")),
_ => Ok(()),
}
}
#[cfg(feature = "tls")]
pub fn channel(profile: &Profile, encryption: &Encryption) -> Result<Option<mysql_async::SslOpts>> {
use mysql_async::{ClientIdentity, SslOpts};
if !wants_encryption(profile, encryption) {
return Ok(None);
}
ensure_identity_is_complete(profile)?;
ensure_the_named_authority_exists(profile, encryption.root_store)?;
let mut options = SslOpts::default()
.with_danger_accept_invalid_certs(encryption.verification.accept_unknown_authority)
.with_danger_skip_domain_validation(encryption.verification.accept_address_mismatch)
.with_disable_built_in_roots(!encryption.root_store.trusts_the_built_in_authorities());
if let Some(authority) = &profile.ca {
if encryption.root_store.trusts_the_named_authority() {
options = options.with_root_certs(vec![authority.clone().into()]);
}
}
if let (Some(certificate), Some(key)) = (&profile.client_cert, &profile.client_key) {
options = options.with_client_identity(Some(ClientIdentity::new(
certificate.clone().into(),
key.clone().into(),
)));
}
Ok(Some(options))
}
#[cfg(feature = "tls")]
fn ensure_the_named_authority_exists(profile: &Profile, root_store: RootStore) -> Result<()> {
if root_store == RootStore::File && profile.ca.is_none() {
return Err(Failure::config(
"tls.no_authority_named",
"the trust source is the named authority and this destination names none",
)
.with_hint("name an authority with --ca, or set tls.root_store to system"));
}
Ok(())
}
#[cfg(not(feature = "tls"))]
pub fn channel(profile: &Profile, encryption: &Encryption) -> Result<Option<mysql_async::SslOpts>> {
if wants_encryption(profile, encryption) {
return Err(unavailable());
}
ensure_identity_is_complete(profile)?;
Ok(None)
}
#[cfg(test)]
mod tests {
use super::*;
use std::path::PathBuf;
fn encrypted() -> Profile {
Profile {
host: Some("db.example".to_owned()),
require_tls: Some(true),
..Profile::named("secure")
}
}
#[test]
fn a_plain_destination_asks_for_no_encryption() {
let profile = Profile {
host: Some("db.example".to_owned()),
..Profile::named("plain")
};
assert!(!wants_encryption(&profile, &Encryption::default()));
assert!(channel(&profile, &Encryption::default())
.expect("no encryption asked for")
.is_none());
}
#[test]
fn naming_a_certificate_asks_for_encryption() {
let by_authority = Profile {
ca: Some(PathBuf::from("/etc/ssl/ca.pem")),
..Profile::named("implicit")
};
assert!(wants_encryption(&by_authority, &Encryption::default()));
}
#[test]
fn a_silent_destination_takes_the_stored_demand() {
let profile = Profile {
host: Some("db.example".to_owned()),
..Profile::named("silent")
};
let demanded = Encryption {
demanded: true,
..Encryption::default()
};
assert!(!wants_encryption(&profile, &Encryption::default()));
assert!(wants_encryption(&profile, &demanded));
}
#[test]
fn a_destination_that_states_no_encryption_beats_the_stored_demand() {
let demanded = Encryption {
demanded: true,
..Encryption::default()
};
let refuses = Profile {
require_tls: Some(false),
..Profile::named("plain")
};
assert!(
!wants_encryption(&refuses, &demanded),
"the destination has the last word over the stored default"
);
let silent = Profile {
require_tls: None,
..Profile::named("silent")
};
assert!(wants_encryption(&silent, &demanded));
}
#[test]
fn naming_a_certificate_wins_even_over_a_stated_refusal() {
let contradictory = Profile {
require_tls: Some(false),
ca: Some(PathBuf::from("/etc/ssl/ca.pem")),
..Profile::named("contradictory")
};
assert!(wants_encryption(&contradictory, &Encryption::default()));
}
#[test]
fn each_level_names_exactly_which_checks_it_relaxes() {
assert!(Verification::parse("full").expect("known").is_strict());
let authority_kept = Verification::parse("ca").expect("known");
assert!(!authority_kept.accept_unknown_authority);
assert!(authority_kept.accept_address_mismatch);
let nothing = Verification::parse("none").expect("known");
assert!(nothing.accept_unknown_authority);
assert!(nothing.accept_address_mismatch);
assert_eq!(
Verification::parse("sometimes")
.expect_err("must refuse")
.code(),
"config.unknown_tls_verify"
);
}
#[test]
fn each_trust_source_names_a_different_set_of_authorities() {
let system = RootStore::parse("system").expect("known");
assert!(system.trusts_the_built_in_authorities());
assert!(system.trusts_the_named_authority());
let bundled = RootStore::parse("bundled").expect("known");
assert!(bundled.trusts_the_built_in_authorities());
assert!(!bundled.trusts_the_named_authority());
let file = RootStore::parse("file").expect("known");
assert!(!file.trusts_the_built_in_authorities());
assert!(file.trusts_the_named_authority());
assert_eq!(
RootStore::parse("elsewhere")
.expect_err("must refuse")
.code(),
"config.unknown_root_store"
);
}
#[test]
fn trusting_only_a_named_authority_needs_one_to_be_named() {
let encryption = Encryption {
demanded: true,
root_store: RootStore::File,
..Encryption::default()
};
let failure = channel(&encrypted(), &encryption).expect_err("must refuse");
assert!(matches!(
failure.code(),
"tls.no_authority_named" | "tls.not_available"
));
}
#[test]
fn the_two_checks_are_independent() {
let authority_only = Verification {
accept_unknown_authority: true,
accept_address_mismatch: false,
};
assert!(!authority_only.is_strict());
assert!(Verification::default().is_strict());
}
#[test]
fn a_half_pair_is_refused() {
let profile = Profile {
host: Some("db.example".to_owned()),
client_cert: Some(PathBuf::from("/etc/ssl/client.pem")),
..Profile::named("halfpair")
};
let failure = channel(&profile, &Encryption::default()).expect_err("must refuse");
assert_eq!(failure.category(), crate::error::Category::Config);
assert!(matches!(
failure.code(),
"tls.key_missing" | "tls.not_available"
));
}
#[cfg(not(feature = "tls"))]
#[test]
fn a_build_without_encryption_refuses_and_says_why() {
let failure = channel(&encrypted(), &Encryption::default()).expect_err("must refuse");
assert_eq!(failure.code(), "tls.not_available");
assert!(failure.hint().is_some());
assert!(!failure.is_retryable());
}
#[cfg(feature = "tls")]
#[test]
fn a_build_with_encryption_honours_the_request() {
let options = channel(&encrypted(), &Encryption::default())
.expect("encryption available")
.expect("channel built");
assert!(options.root_certs().is_empty());
assert!(!options.skip_domain_validation());
assert!(!options.accept_invalid_certs());
assert!(
!options.disable_built_in_roots(),
"the ordinary source keeps the authorities this build carries"
);
}
#[cfg(feature = "tls")]
#[test]
fn each_trust_source_reaches_the_driver_differently() {
let with_authority = Profile {
ca: Some(PathBuf::from("/etc/ssl/ca.pem")),
..encrypted()
};
let built = |store| {
channel(
&with_authority,
&Encryption {
demanded: true,
root_store: store,
..Encryption::default()
},
)
.expect("encryption available")
.expect("channel built")
};
let system = built(RootStore::System);
assert!(!system.disable_built_in_roots());
assert_eq!(system.root_certs().len(), 1);
let bundled = built(RootStore::Bundled);
assert!(!bundled.disable_built_in_roots());
assert!(
bundled.root_certs().is_empty(),
"only what this build carries is trusted"
);
let file = built(RootStore::File);
assert!(file.disable_built_in_roots());
assert_eq!(file.root_certs().len(), 1);
}
#[cfg(feature = "tls")]
#[test]
fn each_level_reaches_the_drivers_two_checks() {
let built = |word| {
channel(
&encrypted(),
&Encryption {
demanded: true,
verification: Verification::parse(word).expect("known"),
..Encryption::default()
},
)
.expect("encryption available")
.expect("channel built")
};
let full = built("full");
assert!(!full.accept_invalid_certs());
assert!(!full.skip_domain_validation());
let authority_only = built("ca");
assert!(!authority_only.accept_invalid_certs());
assert!(authority_only.skip_domain_validation());
let nothing = built("none");
assert!(nothing.accept_invalid_certs());
assert!(nothing.skip_domain_validation());
}
}