Skip to main content

RustlsConfig

Struct RustlsConfig 

Source
pub struct RustlsConfig { /* private fields */ }
Available on crate feature tls-rustls only.
Expand description

Rustls configuration.

Implementations§

Source§

impl RustlsConfig

Source

pub fn from_config(config: Arc<ServerConfig>) -> Self

Create config from Arc<ServerConfig>.

NOTE: You need to set ALPN protocols (like http/1.1 or h2) manually.

Source

pub async fn from_der(cert: Vec<Vec<u8>>, key: Vec<u8>) -> Result<Self>

Create config from DER-encoded data.

The certificate must be DER-encoded X.509.

The private key must be DER-encoded ASN.1 in either PKCS#8 or PKCS#1 format.

Source

pub async fn from_pem(cert: Vec<u8>, key: Vec<u8>) -> Result<Self>

Create config from PEM formatted data.

Certificate and private key must be in PEM format.

Source

pub async fn from_pem_file( cert: impl AsRef<Path>, key: impl AsRef<Path>, ) -> Result<Self>

Create config from PEM formatted files.

Contents of certificate file and private key file must be in PEM format.

Examples found in repository?
examples/rustls_session.rs (lines 16-19)
13async fn main() {
14    let app = Router::new().route("/", get(handler));
15
16    let config = RustlsConfig::from_pem_file(
17        "examples/self-signed-certs/cert.pem",
18        "examples/self-signed-certs/key.pem",
19    )
20    .await
21    .unwrap();
22
23    let addr = SocketAddr::from(([127, 0, 0, 1], 3000));
24
25    println!("listening on {}", addr);
26
27    axum_server::bind_rustls(addr, config)
28        .serve(app.into_make_service())
29        .await
30        .unwrap();
31}
More examples
Hide additional examples
examples/rustls_server.rs (lines 13-16)
10async fn main() {
11    let app = Router::new().route("/", get(|| async { "Hello, world!" }));
12
13    let config = RustlsConfig::from_pem_file(
14        "examples/self-signed-certs/cert.pem",
15        "examples/self-signed-certs/key.pem",
16    )
17    .await
18    .unwrap();
19
20    let addr = SocketAddr::from(([127, 0, 0, 1], 3000));
21    println!("listening on {}", addr);
22    axum_server::tls_rustls::bind_rustls(addr, config)
23        .serve(app.into_make_service())
24        .await
25        .unwrap();
26}
examples/http_and_https.rs (lines 39-42)
36async fn https_server() {
37    let app = Router::new().route("/", get(|| async { "Hello, world!" }));
38
39    let config = RustlsConfig::from_pem_file(
40        "examples/self-signed-certs/cert.pem",
41        "examples/self-signed-certs/key.pem",
42    )
43    .await
44    .unwrap();
45
46    let addr = SocketAddr::from(([127, 0, 0, 1], 3443));
47    println!("https listening on {}", addr);
48    axum_server::bind_rustls(addr, config)
49        .serve(app.into_make_service())
50        .await
51        .unwrap();
52}
examples/rustls_reload.rs (lines 18-21)
15async fn main() {
16    let app = Router::new().route("/", get(|| async { "Hello, world!" }));
17
18    let config = RustlsConfig::from_pem_file(
19        "examples/self-signed-certs/cert.pem",
20        "examples/self-signed-certs/key.pem",
21    )
22    .await
23    .unwrap();
24
25    // Spawn a task to reload tls.
26    tokio::spawn(reload(config.clone()));
27
28    let addr = SocketAddr::from(([127, 0, 0, 1], 3000));
29    println!("listening on {}", addr);
30    axum_server::bind_rustls(addr, config)
31        .serve(app.into_make_service())
32        .await
33        .unwrap();
34}
examples/from_std_listener_rustls.rs (lines 14-17)
11async fn main() {
12    let app = Router::new().route("/", get(|| async { "Hello, world!" }));
13
14    let config = RustlsConfig::from_pem_file(
15        "examples/self-signed-certs/cert.pem",
16        "examples/self-signed-certs/key.pem",
17    )
18    .await
19    .unwrap();
20
21    let addr = SocketAddr::from(([127, 0, 0, 1], 3000));
22    let listener = TcpListener::bind(addr).unwrap();
23    println!("listening on {}", addr);
24    axum_server::from_tcp_rustls(listener, config)
25        .unwrap()
26        .serve(app.into_make_service())
27        .await
28        .unwrap();
29}
examples/async_sni.rs (line 152)
132    async fn resolve(&self, server_name: Option<&str>) -> io::Result<RustlsConfig> {
133        let server_name = server_name.ok_or_else(|| {
134            io::Error::new(
135                io::ErrorKind::InvalidData,
136                "client did not send a server name",
137            )
138        })?;
139
140        let (cert, key) = self.certificates.get(server_name).ok_or_else(|| {
141            io::Error::new(
142                io::ErrorKind::NotFound,
143                format!("no certificate registered for {server_name}"),
144            )
145        })?;
146
147        println!("resolving certificate for {server_name}");
148
149        // Async I/O happens here, before the handshake continues. `from_pem_file`
150        // also sets the `h2` and `http/1.1` ALPN protocols. A `ServerConfig`
151        // built by hand must set them too.
152        RustlsConfig::from_pem_file(cert, key).await
153    }
Source

pub async fn from_sni_pem_files<I, S, P, K>(files: I) -> Result<Self>
where I: IntoIterator<Item = (S, P, K)>, S: AsRef<str>, P: AsRef<Path>, K: AsRef<Path>,

Create config from PEM formatted files, selecting the certificate by the server name sent by the client using SNI.

Each item is (server_name, certificate_path, private_key_path). The server name is matched against the client’s SNI value, and each certificate must be valid for the name it is registered under.

The certificate and private key files must be in PEM format.

Source

pub fn get_inner(&self) -> Arc<ServerConfig> ⓘ

Get inner Arc<ServerConfig>.

Examples found in repository?
examples/async_sni.rs (line 90)
72    fn accept(&self, stream: I, service: S) -> Self::Future {
73        let store = self.store.clone();
74        let handshake_timeout = self.handshake_timeout;
75
76        Box::pin(async move {
77            // One deadline covers reading the ClientHello and the handshake.
78            let deadline = Instant::now() + handshake_timeout;
79
80            let start = timeout_at(
81                deadline,
82                LazyConfigAcceptor::new(Acceptor::default(), stream),
83            )
84            .await
85            .map_err(|_| timeout_error())??;
86
87            let server_name = start.client_hello().server_name().map(str::to_owned);
88            let config = store.resolve(server_name.as_deref()).await?;
89
90            let stream = timeout_at(deadline, start.into_stream(config.get_inner()))
91                .await
92                .map_err(|_| timeout_error())??;
93
94            Ok((stream, service))
95        })
96    }
Source

pub fn reload_from_config(&self, config: Arc<ServerConfig>)

Reload config from Arc<ServerConfig>.

Source

pub async fn reload_from_der( &self, cert: Vec<Vec<u8>>, key: Vec<u8>, ) -> Result<()>

Reload config from DER-encoded data.

The certificate must be DER-encoded X.509.

The private key must be DER-encoded ASN.1 in either PKCS#8 or PKCS#1 format.

Source

pub async fn from_pem_chain_file( chain: impl AsRef<Path>, key: impl AsRef<Path>, ) -> Result<Self>

This helper will establish a TLS server based on strong cipher suites from a PEM-formatted certificate chain and key.

Source

pub async fn reload_from_pem(&self, cert: Vec<u8>, key: Vec<u8>) -> Result<()>

Reload config from PEM formatted data.

Certificate and private key must be in PEM format.

Source

pub async fn reload_from_pem_file( &self, cert: impl AsRef<Path>, key: impl AsRef<Path>, ) -> Result<()>

Reload config from PEM formatted files.

Contents of certificate file and private key file must be in PEM format.

Examples found in repository?
examples/rustls_reload.rs (lines 44-47)
36async fn reload(config: RustlsConfig) {
37    // Wait for 20 seconds.
38    sleep(Duration::from_secs(20)).await;
39
40    println!("reloading rustls configuration");
41
42    // Reload rustls configuration from new files.
43    config
44        .reload_from_pem_file(
45            "examples/self-signed-certs/reload/cert.pem",
46            "examples/self-signed-certs/reload/key.pem",
47        )
48        .await
49        .unwrap();
50
51    println!("rustls configuration reloaded");
52}
Source§

impl RustlsConfig

Source

pub async fn from_pem_with_password( cert: Vec<u8>, key: Vec<u8>, password: impl AsRef<[u8]>, ) -> Result<Self>

Create config from a PEM formatted certificate and an encrypted PKCS#8 private key.

The key must be a PKCS#8 ENCRYPTED PRIVATE KEY section, as produced by openssl pkcs8 -topk8.

Source

pub async fn from_pem_file_with_password( cert: impl AsRef<Path>, key: impl AsRef<Path>, password: impl AsRef<[u8]>, ) -> Result<Self>

Create config from PEM formatted files, where the private key is an encrypted PKCS#8 key.

Source

pub async fn reload_from_pem_with_password( &self, cert: Vec<u8>, key: Vec<u8>, password: impl AsRef<[u8]>, ) -> Result<()>

Reload config from a PEM formatted certificate and an encrypted PKCS#8 private key.

Source

pub async fn reload_from_pem_file_with_password( &self, cert: impl AsRef<Path>, key: impl AsRef<Path>, password: impl AsRef<[u8]>, ) -> Result<()>

Reload config from PEM formatted files, where the private key is an encrypted PKCS#8 key.

Trait Implementations§

Source§

impl Clone for RustlsConfig

Source§

fn clone(&self) -> Self

Returns a duplicate of the value. Read more
1.0.0 (const: unstable) · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl Debug for RustlsConfig

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<'a, T, E> AsTaggedExplicit<'a, E> for T
where T: 'a,

Source§

fn explicit(self, class: Class, tag: u32) -> TaggedParser<'a, Explicit, Self, E>

Source§

impl<'a, T, E> AsTaggedImplicit<'a, E> for T
where T: 'a,

Source§

fn implicit( self, class: Class, constructed: bool, tag: u32, ) -> TaggedParser<'a, Implicit, Self, E>

Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T> Instrument for T

Source§

fn instrument(self, span: Span) -> Instrumented<Self> ⓘ

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more
Source§

fn in_current_span(self) -> Instrumented<Self> ⓘ

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> IntoEither for T

Source§

fn into_either(self, into_left: bool) -> Either<Self, Self> ⓘ

Converts self into a Left variant of Either<Self, Self> if into_left is true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

fn into_either_with<F>(self, into_left: F) -> Either<Self, Self> ⓘ
where F: FnOnce(&Self) -> bool,

Converts self into a Left variant of Either<Self, Self> if into_left(&self) returns true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

impl<T> Same for T

Source§

type Output = T

Should always be Self
Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = !

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, !>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
Source§

impl<T> WithSubscriber for T

Source§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self> ⓘ
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

fn with_current_subscriber(self) -> WithDispatch<Self> ⓘ

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more