use lapin::tcp::{OwnedIdentity, OwnedTLSConfig};
use lapin::{Connection, ConnectionProperties};
use crate::error::AxiamError;
#[derive(Debug, Clone, Default)]
pub struct AmqpTlsConfig {
pub ca_cert_pem: Option<String>,
pub client_cert_pem: Option<Vec<u8>>,
pub client_key_pem: Option<Vec<u8>>,
}
impl AmqpTlsConfig {
pub fn validate(&self) -> Result<(), AxiamError> {
match (&self.client_cert_pem, &self.client_key_pem) {
(Some(_), None) => Err(AxiamError::network(
"AMQP TLS: a client certificate was supplied without its key — half a \
client identity cannot authenticate, and connecting anyway would \
silently drop the mutual half of mutual TLS (CONTRACT.md §8b rule 3). \
Set both or neither.",
)),
(None, Some(_)) => Err(AxiamError::network(
"AMQP TLS: a client key was supplied without its certificate; set both \
or neither (CONTRACT.md §8b rule 3).",
)),
_ => Ok(()),
}
}
pub fn is_empty(&self) -> bool {
self.ca_cert_pem.is_none()
&& self.client_cert_pem.is_none()
&& self.client_key_pem.is_none()
}
fn to_owned_tls_config(&self) -> OwnedTLSConfig {
let identity = match (&self.client_cert_pem, &self.client_key_pem) {
(Some(cert), Some(key)) => Some(OwnedIdentity::PKCS8 {
pem: cert.clone(),
key: key.clone(),
}),
_ => None,
};
OwnedTLSConfig {
identity,
cert_chain: self.ca_cert_pem.clone(),
}
}
}
pub fn ensure_amqps(amqp_url: &str) -> Result<(), AxiamError> {
if amqp_url.trim().to_ascii_lowercase().starts_with("amqps://") {
return Ok(());
}
Err(AxiamError::network(format!(
"AMQP url must use the encrypted `amqps://` scheme (got {amqp_url:?}). Broker \
traffic carries authorization requests, audit events and reactor replies across \
a trust boundary, and HMAC signing gives them authenticity and replay protection \
but NOT confidentiality. There is no plaintext fallback and no verification-skip \
switch (CONTRACT.md §8b rules 1, 4 and 5); supply a private broker CA via \
`AmqpTlsConfig::ca_cert_pem` if the broker certificate is not publicly issued."
)))
}
pub async fn connect_amqps(amqp_url: &str, tls: &AmqpTlsConfig) -> Result<Connection, AxiamError> {
ensure_amqps(amqp_url)?;
tls.validate()?;
let runtime = lapin::runtime::default_runtime()
.map_err(|e| AxiamError::network(format!("failed to resolve the AMQP runtime: {e}")))?;
Connection::connect_with_config(
amqp_url,
ConnectionProperties::default(),
tls.to_owned_tls_config(),
runtime,
)
.await
.map_err(|e| AxiamError::network(format!("failed to connect to AMQP broker: {e}")))
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn amqps_is_accepted_case_insensitively() {
ensure_amqps("amqps://broker.example.com:5671").expect("amqps is the required scheme");
ensure_amqps("AMQPS://broker.example.com:5671").expect("scheme match is case-insensitive");
}
#[test]
fn plaintext_is_refused_including_on_loopback() {
for url in [
"amqp://broker.example.com:5672",
"amqp://localhost:5672",
"amqp://127.0.0.1:5672",
] {
let err = ensure_amqps(url).expect_err("plaintext must be refused");
assert!(
format!("{err}").contains("amqps://"),
"the error must name the scheme to use, got: {err}"
);
}
}
#[test]
fn an_unparseable_url_is_refused_rather_than_waved_through() {
for url in ["", " ", "not a url at all", "://broker", "amqps:/broker"] {
assert!(
ensure_amqps(url).is_err(),
"an unparseable url ({url:?}) must fail closed"
);
}
}
#[test]
fn an_amqps_prefixed_impostor_is_not_amqps() {
assert!(ensure_amqps("amqpsomething://broker:5671").is_err());
}
#[test]
fn tls_material_is_optional_but_must_be_internally_consistent() {
assert!(AmqpTlsConfig::default().validate().is_ok());
assert!(AmqpTlsConfig::default().is_empty());
let ca_only = AmqpTlsConfig {
ca_cert_pem: Some("-----BEGIN CERTIFICATE-----".into()),
..Default::default()
};
ca_only
.validate()
.expect("a CA bundle alone is the common private-CA case (rule 2)");
assert!(!ca_only.is_empty());
let cert_only = AmqpTlsConfig {
client_cert_pem: Some(b"cert".to_vec()),
..Default::default()
};
let err = cert_only
.validate()
.expect_err("half a client identity must fail closed");
assert!(format!("{err}").contains("key"), "got: {err}");
let key_only = AmqpTlsConfig {
client_key_pem: Some(b"key".to_vec()),
..Default::default()
};
assert!(key_only.validate().is_err(), "…and so must the mirror case");
}
#[test]
fn there_is_no_verification_skip_option() {
let rendered = format!("{:?}", AmqpTlsConfig::default()).to_ascii_lowercase();
for forbidden in ["verify", "insecure", "skip", "danger", "plaintext"] {
assert!(
!rendered.contains(forbidden),
"AmqpTlsConfig must not grow a {forbidden:?}-shaped field: a \
verification-skip switch travels from a dev compose file into \
production and turns TLS into an expensive no-op"
);
}
}
#[test]
fn tls_material_reaches_lapins_owned_config() {
let cfg = AmqpTlsConfig {
ca_cert_pem: Some("ca-pem".into()),
client_cert_pem: Some(b"cert-pem".to_vec()),
client_key_pem: Some(b"key-pem".to_vec()),
};
let owned = cfg.to_owned_tls_config();
assert_eq!(owned.cert_chain.as_deref(), Some("ca-pem"));
match owned.identity {
Some(OwnedIdentity::PKCS8 { pem, key }) => {
assert_eq!(pem, b"cert-pem".to_vec());
assert_eq!(key, b"key-pem".to_vec());
}
other => panic!("expected a PKCS8 client identity, got {other:?}"),
}
}
}