Skip to main content

phoenix_runtime/
tls.rs

1//! Direct rustls TLS listener support.
2
3use std::{io::Cursor, path::Path, sync::Arc, time::Duration};
4
5use rustls::ServerConfig;
6use thiserror::Error;
7
8use crate::{ALPN_HTTP_1_1, ALPN_HTTP_2, DEFAULT_TLS_HANDSHAKE_TIMEOUT, HttpProtocol};
9
10/// Rustls server configuration with Phoenix ALPN and handshake policy.
11#[derive(Clone)]
12pub struct TlsConfig {
13    pub(crate) server_config: Arc<ServerConfig>,
14    pub(crate) handshake_timeout: Duration,
15}
16
17impl TlsConfig {
18    /// Load a certificate chain and private key from PEM bytes.
19    ///
20    /// # Errors
21    ///
22    /// Returns an error for unreadable PEM, missing material, or an invalid key/certificate pair.
23    pub fn from_pem(
24        certificate_pem: &[u8],
25        private_key_pem: &[u8],
26    ) -> Result<Self, TlsConfigError> {
27        let certificates = rustls_pemfile::certs(&mut Cursor::new(certificate_pem))
28            .collect::<Result<Vec<_>, _>>()?;
29        if certificates.is_empty() {
30            return Err(TlsConfigError::MissingCertificate);
31        }
32        let private_key = rustls_pemfile::private_key(&mut Cursor::new(private_key_pem))?
33            .ok_or(TlsConfigError::MissingPrivateKey)?;
34        let server_config = ServerConfig::builder()
35            .with_no_client_auth()
36            .with_single_cert(certificates, private_key)?;
37        Ok(Self::from_server_config(server_config))
38    }
39
40    /// Load PEM material from local files during application startup.
41    ///
42    /// # Errors
43    ///
44    /// Returns an error when either file cannot be read or parsed.
45    pub fn from_files(
46        certificate_path: impl AsRef<Path>,
47        private_key_path: impl AsRef<Path>,
48    ) -> Result<Self, TlsConfigError> {
49        let certificate_pem = std::fs::read(certificate_path)?;
50        let private_key_pem = std::fs::read(private_key_path)?;
51        Self::from_pem(&certificate_pem, &private_key_pem)
52    }
53
54    /// Wrap an advanced rustls configuration. Phoenix supplies HTTP ALPN defaults when absent.
55    #[must_use]
56    pub fn from_server_config(mut server_config: ServerConfig) -> Self {
57        if server_config.alpn_protocols.is_empty() {
58            server_config.alpn_protocols = vec![ALPN_HTTP_2.to_vec(), ALPN_HTTP_1_1.to_vec()];
59        }
60        Self {
61            server_config: Arc::new(server_config),
62            handshake_timeout: DEFAULT_TLS_HANDSHAKE_TIMEOUT,
63        }
64    }
65
66    /// Set a hard deadline for completing the TLS handshake.
67    ///
68    /// # Errors
69    ///
70    /// Returns an error when the timeout is zero.
71    pub fn handshake_timeout(mut self, timeout: Duration) -> Result<Self, TlsConfigError> {
72        if timeout.is_zero() {
73            return Err(TlsConfigError::InvalidHandshakeTimeout);
74        }
75        self.handshake_timeout = timeout;
76        Ok(self)
77    }
78
79    #[must_use]
80    pub fn alpn_protocols(&self) -> &[Vec<u8>] {
81        &self.server_config.alpn_protocols
82    }
83
84    pub(crate) fn for_http_protocol(&self, protocol: HttpProtocol) -> Self {
85        let mut server_config = (*self.server_config).clone();
86        server_config.alpn_protocols = match protocol {
87            HttpProtocol::Auto => vec![ALPN_HTTP_2.to_vec(), ALPN_HTTP_1_1.to_vec()],
88            HttpProtocol::Http1Only => vec![ALPN_HTTP_1_1.to_vec()],
89            HttpProtocol::Http2Only => vec![ALPN_HTTP_2.to_vec()],
90        };
91        Self {
92            server_config: Arc::new(server_config),
93            handshake_timeout: self.handshake_timeout,
94        }
95    }
96}
97
98impl std::fmt::Debug for TlsConfig {
99    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
100        formatter
101            .debug_struct("TlsConfig")
102            .field("alpn_protocols", &self.server_config.alpn_protocols)
103            .field("handshake_timeout", &self.handshake_timeout)
104            .finish_non_exhaustive()
105    }
106}
107
108#[derive(Debug, Error)]
109pub enum TlsConfigError {
110    #[error("TLS PEM I/O error: {0}")]
111    Io(#[from] std::io::Error),
112    #[error("TLS certificate PEM does not contain a certificate")]
113    MissingCertificate,
114    #[error("TLS private-key PEM does not contain a supported private key")]
115    MissingPrivateKey,
116    #[error("TLS certificate or private key is invalid: {0}")]
117    Rustls(#[from] rustls::Error),
118    #[error("TLS handshake timeout must be greater than zero")]
119    InvalidHandshakeTimeout,
120}
121