rustls-resolver/examples/demo.rs

63 lines
1.9 KiB
Rust
Raw Normal View History

use std::time::Duration;
2024-01-28 18:08:11 +00:00
use actix_web::{web, App, HttpServer};
async fn index() -> &'static str {
"Hewwo Mr Obama"
}
#[actix_web::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
let initial_key = read_key().await?.unwrap();
2024-01-28 18:08:11 +00:00
let (tx, rx) = rustls_resolver::channel::<32>(initial_key);
let handle = actix_web::rt::spawn(async move {
let mut interval = actix_web::rt::time::interval(Duration::from_secs(30));
interval.tick().await;
loop {
interval.tick().await;
match read_key().await {
Ok(Some(key)) => tx.update(key),
Ok(None) => eprintln!("No key in keyfile"),
Err(e) => {
eprintln!("Failed to read key from fs {e}");
}
}
}
});
let server_config = rustls::ServerConfig::builder()
.with_safe_defaults()
.with_no_client_auth()
.with_cert_resolver(rx);
2024-01-28 18:08:11 +00:00
HttpServer::new(|| App::new().route("/", web::get().to(index)))
.bind_rustls_021("0.0.0.0:8443", server_config)?
.bind("0.0.0.0:8080")?
.run()
.await?;
handle.abort();
let _ = handle.await;
Ok(())
}
async fn read_key() -> Result<Option<rustls::sign::CertifiedKey>, Box<dyn std::error::Error>> {
let cert_bytes = tokio::fs::read("./out/example.crt").await?;
let certs = rustls_pemfile::certs(&mut cert_bytes.as_slice())
.map(|res| res.map(|c| rustls::Certificate(c.to_vec())))
.collect::<Result<Vec<_>, _>>()?;
let key_bytes = tokio::fs::read("./out/example.key").await?;
let Some(private_key) = rustls_pemfile::private_key(&mut key_bytes.as_slice())? else {
return Ok(None);
};
let private_key =
rustls::sign::any_supported_type(&rustls::PrivateKey(Vec::from(private_key.secret_der())))?;
Ok(Some(rustls::sign::CertifiedKey::new(certs, private_key)))
}