krabka-security 0.7.0

TLS, SASL, SCRAM, OAuth, and Kerberos security utilities for Krabka
Documentation
//! mTLS principal extraction.
//!
//! From a DER-encoded X.509 client certificate, this module derives the
//! principal name that the broker uses for ACL lookups.
//!
//! Kafka's `DefaultKafkaPrincipalBuilder` uses the cert's Subject
//! Distinguished Name in RFC 2253 format, for example `CN=alice,OU=foo,O=org`,
//! as the principal name. Operators and `KafkaUser` mTLS provisioning pin ACLs
//! by that DN, so Krabka matches it byte-for-byte.

use x509_parser::prelude::{FromDer, X509Certificate};

/// Parse `cert_der` and return the Subject DN in RFC 2253 format.
///
/// This function returns `None` if the bytes do not parse as a valid X.509
/// cert.
// mTLS principal extraction. skip_all keeps the raw `cert_der` bytes out of
// span fields; the derived Subject DN (the principal, non-secret) is recorded
// mid-fn. Returns `Option`, not `Result`, so no `err`.
#[must_use]
#[tracing::instrument(
    level = "debug",
    skip_all,
    fields(mechanism = "mTLS", principal = tracing::field::Empty)
)]
pub fn extract_principal_from_cert(cert_der: &[u8]) -> Option<String> {
    let (_, cert) = X509Certificate::from_der(cert_der).ok()?;
    let dn = cert.subject().to_string();
    tracing::Span::current().record("principal", dn.as_str());
    Some(dn)
}

#[cfg(test)]
mod tests {

    use rustls::pki_types::{CertificateDer, pem::PemObject};

    use super::*;

    #[test]
    fn extracts_subject_dn_from_fixture_client_cert() {
        let pem = include_bytes!("../tests/fixtures/dev_client_cert.pem");
        let mut iter = CertificateDer::pem_slice_iter(pem);
        let cert: CertificateDer<'static> = iter.next().expect("at least one cert").unwrap();
        let dn = extract_principal_from_cert(cert.as_ref()).expect("parse fixture cert");
        // openssl-rendered subject is CN=test-client,OU=integration,O=krabka.
        // x509-parser preserves that order (most-significant first),
        // comma-separated, no spaces. Operators pin this DN verbatim in
        // ACLs and super_users.
        assert2::assert!(dn == "CN=test-client,OU=integration,O=krabka");
    }

    #[test]
    fn malformed_cert_returns_none() {
        for (_name, input) in [
            ("garbage", b"not-a-cert".as_slice()),
            ("empty", b"".as_slice()),
        ] {
            assert2::assert!(extract_principal_from_cert(input).is_none());
        }
    }
}