1
0
mirror of https://github.com/actix/examples synced 2024-11-23 22:41:07 +01:00

clean up rustls example

This commit is contained in:
Rob Ede 2022-03-15 18:17:19 +00:00
parent c9ebeacf58
commit 4f1881d1a3
No known key found for this signature in database
GPG Key ID: 97C636207D3EF933
5 changed files with 97 additions and 40 deletions

52
Cargo.lock generated
View File

@ -566,6 +566,39 @@ dependencies = [
"tokio 1.17.0", "tokio 1.17.0",
] ]
[[package]]
name = "actix-web-lab"
version = "0.15.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "277bee594fb4c95da23aee37864e78ff06b427b480ecca7c205c8b630a090acf"
dependencies = [
"actix-files",
"actix-http",
"actix-router",
"actix-service",
"actix-utils",
"actix-web",
"ahash",
"bytes 1.1.0",
"csv",
"derive_more",
"digest 0.10.3",
"futures-core",
"futures-util",
"hmac 0.12.1",
"local-channel",
"log",
"matchit",
"mime",
"once_cell",
"pin-project-lite 0.2.8",
"serde 1.0.136",
"serde_json",
"serde_urlencoded",
"subtle",
"tokio 1.17.0",
]
[[package]] [[package]]
name = "actix_derive" name = "actix_derive"
version = "0.6.0" version = "0.6.0"
@ -3201,7 +3234,7 @@ dependencies = [
"futures-util", "futures-util",
"log", "log",
"rustls 0.20.4", "rustls 0.20.4",
"rustls-pemfile", "rustls-pemfile 0.2.1",
] ]
[[package]] [[package]]
@ -3324,7 +3357,7 @@ dependencies = [
"percent-encoding", "percent-encoding",
"rand 0.8.5", "rand 0.8.5",
"rustls 0.19.1", "rustls 0.19.1",
"rustls-pemfile", "rustls-pemfile 0.2.1",
"serde 1.0.136", "serde 1.0.136",
"serde_bytes", "serde_bytes",
"serde_with", "serde_with",
@ -4699,7 +4732,7 @@ dependencies = [
"env_logger", "env_logger",
"log", "log",
"rustls 0.20.4", "rustls 0.20.4",
"rustls-pemfile", "rustls-pemfile 0.2.1",
] ]
[[package]] [[package]]
@ -4708,9 +4741,11 @@ version = "1.0.0"
dependencies = [ dependencies = [
"actix-files", "actix-files",
"actix-web", "actix-web",
"actix-web-lab 0.15.0",
"env_logger", "env_logger",
"log",
"rustls 0.20.4", "rustls 0.20.4",
"rustls-pemfile", "rustls-pemfile 0.3.0",
] ]
[[package]] [[package]]
@ -4722,6 +4757,15 @@ dependencies = [
"base64 0.13.0", "base64 0.13.0",
] ]
[[package]]
name = "rustls-pemfile"
version = "0.3.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1ee86d63972a7c661d1536fefe8c3c8407321c3df668891286de28abcd087360"
dependencies = [
"base64 0.13.0",
]
[[package]] [[package]]
name = "rustversion" name = "rustversion"
version = "1.0.6" version = "1.0.6"

View File

@ -81,7 +81,7 @@ pub async fn gen_tls_cert(user_email: &str, user_domain: &str) -> anyhow::Result
// http://mydomain.io/.well-known/acme-challenge/<token> // http://mydomain.io/.well-known/acme-challenge/<token>
let chall = auths[0] let chall = auths[0]
.http_challenge() .http_challenge()
.ok_or(anyhow!("no HTTP challenge accessible"))?; .ok_or_else(|| anyhow!("no HTTP challenge accessible"))?;
// The token is the filename. // The token is the filename.
let token = chall.http_token(); let token = chall.http_token();

View File

@ -18,7 +18,7 @@ async fn main() -> io::Result<()> {
println!("Started http server: 127.0.0.1:8443"); println!("Started http server: 127.0.0.1:8443");
// load ssl keys // load TLS keys
let mut builder = SslAcceptor::mozilla_intermediate(SslMethod::tls()).unwrap(); let mut builder = SslAcceptor::mozilla_intermediate(SslMethod::tls()).unwrap();
builder builder
.set_private_key_file("key.pem", SslFiletype::PEM) .set_private_key_file("key.pem", SslFiletype::PEM)

View File

@ -8,8 +8,11 @@ name = "rustls-server"
path = "src/main.rs" path = "src/main.rs"
[dependencies] [dependencies]
env_logger = "0.9"
rustls = "0.20.2"
rustls-pemfile = "0.2.1"
actix-web = { version = "4", features = ["rustls"] } actix-web = { version = "4", features = ["rustls"] }
actix-web-lab = "0.15"
actix-files = "0.6" actix-files = "0.6"
env_logger = "0.9"
log = "0.4"
rustls = "0.20.2"
rustls-pemfile = "0.3"

View File

@ -1,32 +1,58 @@
use std::fs::File; use std::{fs::File, io::BufReader};
use std::io::BufReader;
use actix_files::Files; use actix_files::Files;
use actix_web::{middleware, web, App, HttpRequest, HttpResponse, HttpServer}; use actix_web::{
http::header::ContentType, middleware, web, App, HttpRequest, HttpResponse, HttpServer,
};
use actix_web_lab::web::redirect;
use log::debug;
use rustls::{Certificate, PrivateKey, ServerConfig}; use rustls::{Certificate, PrivateKey, ServerConfig};
use rustls_pemfile::{certs, pkcs8_private_keys}; use rustls_pemfile::{certs, pkcs8_private_keys};
/// simple handle /// simple handle
async fn index(req: HttpRequest) -> HttpResponse { async fn index(req: HttpRequest) -> HttpResponse {
println!("{:?}", req); debug!("{:?}", req);
HttpResponse::Ok()
.content_type("text/html; charset=utf-8") HttpResponse::Ok().content_type(ContentType::html()).body(
.body("<!DOCTYPE html><html><body><p>Welcome!</p></body></html>") "<!DOCTYPE html><html><body>\
<p>Welcome to your TLS-secured homepage!</p>\
</body></html>",
)
} }
#[actix_web::main] #[actix_web::main]
async fn main() -> std::io::Result<()> { async fn main() -> std::io::Result<()> {
if std::env::var("RUST_LOG").is_err() { env_logger::init_from_env(env_logger::Env::default().default_filter_or("info"));
std::env::set_var("RUST_LOG", "actix_web=info");
}
env_logger::init();
// load ssl keys let config = load_rustls_config();
log::info!("starting HTTPS server at http://localhost:8443");
HttpServer::new(|| {
App::new()
// enable logger
.wrap(middleware::Logger::default())
// register simple handler, handle all methods
.service(web::resource("/index.html").to(index))
.service(redirect("/", "/index.html"))
.service(Files::new("/static", "static"))
})
.bind_rustls("127.0.0.1:8443", config)?
.run()
.await
}
fn load_rustls_config() -> rustls::ServerConfig {
// init server config builder with safe defaults
let config = ServerConfig::builder() let config = ServerConfig::builder()
.with_safe_defaults() .with_safe_defaults()
.with_no_client_auth(); .with_no_client_auth();
// load TLS key/cert files
let cert_file = &mut BufReader::new(File::open("cert.pem").unwrap()); let cert_file = &mut BufReader::new(File::open("cert.pem").unwrap());
let key_file = &mut BufReader::new(File::open("key.pem").unwrap()); let key_file = &mut BufReader::new(File::open("key.pem").unwrap());
// convert files to key/cert objects
let cert_chain = certs(cert_file) let cert_chain = certs(cert_file)
.unwrap() .unwrap()
.into_iter() .into_iter()
@ -37,28 +63,12 @@ async fn main() -> std::io::Result<()> {
.into_iter() .into_iter()
.map(PrivateKey) .map(PrivateKey)
.collect(); .collect();
// exit if no keys could be parsed
if keys.is_empty() { if keys.is_empty() {
eprintln!("Could not locate PKCS 8 private keys."); eprintln!("Could not locate PKCS 8 private keys.");
std::process::exit(1); std::process::exit(1);
} }
let config = config.with_single_cert(cert_chain, keys.remove(0)).unwrap();
println!("Starting https server: 127.0.0.1:8443"); config.with_single_cert(cert_chain, keys.remove(0)).unwrap()
HttpServer::new(|| {
App::new()
// enable logger
.wrap(middleware::Logger::default())
// register simple handler, handle all methods
.service(web::resource("/index.html").to(index))
// with path parameters
.service(web::resource("/").route(web::get().to(|| async {
HttpResponse::Found()
.append_header(("LOCATION", "/index.html"))
.finish()
})))
.service(Files::new("/static", "static"))
})
.bind_rustls("127.0.0.1:8443", config)?
.run()
.await
} }