From 1a5f97789682f9582965fdaf8dd2876f1647c324 Mon Sep 17 00:00:00 2001 From: programatik29 <70590982+programatik29@users.noreply.github.com> Date: Tue, 24 Aug 2021 10:56:31 +0300 Subject: [PATCH] Simplify tls-rustls example (#254) ## Motivation Current `tls-rustls` example might be inconvenient for some people. ## Solution Rename current example to `low-level-rustls` and add a high level example in its place. --- examples/low-level-rustls/Cargo.toml | 13 ++++ .../self_signed_certs/cert.pem | 22 ++++++ .../self_signed_certs/key.pem | 28 ++++++++ examples/low-level-rustls/src/main.rs | 68 +++++++++++++++++++ examples/tls-rustls/Cargo.toml | 5 +- examples/tls-rustls/src/main.rs | 51 ++------------ 6 files changed, 139 insertions(+), 48 deletions(-) create mode 100644 examples/low-level-rustls/Cargo.toml create mode 100644 examples/low-level-rustls/self_signed_certs/cert.pem create mode 100644 examples/low-level-rustls/self_signed_certs/key.pem create mode 100644 examples/low-level-rustls/src/main.rs diff --git a/examples/low-level-rustls/Cargo.toml b/examples/low-level-rustls/Cargo.toml new file mode 100644 index 00000000..5472470a --- /dev/null +++ b/examples/low-level-rustls/Cargo.toml @@ -0,0 +1,13 @@ +[package] +name = "example-low-level-rustls" +version = "0.1.0" +edition = "2018" +publish = false + +[dependencies] +axum = { path = "../.." } +tokio = { version = "1.0", features = ["full"] } +tracing = "0.1" +tracing-subscriber = "0.2" +tokio-rustls = "0.22.0" +hyper = { version = "0.14", features = ["full"] } diff --git a/examples/low-level-rustls/self_signed_certs/cert.pem b/examples/low-level-rustls/self_signed_certs/cert.pem new file mode 100644 index 00000000..656aa880 --- /dev/null +++ b/examples/low-level-rustls/self_signed_certs/cert.pem @@ -0,0 +1,22 @@ +-----BEGIN CERTIFICATE----- +MIIDkzCCAnugAwIBAgIUXVYkRCrM/ge03DVymDtXCuybp7gwDQYJKoZIhvcNAQEL +BQAwWTELMAkGA1UEBhMCVVMxEzARBgNVBAgMClNvbWUtU3RhdGUxITAfBgNVBAoM +GEludGVybmV0IFdpZGdpdHMgUHR5IEx0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Y8Vxr +AopvZ09uEQ== +-----END CERTIFICATE----- diff --git a/examples/low-level-rustls/self_signed_certs/key.pem b/examples/low-level-rustls/self_signed_certs/key.pem new file mode 100644 index 00000000..3de14eb3 --- /dev/null +++ b/examples/low-level-rustls/self_signed_certs/key.pem @@ -0,0 +1,28 @@ +-----BEGIN PRIVATE KEY----- +MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQDTZXlmOaosH9VD +BNquvP/fmqxrzcv4NsChrTTTX6NWaYL4b025+LR1qugVaP9SJy/Z9lYRNTwmhkpS +tfgEr2iDlyDmuWf8K0FFYJRgjBGBj1H8J0EY+fiSn5eRIloLDvhkjIvL9l+7HqHw +RLWb1hGcHNr6ztT4iZEFF/gxE+1dDf+aonEBlip06cqe+yxHIPaq62BVMDHAxS8l +YiK9GFFgOPtY6lLgIQR5DE/WIfX9Pk/sV21MZ1NtUEAEIDwmEv3q4UY+k5gdwz/t +HkQgDfJnkU2D3fVDOgMhOO1ca1DrL3+X8hiRabonrtFZw3QihOxmHPRY1TiAB6yV +W0kuh+fxAgMBAAECggEADltu8k1qTFLhJgsXWxTFAAe+PBgfCT2WuaRM2So+qqjB +12Of0MieYPt5hbK63HaC3nfHgqWt7yPhulpXfOH45C8IcgMXl93MMg0MJr58leMI ++2ojFrIrerHSFm5R1TxwDEwrVm/mMowzDWFtQCc6zPJ8wNn5RuP48HKfTZ3/2fjw +zEjSwPO2wFMfo1EJNTjlI303lFbdFBs67NaX6puh30M7Tn+gznHKyO5a7F57wkIt +fkgnEy/sgMedQlwX7bRpUoD6f0fZzV8Qz4cHFywtYErczZJh3VGitJoO/VCIDdty +RPXOAqVDd7EpP1UUehZlKVWZ0OZMEfRgKbRCel5abQKBgQDwgwrIQ5+BiZv6a0VT +ETeXB+hRbvBinRykNo/RvLc3j1enRh9/zO/ShadZIXgOAiM1Jnr5Gp8KkNGca6K1 +myhtad7xYPODYzNXXp6T1OPgZxHZLIYzVUj6ypXeV64Te5ZiDaJ1D49czsq+PqsQ +XRcgBJSNpFtDFiXWpjXWfx8PxwKBgQDhAnLY5Sl2eeQo+ud0MvjwftB/mN2qCzJY +5AlQpRI4ThWxJgGPuHTR29zVa5iWNYuA5LWrC1y/wx+t5HKUwq+5kxvs+npYpDJD +ZX/w0Glc6s0Jc/mFySkbw9B2LePedL7lRF5OiAyC6D106Sc9V2jlL4IflmOzt4CD +ZTNbLtC6hwKBgHfIzBXxl/9sCcMuqdg1Ovp9dbcZCaATn7ApfHd5BccmHQGyav27 +k7XF2xMJGEHhzqcqAxUNrSgV+E9vTBomrHvRvrd5Ec7eGTPqbBA0d0nMC5eeFTh7 +wV0miH20LX6Gjt9G6yJiHYSbeV5G1+vOcTYBEft5X/qJjU7aePXbWh0BAoGBAJlV +5tgCCuhvFloK6fHYzqZtdT6O+PfpW20SMXrgkvMF22h2YvgDFrDwqKRUB47NfHzg +3yBpxNH1ccA5/w97QO8w3gX3h6qicpJVOAPusu6cIBACFZfjRv1hyszOZwvw+Soa +Fj5kHkqTY1YpkREPYS9V2dIW1Wjic1SXgZDw7VM/AoGAP/cZ3ZHTSCDTFlItqy5C +rIy2AiY0WJsx+K0qcvtosPOOwtnGjWHb1gdaVdfX/IRkSsX4PAOdnsyidNC5/l/m +y8oa+5WEeGFclWFhr4dnTA766o8HrM2UjIgWWYBF2VKdptGnHxFeJWFUmeQC/xeW +w37pCS7ykL+7gp7V0WShYsw= +-----END PRIVATE KEY----- diff --git a/examples/low-level-rustls/src/main.rs b/examples/low-level-rustls/src/main.rs new file mode 100644 index 00000000..afe95f5a --- /dev/null +++ b/examples/low-level-rustls/src/main.rs @@ -0,0 +1,68 @@ +//! Run with +//! +//! ```not_rust +//! cargo run -p example-low-level-rustls +//! ``` + +use axum::{handler::get, Router}; +use hyper::server::conn::Http; +use std::{fs::File, io::BufReader, sync::Arc}; +use tokio::net::TcpListener; +use tokio_rustls::{ + rustls::{ + internal::pemfile::certs, internal::pemfile::pkcs8_private_keys, NoClientAuth, ServerConfig, + }, + TlsAcceptor, +}; + +#[tokio::main] +async fn main() { + // Set the RUST_LOG, if it hasn't been explicitly defined + if std::env::var("RUST_LOG").is_err() { + std::env::set_var("RUST_LOG", "example_tls_rustls=debug") + } + tracing_subscriber::fmt::init(); + + let rustls_config = rustls_server_config( + "examples/tls-rustls/self_signed_certs/key.pem", + "examples/tls-rustls/self_signed_certs/cert.pem", + ); + + let acceptor = TlsAcceptor::from(rustls_config); + let listener = TcpListener::bind("127.0.0.1:3000").await.unwrap(); + + let app = Router::new().route("/", get(handler)); + + loop { + let (stream, _addr) = listener.accept().await.unwrap(); + let acceptor = acceptor.clone(); + + let app = app.clone(); + + tokio::spawn(async move { + if let Ok(stream) = acceptor.accept(stream).await { + let _ = Http::new().serve_connection(stream, app).await; + } + }); + } +} + +async fn handler() -> &'static str { + "Hello, World!" +} + +fn rustls_server_config(key: &str, cert: &str) -> Arc { + let mut config = ServerConfig::new(NoClientAuth::new()); + + let mut key_reader = BufReader::new(File::open(key).unwrap()); + let mut cert_reader = BufReader::new(File::open(cert).unwrap()); + + let key = pkcs8_private_keys(&mut key_reader).unwrap().remove(0); + let certs = certs(&mut cert_reader).unwrap(); + + config.set_single_cert(certs, key).unwrap(); + + config.set_protocols(&[b"h2".to_vec(), b"http/1.1".to_vec()]); + + Arc::new(config) +} diff --git a/examples/tls-rustls/Cargo.toml b/examples/tls-rustls/Cargo.toml index e0a9353e..b552d189 100644 --- a/examples/tls-rustls/Cargo.toml +++ b/examples/tls-rustls/Cargo.toml @@ -6,8 +6,7 @@ publish = false [dependencies] axum = { path = "../.." } -tokio = { version = "1.0", features = ["full"] } +axum-server = { version = "0.1", features = ["tls-rustls"] } +tokio = { version = "1", features = ["full"] } tracing = "0.1" tracing-subscriber = "0.2" -tokio-rustls = "0.22.0" -hyper = { version = "0.14", features = ["full"] } diff --git a/examples/tls-rustls/src/main.rs b/examples/tls-rustls/src/main.rs index bb051269..b69a8878 100644 --- a/examples/tls-rustls/src/main.rs +++ b/examples/tls-rustls/src/main.rs @@ -5,15 +5,6 @@ //! ``` use axum::{handler::get, Router}; -use hyper::server::conn::Http; -use std::{fs::File, io::BufReader, sync::Arc}; -use tokio::net::TcpListener; -use tokio_rustls::{ - rustls::{ - internal::pemfile::certs, internal::pemfile::pkcs8_private_keys, NoClientAuth, ServerConfig, - }, - TlsAcceptor, -}; #[tokio::main] async fn main() { @@ -23,46 +14,16 @@ async fn main() { } tracing_subscriber::fmt::init(); - let rustls_config = rustls_server_config( - "examples/tls-rustls/self_signed_certs/key.pem", - "examples/tls-rustls/self_signed_certs/cert.pem", - ); - - let acceptor = TlsAcceptor::from(rustls_config); - let listener = TcpListener::bind("127.0.0.1:3000").await.unwrap(); - let app = Router::new().route("/", get(handler)); - loop { - let (stream, _addr) = listener.accept().await.unwrap(); - let acceptor = acceptor.clone(); - - let app = app.clone(); - - tokio::spawn(async move { - if let Ok(stream) = acceptor.accept(stream).await { - let _ = Http::new().serve_connection(stream, app).await; - } - }); - } + axum_server::bind_rustls("127.0.0.1:3000") + .private_key_file("examples/tls-rustls/self_signed_certs/key.pem") + .certificate_file("examples/tls-rustls/self_signed_certs/cert.pem") + .serve(app) + .await + .unwrap(); } async fn handler() -> &'static str { "Hello, World!" } - -fn rustls_server_config(key: &str, cert: &str) -> Arc { - let mut config = ServerConfig::new(NoClientAuth::new()); - - let mut key_reader = BufReader::new(File::open(key).unwrap()); - let mut cert_reader = BufReader::new(File::open(cert).unwrap()); - - let key = pkcs8_private_keys(&mut key_reader).unwrap().remove(0); - let certs = certs(&mut cert_reader).unwrap(); - - config.set_single_cert(certs, key).unwrap(); - - config.set_protocols(&[b"h2".to_vec(), b"http/1.1".to_vec()]); - - Arc::new(config) -}