ctb_io_webui/
tls_rustls_vendored.rs

1// SPDX-License-Identifier: AGPL-3.0-or-later AND MIT
2// SPDX-License-Identifier for parts derived from from programatik29/axum-server/blob/master/src/tls_rustls/mod.rs: MIT
3/*
4This file is part of Collective Toolbox, a database and document workspace and utilities.
5Copyright (C) 2026 Collective Toolbox Developers
6Contact: info@collectivetoolbox.com
7
8This program is free software: you can redistribute it and/or modify it under
9the terms of the GNU Affero General Public License as published by the Free
10Software Foundation, either version 3 of the License, or (at your option) any
11later version.
12
13This program is distributed in the hope that it will be useful, but WITHOUT ANY
14WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
15A PARTICULAR PURPOSE.  See the GNU Affero General Public License for more details.
16
17You should have received a copy of the GNU Affero General Public License along
18with this program.  If not, see <https://www.gnu.org/licenses/>.
19*/
20
21// Parts derived from from programatik29/axum-server/blob/master/src/tls_rustls/mod.rs:
22
23// Copyright 2021 Axum Server Contributors
24
25// See additional licensing details at end of file.
26
27//! Tls implementation using [`rustls`].
28//! Vendored with changes from <https://github.com/programatik29/axum-server/blob/master/src/tls_rustls/mod.rs>
29//!
30//! # Example
31//!
32//! ```rust,no_run
33//! use axum::{routing::get, Router};
34//! use axum_server::tls_rustls::RustlsConfig;
35//! use std::net::SocketAddr;
36//!
37//! #[tokio::main]
38//! async fn main() {
39//!     let app = Router::new().route("/", get(|| async { "Hello, world!" }));
40//!
41//!     let config = RustlsConfig::from_pem_file(
42//!         "tls_rustls_vendored/fixtures/cert.pem",
43//!         "tls_rustls_vendored/fixtures/key.pem",
44//!     )
45//!     .await
46//!     .unwrap();
47//!
48//!     let addr = SocketAddr::from(([127, 0, 0, 1], 3000));
49//!     println!("listening on {}", addr);
50//!     axum_server::bind_rustls(addr, config)
51//!         .serve(app.into_make_service())
52//!         .await
53//!         .unwrap();
54//! }
55//! ```
56
57use 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    // Check the entire PEM file for the key in case it is not first section
113    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            // if we already got a key, then...
119            Ok(_) => {
120                // ...if we get a key now, we know that there are multiple keys and that's not allowed
121                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            // but if already have an error, just overwrite it with whatever we got this time. If
128            // it's a good key, that's cool. If it's an error, then we're just ignoring the old
129            // error in favor of this new one
130            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/*
283
284// From axum-server:
285
286MIT License
287
288Copyright 2021 Axum Server Contributors
289
290Permission is hereby granted, free of charge, to any person obtaining a copy
291of this software and associated documentation files (the "Software"), to deal
292in the Software without restriction, including without limitation the rights
293to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
294copies of the Software, and to permit persons to whom the Software is
295furnished to do so, subject to the following conditions:
296
297The above copyright notice and this permission notice shall be included in all
298copies or substantial portions of the Software.
299
300THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
301IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
302FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
303AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
304LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
305OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
306SOFTWARE.
307
308*/