ctb_io_webui/
tls_rustls_vendored.rs1use axum::BoxError;
58use ctb_utilities::get_embedded_asset;
59use include_dir::{Dir, include_dir};
60use rustls::ServerConfig;
61use rustls_pki_types::pem::PemObject;
62use rustls_pki_types::{CertificateDer, PrivateKeyDer};
63use std::{io, path::Path};
64
65pub use axum_server::tls_rustls::RustlsConfig;
66
67static TLS_RUSTLS_VENDORED_DATA_DIR: Dir =
68 include_dir!("$CARGO_MANIFEST_DIR/tls_rustls_vendored");
69
70pub(crate) fn get_tls_rustls_vendored_data(key: &str) -> Option<Vec<u8>> {
71 get_embedded_asset(&TLS_RUSTLS_VENDORED_DATA_DIR, key)
72}
73
74fn io_other<E: Into<BoxError>>(error: E) -> io::Error {
75 io::Error::other(error)
76}
77
78fn config_from_der(
79 cert: Vec<Vec<u8>>,
80 key: Vec<u8>,
81) -> io::Result<ServerConfig> {
82 let cert = cert.into_iter().map(CertificateDer::from).collect();
83 let key = PrivateKeyDer::try_from(key).map_err(io_other)?;
84
85 let mut config = ServerConfig::builder()
86 .with_no_client_auth()
87 .with_single_cert(cert, key)
88 .map_err(io_other)?;
89
90 config.alpn_protocols = vec![b"h2".to_vec(), b"http/1.1".to_vec()];
91
92 Ok(config)
93}
94
95fn config_from_pem(cert: Vec<u8>, key: Vec<u8>) -> io::Result<ServerConfig> {
96 der_from_pem(cert, key)
97 .and_then(|(cert_der, key_der)| config_from_der(cert_der, key_der))
98}
99
100pub(crate) fn typed_der_from_pem(
101 cert: Vec<u8>,
102 key: Vec<u8>,
103) -> io::Result<(Vec<CertificateDer<'static>>, PrivateKeyDer<'static>)> {
104 let cert: Vec<CertificateDer<'static>> =
105 CertificateDer::pem_slice_iter(&cert)
106 .collect::<Result<Vec<_>, _>>()
107 .map_err(|_| io_other("failed to parse certificate"))?;
108
109 let mut key_result: Result<PrivateKeyDer<'static>, io::Error> =
110 Err(io_other("The private key file contained no keys"));
111
112 for item in rustls_pki_types::pem::PemObject::pem_slice_iter(&key) {
114 let key: Result<PrivateKeyDer<'static>, io::Error> =
115 item.map_err(|_| io_other("failed to parse PEM"));
116
117 match key_result {
118 Ok(_) => {
120 if key.is_ok() {
122 return Err(io_other(
123 "The private key file containsed multiple keys (it must only contain one)",
124 ));
125 }
126 }
127 Err(_) => key_result = key,
131 }
132 }
133
134 let key = key_result?;
135
136 Ok((cert, key))
137}
138
139pub(crate) fn der_from_pem(
140 cert: Vec<u8>,
141 key: Vec<u8>,
142) -> io::Result<(Vec<Vec<u8>>, Vec<u8>)> {
143 let (cert, key) = typed_der_from_pem(cert, key)?;
144 let cert_der: Vec<Vec<u8>> = cert.into_iter().map(|c| c.to_vec()).collect();
145 let key_der = key.secret_der().to_vec();
146
147 Ok((cert_der, key_der))
148}
149
150async fn config_from_pem_file(
151 cert: impl AsRef<Path>,
152 key: impl AsRef<Path>,
153) -> io::Result<ServerConfig> {
154 let cert = fs_err::tokio::read(cert.as_ref()).await?;
155 let key = fs_err::tokio::read(key.as_ref()).await?;
156
157 config_from_pem(cert, key)
158}
159
160async fn config_from_pem_chain_file(
161 cert: impl AsRef<Path>,
162 chain: impl AsRef<Path>,
163) -> io::Result<ServerConfig> {
164 let cert = fs_err::tokio::read(cert.as_ref()).await?;
165 let cert = CertificateDer::pem_slice_iter(&cert)
166 .collect::<Result<Vec<_>, _>>()
167 .map_err(|_| io_other("failed to parse certificate"))?;
168 let key = fs_err::tokio::read(chain.as_ref()).await?;
169 let key_cert: PrivateKeyDer = PrivateKeyDer::from_pem_slice(&key)
170 .map_err(|_| io_other("could not parse pem file"))?;
171
172 ServerConfig::builder()
173 .with_no_client_auth()
174 .with_single_cert(cert, key_cert)
175 .map_err(|_| io_other("invalid certificate"))
176}
177
178#[cfg(test)]
179#[allow(
180 clippy::panic,
181 clippy::expect_used,
182 clippy::unwrap_used,
183 clippy::unwrap_in_result,
184 clippy::panic_in_result_fn,
185 clippy::indexing_slicing,
186 clippy::arithmetic_side_effects,
187 reason = "Standard repository test boilerplate"
188)]
189mod tests {
190 use super::*;
191 use crate::anyhow;
192 use std::io;
193
194 fn fixtures() -> anyhow::Result<tempfile::TempDir> {
195 let dir = tempfile::TempDir::new()?;
196 for filename in ["cert.pem", "key.pem"] {
197 let bytes =
198 get_tls_rustls_vendored_data(&format!("fixtures/{filename}"))
199 .ok_or_else(|| {
200 anyhow::anyhow!("Missing embedded TLS fixture: {filename}")
201 })?;
202 std::fs::write(dir.path().join(filename), bytes)?;
203 }
204 Ok(dir)
205 }
206
207 #[crate::ctb_test("tokio")]
208 async fn from_pem_file_not_found() -> anyhow::Result<()> {
209 let dir = fixtures()?;
210 let missing = dir.path().join("missing.pem");
211 let err =
212 RustlsConfig::from_pem_file(&missing, dir.path().join("key.pem"))
213 .await
214 .unwrap_err();
215 assert_eq!(err.kind(), io::ErrorKind::NotFound);
216 assert!(
217 err.to_string().replace('\\', "/").starts_with(
218 &format!("failed to read from file `{}`", missing.display())
219 .replace('\\', "/")
220 )
221 );
222
223 let err =
224 RustlsConfig::from_pem_file(dir.path().join("cert.pem"), &missing)
225 .await
226 .unwrap_err();
227 assert_eq!(err.kind(), io::ErrorKind::NotFound);
228 assert!(
229 err.to_string().replace('\\', "/").starts_with(
230 &format!("failed to read from file `{}`", missing.display())
231 .replace('\\', "/")
232 )
233 );
234 Ok(())
235 }
236
237 #[crate::ctb_test("tokio")]
238 async fn from_pem_file_chain_file_not_found() -> anyhow::Result<()> {
239 let dir = fixtures()?;
240 let missing = dir.path().join("missing.pem");
241 let err = RustlsConfig::from_pem_chain_file(
242 &missing,
243 dir.path().join("key.pem"),
244 )
245 .await
246 .unwrap_err();
247 assert_eq!(err.kind(), io::ErrorKind::NotFound);
248 assert!(
249 err.to_string().replace('\\', "/").starts_with(
250 &format!("failed to read from file `{}`", missing.display())
251 .replace('\\', "/")
252 )
253 );
254
255 let err = RustlsConfig::from_pem_chain_file(
256 dir.path().join("cert.pem"),
257 &missing,
258 )
259 .await
260 .unwrap_err();
261 assert_eq!(err.kind(), io::ErrorKind::NotFound);
262 assert!(
263 err.to_string().replace('\\', "/").starts_with(
264 &format!("failed to read from file `{}`", missing.display())
265 .replace('\\', "/")
266 )
267 );
268 Ok(())
269 }
270
271 #[crate::ctb_test("tokio")]
272 async fn from_pem_files_valid() -> anyhow::Result<()> {
273 let dir = fixtures()?;
274 let cert = dir.path().join("cert.pem");
275 let key = dir.path().join("key.pem");
276 RustlsConfig::from_pem_file(&cert, &key).await?;
277 RustlsConfig::from_pem_chain_file(&cert, &key).await?;
278 Ok(())
279 }
280}
281
282