Skip to main content

domain_status/
models.rs

1//! Application-level data models.
2//!
3//! This module defines data structures used throughout the application:
4//! - `TlsCertificateInfo` - TLS certificate details extracted from connections
5//! - `KeyAlgorithm` - TLS public key algorithm enum
6//!
7//! These models are separate from database models (in `storage::models`) to
8//! maintain a clear separation between application logic and persistence.
9
10use chrono::NaiveDateTime;
11use std::fmt;
12
13/// Public key algorithm used in a TLS certificate.
14///
15/// Eliminates primitive obsession by replacing raw `String` algorithm names
16/// with a type-safe enum. The `Other(String)` variant handles unknown OIDs
17/// that don't map to a recognized algorithm.
18///
19/// Marked `#[non_exhaustive]` so adding new public-key algorithms is not a
20/// semver-breaking change. Downstream `match` expressions must include a
21/// `_ =>` arm (or use the `Other` variant as a catch-all).
22#[derive(Debug, Clone, PartialEq, Eq)]
23#[non_exhaustive]
24pub enum KeyAlgorithm {
25    /// RSA (OID 1.2.840.113549.1.1.1)
26    RSA,
27    /// ECDSA (OID 1.2.840.10045.2.1)
28    ECDSA,
29    /// Ed25519 (OID 1.3.101.112)
30    Ed25519,
31    /// Ed448 (OID 1.3.101.113)
32    Ed448,
33    /// Fallback for unknown OIDs (stores the raw OID string).
34    Other(String),
35}
36
37impl KeyAlgorithm {
38    /// Returns the algorithm name as a string slice.
39    ///
40    /// For known algorithms, returns a static string.
41    /// For `Other`, returns the stored OID string.
42    #[must_use]
43    pub fn as_str(&self) -> &str {
44        match self {
45            KeyAlgorithm::RSA => "RSA",
46            KeyAlgorithm::ECDSA => "ECDSA",
47            KeyAlgorithm::Ed25519 => "Ed25519",
48            KeyAlgorithm::Ed448 => "Ed448",
49            KeyAlgorithm::Other(oid) => oid,
50        }
51    }
52
53    /// Parses a key algorithm from an X.509 OID string.
54    #[must_use]
55    pub fn from_oid(oid_str: &str) -> Self {
56        if oid_str == "1.2.840.113549.1.1.1" {
57            KeyAlgorithm::RSA
58        } else if oid_str == "1.2.840.10045.2.1" {
59            KeyAlgorithm::ECDSA
60        } else if oid_str == "1.3.101.112" {
61            KeyAlgorithm::Ed25519
62        } else if oid_str == "1.3.101.113" {
63            KeyAlgorithm::Ed448
64        } else {
65            KeyAlgorithm::Other(oid_str.to_string())
66        }
67    }
68}
69
70impl fmt::Display for KeyAlgorithm {
71    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
72        f.write_str(self.as_str())
73    }
74}
75
76/// TLS protocol version negotiated during an HTTPS connection.
77///
78/// Eliminates primitive obsession by replacing raw `String` version names
79/// with a type-safe enum. This fixes a subtle bug where the Debug format
80/// of rustls versions (`TLS13`) didn't match the string comparisons in
81/// security analysis (`"TLSv1.3"`), making the weak-TLS check fragile.
82///
83/// Marked `#[non_exhaustive]` so a future TLS 1.4 (or post-quantum protocol)
84/// can be added without breaking downstream callers. The `Unknown` variant
85/// is also available as a catch-all for legacy match arms.
86#[derive(Debug, Clone, Copy, PartialEq, Eq)]
87#[non_exhaustive]
88pub enum TlsVersion {
89    /// TLS 1.0 (insecure)
90    Tls10,
91    /// TLS 1.1 (insecure)
92    Tls11,
93    /// TLS 1.2 (secure)
94    Tls12,
95    /// TLS 1.3 (secure)
96    Tls13,
97    /// SSL 3.0 (insecure)
98    Ssl30,
99    /// Unknown or unrecognized protocol version
100    Unknown,
101}
102
103impl TlsVersion {
104    /// Returns the version name as a string slice.
105    #[must_use]
106    pub fn as_str(&self) -> &'static str {
107        match self {
108            TlsVersion::Tls10 => "TLSv1.0",
109            TlsVersion::Tls11 => "TLSv1.1",
110            TlsVersion::Tls12 => "TLSv1.2",
111            TlsVersion::Tls13 => "TLSv1.3",
112            TlsVersion::Ssl30 => "SSLv3",
113            TlsVersion::Unknown => "Unknown",
114        }
115    }
116}
117
118impl fmt::Display for TlsVersion {
119    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
120        f.write_str(self.as_str())
121    }
122}
123
124/// TLS/SSL certificate information extracted from an HTTPS connection.
125///
126/// Contains all relevant certificate details including version, subject, issuer,
127/// validity period, certificate OIDs (from policies, extended key usage, and extensions),
128/// cipher suite, and key algorithm.
129/// All fields are optional to handle cases where certificate information cannot be extracted.
130///
131/// # Fields
132///
133/// * `tls_version` - TLS protocol version (e.g., "TLSv1.3")
134/// * `subject` - Certificate subject (e.g., "CN=example.com")
135/// * `issuer` - Certificate issuer (e.g., "CN=Let's Encrypt")
136/// * `valid_from` - Certificate validity start date
137/// * `valid_to` - Certificate validity end date
138/// * `oids` - Set of certificate OIDs (includes policy OIDs, extended key usage OIDs, and extension OIDs)
139/// * `cipher_suite` - Negotiated cipher suite (e.g., "`TLS13_AES_256_GCM_SHA384`")
140/// * `key_algorithm` - Public key algorithm
141/// * `subject_alternative_names` - DNS names from the Subject Alternative Name extension (for linking domains sharing certificates)
142/// * `fingerprint_sha256` - SHA-256 hash of the leaf certificate DER (for infrastructure correlation)
143#[derive(Debug, Default)]
144pub struct CertificateInfo {
145    pub tls_version: Option<TlsVersion>,
146    pub subject: Option<String>,
147    pub issuer: Option<String>,
148    pub valid_from: Option<NaiveDateTime>,
149    pub valid_to: Option<NaiveDateTime>,
150    pub oids: Option<std::collections::HashSet<String>>,
151    pub cipher_suite: Option<String>,
152    pub key_algorithm: Option<KeyAlgorithm>,
153    pub subject_alternative_names: Option<Vec<String>>,
154    pub fingerprint_sha256: Option<String>,
155    pub serial_number: Option<String>,
156    pub is_self_signed: Option<bool>,
157    pub is_wildcard: Option<bool>,
158}
159
160#[cfg(test)]
161mod tests {
162    use super::*;
163    use pretty_assertions::assert_eq;
164
165    #[test]
166    fn test_key_algorithm_from_oid_maps_known_algorithms() {
167        assert_eq!(
168            KeyAlgorithm::from_oid("1.2.840.113549.1.1.1"),
169            KeyAlgorithm::RSA
170        );
171        assert_eq!(
172            KeyAlgorithm::from_oid("1.2.840.10045.2.1"),
173            KeyAlgorithm::ECDSA
174        );
175        assert_eq!(KeyAlgorithm::from_oid("1.3.101.112"), KeyAlgorithm::Ed25519);
176        assert_eq!(KeyAlgorithm::from_oid("1.3.101.113"), KeyAlgorithm::Ed448);
177    }
178
179    #[test]
180    fn test_key_algorithm_from_oid_preserves_unknown_value() {
181        assert_eq!(
182            KeyAlgorithm::from_oid("1.2.3.4.5"),
183            KeyAlgorithm::Other("1.2.3.4.5".to_string())
184        );
185        assert_eq!(
186            KeyAlgorithm::Other("1.2.3.4.5".to_string()).to_string(),
187            "1.2.3.4.5"
188        );
189    }
190
191    #[test]
192    fn test_key_algorithm_from_oid_requires_exact_match() {
193        assert_eq!(
194            KeyAlgorithm::from_oid("prefix-1.2.840.113549.1.1.1"),
195            KeyAlgorithm::Other("prefix-1.2.840.113549.1.1.1".to_string())
196        );
197    }
198
199    #[test]
200    fn test_tls_version_display_contract() {
201        assert_eq!(TlsVersion::Tls10.as_str(), "TLSv1.0");
202        assert_eq!(TlsVersion::Tls12.to_string(), "TLSv1.2");
203        assert_eq!(TlsVersion::Tls13.to_string(), "TLSv1.3");
204        assert_eq!(TlsVersion::Ssl30.to_string(), "SSLv3");
205    }
206}