use std::sync::Arc;
use std::time::{Duration, SystemTime};
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Security {
tls_version: Option<Arc<str>>,
cipher_suite: Option<Arc<str>>,
alpn: Vec<Arc<str>>,
certificate: Option<CertificateInfo>,
}
impl Security {
pub fn new() -> Self {
Self {
tls_version: None,
cipher_suite: None,
alpn: Vec::new(),
certificate: None,
}
}
pub fn tls_version(&self) -> Option<&str> {
self.tls_version.as_deref()
}
pub fn cipher_suite(&self) -> Option<&str> {
self.cipher_suite.as_deref()
}
pub fn alpn(&self) -> &[Arc<str>] {
&self.alpn
}
pub fn certificate(&self) -> Option<&CertificateInfo> {
self.certificate.as_ref()
}
pub fn with_tls_version(mut self, version: impl Into<Arc<str>>) -> Self {
self.tls_version = Some(version.into());
self
}
pub fn with_cipher_suite(mut self, cipher: impl Into<Arc<str>>) -> Self {
self.cipher_suite = Some(cipher.into());
self
}
pub fn add_alpn(&mut self, protocol: impl Into<Arc<str>>) {
let protocol = protocol.into();
if !self.alpn.contains(&protocol) {
self.alpn.push(protocol);
}
}
pub fn with_alpn(mut self, protocol: impl Into<Arc<str>>) -> Self {
self.add_alpn(protocol);
self
}
pub fn with_certificate(mut self, cert: CertificateInfo) -> Self {
self.certificate = Some(cert);
self
}
pub fn merge(&mut self, other: Security) {
if self.tls_version.is_none() {
self.tls_version = other.tls_version;
}
if self.cipher_suite.is_none() {
self.cipher_suite = other.cipher_suite;
}
if self.certificate.is_none() {
self.certificate = other.certificate;
}
for protocol in other.alpn {
if !self.alpn.contains(&protocol) {
self.alpn.push(protocol);
}
}
}
pub fn is_cert_valid(&self) -> bool {
self.is_cert_valid_at(SystemTime::now())
}
pub fn is_cert_valid_at(&self, target_time: SystemTime) -> bool {
self.certificate
.as_ref()
.is_some_and(|c| target_time >= c.validity_start() && target_time <= c.validity_end())
}
pub fn is_cert_expiring(&self, threshold: Duration) -> bool {
self.is_cert_expiring_at(threshold, SystemTime::now())
}
pub fn is_cert_expiring_at(&self, threshold: Duration, at: SystemTime) -> bool {
self.certificate.as_ref().is_some_and(|c| {
if at < c.validity_start() || at > c.validity_end() {
return false;
}
c.validity_end() < at + threshold
})
}
}
impl Default for Security {
fn default() -> Self {
Self::new()
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct CertificateInfo {
common_name: Arc<str>,
sans: Vec<Arc<str>>,
issuer: Arc<str>,
validity_start: SystemTime,
validity_end: SystemTime,
pubkey_type: Arc<str>,
pubkey_bits: u32,
fingerprint_sha256: Arc<str>,
}
impl CertificateInfo {
pub fn new(
common_name: impl Into<Arc<str>>,
issuer: impl Into<Arc<str>>,
validity_start: SystemTime,
validity_end: SystemTime,
fingerprint_sha256: impl Into<Arc<str>>,
) -> Self {
Self {
common_name: common_name.into(),
sans: Vec::new(),
issuer: issuer.into(),
validity_start,
validity_end,
pubkey_type: Arc::from("unknown"),
pubkey_bits: 0,
fingerprint_sha256: fingerprint_sha256.into(),
}
}
pub fn with_sans(mut self, sans: impl IntoIterator<Item = Arc<str>>) -> Self {
self.sans = sans.into_iter().collect();
self
}
pub fn with_public_key(mut self, kind: impl Into<Arc<str>>, bits: u32) -> Self {
self.pubkey_type = kind.into();
self.pubkey_bits = bits;
self
}
pub fn common_name(&self) -> &str {
&self.common_name
}
pub fn sans(&self) -> &[Arc<str>] {
&self.sans
}
pub fn issuer(&self) -> &str {
&self.issuer
}
pub fn validity_start(&self) -> SystemTime {
self.validity_start
}
pub fn validity_end(&self) -> SystemTime {
self.validity_end
}
pub fn pubkey_type(&self) -> &str {
&self.pubkey_type
}
pub fn pubkey_bits(&self) -> u32 {
self.pubkey_bits
}
pub fn fingerprint_sha256(&self) -> &str {
&self.fingerprint_sha256
}
}
#[cfg(test)]
mod tests {
use super::*;
fn mock_cert(start_offset: i64, end_offset: i64) -> CertificateInfo {
let now = SystemTime::now();
let start = if start_offset < 0 {
now - Duration::from_secs(start_offset.unsigned_abs())
} else {
now + Duration::from_secs(start_offset as u64)
};
let end = if end_offset < 0 {
now - Duration::from_secs(end_offset.unsigned_abs())
} else {
now + Duration::from_secs(end_offset as u64)
};
CertificateInfo::new("test.local", "Local CA", start, end, "deadbeef")
.with_sans([Arc::from("*.test.local")])
.with_public_key("RSA", 2048)
}
#[test]
fn a_record_carries_what_the_handshake_agreed() {
let sec = Security::new()
.with_tls_version("TLSv1.3")
.with_cipher_suite("TLS_AES_256_GCM_SHA384")
.with_alpn("h2")
.with_alpn("http/1.1");
assert_eq!(sec.tls_version(), Some("TLSv1.3"));
assert_eq!(sec.cipher_suite(), Some("TLS_AES_256_GCM_SHA384"));
assert_eq!(sec.alpn().len(), 2);
}
#[test]
fn a_merge_fills_the_gaps_without_displacing_what_is_recorded() {
let mut s1 = Security::new()
.with_tls_version("TLSv1.2")
.with_alpn("http/1.1");
let s2 = Security::new()
.with_cipher_suite("AES128-GCM")
.with_alpn("h2")
.with_alpn("http/1.1");
s1.merge(s2);
assert_eq!(s1.tls_version(), Some("TLSv1.2"));
assert_eq!(s1.cipher_suite(), Some("AES128-GCM"));
assert_eq!(s1.alpn().len(), 2);
assert!(s1.alpn().iter().any(|p| &**p == "h2"));
}
#[test]
fn validity_and_expiry_are_both_answerable_at_a_caller_chosen_time() {
let day = Duration::from_secs(86_400);
let scanned_at = SystemTime::UNIX_EPOCH + day * 365;
let security = Security::new().with_certificate(CertificateInfo::new(
"test.local",
"Local CA",
scanned_at - day * 30,
scanned_at + day * 10,
"deadbeef",
));
assert!(security.is_cert_valid_at(scanned_at));
assert!(
security.is_cert_expiring_at(day * 30, scanned_at),
"ten days left"
);
assert!(!security.is_cert_expiring_at(day * 5, scanned_at));
let read_at = scanned_at + day * 365;
assert!(!security.is_cert_valid_at(read_at));
assert!(!security.is_cert_expiring_at(day * 30, read_at));
}
#[test]
fn an_expired_certificate_is_not_reported_as_one_about_to_expire() {
let valid_cert = mock_cert(-864000, 864000);
let sec_valid = Security::new().with_certificate(valid_cert);
assert!(sec_valid.is_cert_valid());
assert!(!sec_valid.is_cert_expiring(Duration::from_secs(86400 * 5)));
assert!(sec_valid.is_cert_expiring(Duration::from_secs(86400 * 15)));
let expired_cert = mock_cert(-864000, -432000);
let sec_expired = Security::new().with_certificate(expired_cert);
assert!(!sec_expired.is_cert_valid());
assert!(!sec_expired.is_cert_expiring(Duration::from_secs(86400 * 30)));
let future_cert = mock_cert(86400, 864000);
let sec_future = Security::new().with_certificate(future_cert);
assert!(!sec_future.is_cert_valid());
}
}