2
0
Fork 0
mirror of https://git.asonix.dog/asonix/pict-rs synced 2024-11-20 11:21:14 +00:00
pict-rs/src/tls.rs

64 lines
1.7 KiB
Rust
Raw Permalink Normal View History

2024-01-31 23:47:42 +00:00
use std::path::PathBuf;
2024-02-04 03:58:08 +00:00
use rustls::{crypto::ring::sign::any_supported_type, sign::CertifiedKey, Error};
2024-01-31 23:47:42 +00:00
pub(super) struct Tls {
certificate: PathBuf,
private_key: PathBuf,
}
#[derive(Debug, thiserror::Error)]
enum TlsError {
#[error("Failed to read file")]
Io(#[from] std::io::Error),
#[error("Failed to sign certificate")]
2024-02-04 03:58:08 +00:00
Sign(#[from] Error),
2024-01-31 23:47:42 +00:00
#[error("No certificates found in certificate file")]
MissingCerts,
#[error("No key found in private key file")]
MissingKey,
}
impl Tls {
pub(super) fn from_config(config: &crate::config::Configuration) -> Option<Self> {
config
.server
.certificate
.as_ref()
.zip(config.server.private_key.as_ref())
.map(|(cert, key)| Tls {
certificate: cert.clone(),
private_key: key.clone(),
})
}
2024-02-04 03:58:08 +00:00
pub(super) async fn open_keys(&self) -> color_eyre::Result<CertifiedKey> {
2024-01-31 23:47:42 +00:00
let cert_bytes = tokio::fs::read(&self.certificate)
.await
.map_err(TlsError::from)?;
let certs = rustls_pemfile::certs(&mut cert_bytes.as_slice())
.collect::<Result<Vec<_>, _>>()
.map_err(TlsError::from)?;
if certs.is_empty() {
return Err(TlsError::MissingCerts.into());
}
let key_bytes = tokio::fs::read(&self.private_key)
.await
.map_err(TlsError::from)?;
let private_key = rustls_pemfile::private_key(&mut key_bytes.as_slice())
.map_err(TlsError::from)?
.ok_or(TlsError::MissingKey)?;
2024-02-04 03:58:08 +00:00
let private_key = any_supported_type(&private_key).map_err(TlsError::from)?;
2024-01-31 23:47:42 +00:00
2024-02-04 03:58:08 +00:00
Ok(CertifiedKey::new(certs, private_key))
2024-01-31 23:47:42 +00:00
}
}