Skip to main content

fraiseql_server/
tls.rs

1//! TLS/SSL server configuration and enforcement.
2//!
3//! This module handles:
4//! - Loading and validating TLS certificates and keys
5//! - Building TLS acceptance profiles for servers
6//! - Configuring mTLS (client certificate requirements)
7//! - Database connection TLS settings
8//! - Per-connection TLS enforcement using the `TlsEnforcer`
9
10use std::{fmt::Write as _, path::Path, sync::Arc};
11
12use fraiseql_core::security::{TlsConfig, TlsEnforcer, TlsVersion};
13use rustls::{ServerConfig, pki_types::CertificateDer};
14use rustls_pemfile::Item;
15use tracing::info;
16
17use crate::{
18    Result, ServerError,
19    server_config::{DatabaseTlsConfig, TlsServerConfig},
20};
21
22/// TLS server setup and enforcement.
23pub struct TlsSetup {
24    /// TLS enforcer for validating connections.
25    enforcer: TlsEnforcer,
26
27    /// Server TLS configuration.
28    config: Option<TlsServerConfig>,
29
30    /// Database TLS configuration.
31    db_config: Option<DatabaseTlsConfig>,
32}
33
34impl TlsSetup {
35    /// Create new TLS setup from server configuration.
36    ///
37    /// # Errors
38    ///
39    /// Returns error if:
40    /// - TLS is enabled but certificate/key files cannot be read
41    /// - TLS configuration is invalid
42    pub fn new(
43        tls_config: Option<TlsServerConfig>,
44        db_tls_config: Option<DatabaseTlsConfig>,
45    ) -> Result<Self> {
46        // Create the enforcer based on configuration
47        let enforcer = if let Some(ref tls) = tls_config {
48            if tls.enabled {
49                Self::create_enforcer(tls)?
50            } else {
51                TlsEnforcer::permissive()
52            }
53        } else {
54            TlsEnforcer::permissive()
55        };
56
57        Ok(Self {
58            enforcer,
59            config: tls_config,
60            db_config: db_tls_config,
61        })
62    }
63
64    /// Create a TLS enforcer from configuration.
65    fn create_enforcer(config: &TlsServerConfig) -> Result<TlsEnforcer> {
66        // Parse minimum TLS version
67        let min_version = match config.min_version.as_str() {
68            "1.2" => TlsVersion::V1_2,
69            "1.3" => TlsVersion::V1_3,
70            other => {
71                return Err(ServerError::ConfigError(format!(
72                    "Invalid TLS minimum version: {}",
73                    other
74                )));
75            },
76        };
77
78        // Create TLS configuration
79        let tls_config = TlsConfig {
80            tls_required: true,
81            mtls_required: config.require_client_cert,
82            min_version,
83        };
84
85        info!(
86            tls_enabled = true,
87            require_mtls = config.require_client_cert,
88            min_version = %min_version,
89            "TLS configuration loaded"
90        );
91
92        Ok(TlsEnforcer::from_config(tls_config))
93    }
94
95    /// Get the TLS enforcer.
96    #[must_use]
97    pub const fn enforcer(&self) -> &TlsEnforcer {
98        &self.enforcer
99    }
100
101    /// Get the server TLS configuration.
102    #[must_use]
103    pub const fn config(&self) -> &Option<TlsServerConfig> {
104        &self.config
105    }
106
107    /// Get the database TLS configuration.
108    #[must_use]
109    pub const fn db_config(&self) -> &Option<DatabaseTlsConfig> {
110        &self.db_config
111    }
112
113    /// Check if TLS is enabled for server.
114    #[must_use]
115    pub fn is_tls_enabled(&self) -> bool {
116        self.config.as_ref().is_some_and(|c| c.enabled)
117    }
118
119    /// Check if mTLS is required.
120    #[must_use]
121    pub fn is_mtls_required(&self) -> bool {
122        self.config.as_ref().is_some_and(|c| c.enabled && c.require_client_cert)
123    }
124
125    /// Get the certificate path.
126    #[must_use]
127    pub fn cert_path(&self) -> Option<&Path> {
128        self.config.as_ref().map(|c| c.cert_path.as_path())
129    }
130
131    /// Get the key path.
132    #[must_use]
133    pub fn key_path(&self) -> Option<&Path> {
134        self.config.as_ref().map(|c| c.key_path.as_path())
135    }
136
137    /// Get the client CA path (for mTLS).
138    #[must_use]
139    pub fn client_ca_path(&self) -> Option<&Path> {
140        self.config
141            .as_ref()
142            .and_then(|c| c.client_ca_path.as_ref())
143            .map(|p| p.as_path())
144    }
145
146    /// Get PostgreSQL SSL mode for database connections.
147    #[must_use]
148    pub fn postgres_ssl_mode(&self) -> &str {
149        self.db_config.as_ref().map_or("prefer", |c| c.postgres_ssl_mode.as_str())
150    }
151
152    /// Check if Redis TLS is enabled.
153    #[must_use]
154    pub fn redis_ssl_enabled(&self) -> bool {
155        self.db_config.as_ref().is_some_and(|c| c.redis_ssl)
156    }
157
158    /// Check if `ClickHouse` HTTPS is enabled.
159    #[must_use]
160    pub fn clickhouse_https_enabled(&self) -> bool {
161        self.db_config.as_ref().is_some_and(|c| c.clickhouse_https)
162    }
163
164    /// Check if Elasticsearch HTTPS is enabled.
165    #[must_use]
166    pub fn elasticsearch_https_enabled(&self) -> bool {
167        self.db_config.as_ref().is_some_and(|c| c.elasticsearch_https)
168    }
169
170    /// Check if certificate verification is enabled for databases.
171    #[must_use]
172    pub fn verify_certificates(&self) -> bool {
173        self.db_config.as_ref().is_none_or(|c| c.verify_certificates)
174    }
175
176    /// Get the CA bundle path for verifying database certificates.
177    #[must_use]
178    pub fn ca_bundle_path(&self) -> Option<&Path> {
179        self.db_config
180            .as_ref()
181            .and_then(|c| c.ca_bundle_path.as_ref())
182            .map(|p| p.as_path())
183    }
184
185    /// Get database URL with TLS applied (for PostgreSQL).
186    #[must_use]
187    pub fn apply_postgres_tls(&self, db_url: &str) -> String {
188        let mut url = db_url.to_string();
189
190        // Parse SSL mode into URL parameter
191        let ssl_mode = self.postgres_ssl_mode();
192        if !ssl_mode.is_empty() && ssl_mode != "prefer" {
193            // Add or update sslmode parameter
194            if url.contains('?') {
195                let _ = write!(url, "&sslmode={ssl_mode}");
196            } else {
197                let _ = write!(url, "?sslmode={ssl_mode}");
198            }
199        }
200
201        url
202    }
203
204    /// Get Redis URL with TLS applied.
205    #[must_use]
206    pub fn apply_redis_tls(&self, redis_url: &str) -> String {
207        if self.redis_ssl_enabled() {
208            // Replace redis:// with rediss://
209            redis_url.replace("redis://", "rediss://")
210        } else {
211            redis_url.to_string()
212        }
213    }
214
215    /// Get `ClickHouse` URL with TLS applied.
216    #[must_use]
217    pub fn apply_clickhouse_tls(&self, ch_url: &str) -> String {
218        if self.clickhouse_https_enabled() {
219            // Replace http:// with https://
220            ch_url.replace("http://", "https://")
221        } else {
222            ch_url.to_string()
223        }
224    }
225
226    /// Get Elasticsearch URL with TLS applied.
227    #[must_use]
228    pub fn apply_elasticsearch_tls(&self, es_url: &str) -> String {
229        if self.elasticsearch_https_enabled() {
230            // Replace http:// with https://
231            es_url.replace("http://", "https://")
232        } else {
233            es_url.to_string()
234        }
235    }
236
237    /// Load certificates from PEM file.
238    fn load_certificates(path: &Path) -> Result<Vec<CertificateDer<'static>>> {
239        let cert_file = std::fs::File::open(path).map_err(|e| {
240            ServerError::ConfigError(format!(
241                "Failed to open certificate file {}: {}",
242                path.display(),
243                e
244            ))
245        })?;
246
247        let mut reader = std::io::BufReader::new(cert_file);
248        let mut certificates = Vec::new();
249
250        loop {
251            match rustls_pemfile::read_one(&mut reader).map_err(|e| {
252                ServerError::ConfigError(format!("Failed to parse certificate: {}", e))
253            })? {
254                Some(Item::X509Certificate(cert)) => certificates.push(cert),
255                Some(_) => {}, // Skip other items
256                None => break,
257            }
258        }
259
260        if certificates.is_empty() {
261            return Err(ServerError::ConfigError(
262                "No certificates found in certificate file".to_string(),
263            ));
264        }
265
266        Ok(certificates)
267    }
268
269    /// Load private key from PEM file.
270    fn load_private_key(path: &Path) -> Result<rustls::pki_types::PrivateKeyDer<'static>> {
271        let key_file = std::fs::File::open(path).map_err(|e| {
272            ServerError::ConfigError(format!("Failed to open key file {}: {}", path.display(), e))
273        })?;
274
275        let mut reader = std::io::BufReader::new(key_file);
276
277        loop {
278            match rustls_pemfile::read_one(&mut reader).map_err(|e| {
279                ServerError::ConfigError(format!("Failed to parse private key: {}", e))
280            })? {
281                Some(Item::Pkcs8Key(key)) => return Ok(key.into()),
282                Some(Item::Pkcs1Key(key)) => return Ok(key.into()),
283                Some(Item::Sec1Key(key)) => return Ok(key.into()),
284                Some(_) => {}, // Skip other items
285                None => break,
286            }
287        }
288
289        Err(ServerError::ConfigError("No private key found in key file".to_string()))
290    }
291
292    /// Create a rustls `ServerConfig` for TLS.
293    ///
294    /// # Errors
295    ///
296    /// Returns error if:
297    /// - Certificate or key files cannot be read
298    /// - Certificate or key format is invalid
299    pub fn create_rustls_config(&self) -> Result<Arc<ServerConfig>> {
300        let (cert_path, key_path) = match self.config.as_ref() {
301            Some(c) if c.enabled => (&c.cert_path, &c.key_path),
302            _ => return Err(ServerError::ConfigError("TLS not enabled".to_string())),
303        };
304
305        info!(
306            cert_path = %cert_path.display(),
307            key_path = %key_path.display(),
308            "Loading TLS certificates"
309        );
310
311        let certs = Self::load_certificates(cert_path)?;
312        let key = Self::load_private_key(key_path)?;
313
314        let server_config = ServerConfig::builder()
315            .with_no_client_auth()
316            .with_single_cert(certs, key)
317            .map_err(|e| ServerError::ConfigError(format!("Failed to build TLS config: {}", e)))?;
318
319        Ok(Arc::new(server_config))
320    }
321}