Original implementation based on https://github.com/FlorianUekermann/rustls-acme.
An easy-to-use, async compatible ACME client library using rustls. The validation mechanism used is tls-alpn-01, which allows serving acme challenge responses and regular TLS traffic on the same port.
Is designed to use the tokio runtime, if you need support for other runtimes take a look at the original implementation rustls-acme.
No persistent tasks are spawned under the hood and the certificate acquisition/renewal process is folded into the streams and futures being polled by the library user.
The goal is to provide a Let's Encrypt compatible TLS serving and certificate management using a simple and flexible stream based API.
The default tls-ring feature selects ring as rustls's crypto backend.
To use aws-lc-rs instead, disable default features and enable
tls-aws-lc-rs and tls-webpki-roots. One of the two backends must be
enabled; with both, aws-lc-rs is used. The selected backend
flows through to the HTTPS client, the TLS handshake, key parsing, and
ACME request signing, so with tls-aws-lc-rs alone ring is not in the
dependency tree. The crate never reads or installs the process-wide
default provider.
To use tokio-rustls-acme add the following lines to your Cargo.toml:
[dependencies]
tokio-rustls-acme = "*"The high-level API consists of a single stream Incoming of incoming TLS connection.
Polling the next future of the stream takes care of acquisition and renewal of certificates, as
well as accepting TLS connections, which are handed over to the caller on success.
use std::io;
use std::time::Duration;
use tokio::io::AsyncWriteExt;
use n0_future::StreamExt;
use tokio_rustls_acme::{AcmeConfig, caches::DirCache};
use tokio_stream::wrappers::TcpListenerStream;
/// Pause after an accept error, as in axum's `serve`.
const ACCEPT_ERROR_DELAY: Duration = Duration::from_secs(1);
#[tokio::main]
async fn main() {
tracing_subscriber::fmt::init();
let tcp_listener = tokio::net::TcpListener::bind("[::]:443").await.unwrap();
let tcp_incoming = TcpListenerStream::new(tcp_listener);
let mut tls_incoming = AcmeConfig::new(["example.com"])
.contact_push("mailto:admin@example.com")
.cache(DirCache::new("./rustls_acme_cache"))
.incoming(tcp_incoming, Vec::new());
while let Some(tls) = tls_incoming.next().await {
let mut tls = match tls {
Ok(tls) => tls,
Err(err) if is_connection_error(&err) => continue,
Err(err) => {
log::error!("TCP accept failed: {err:?}");
// Accept fails again at once while no file descriptor is free.
tokio::time::sleep(ACCEPT_ERROR_DELAY).await;
continue;
}
};
tokio::spawn(async move {
tls.write_all(HELLO).await.unwrap();
tls.shutdown().await.unwrap();
});
}
}
/// Returns whether `err` concerns only one connection, so accepting can go on at once.
fn is_connection_error(err: &io::Error) -> bool {
matches!(
err.kind(),
io::ErrorKind::ConnectionRefused
| io::ErrorKind::ConnectionAborted
| io::ErrorKind::ConnectionReset
)
}
const HELLO: &'static [u8] = br#"HTTP/1.1 200 OK
Content-Length: 11
Content-Type: text/plain; charset=utf-8
Hello Tls!"#;examples/high_level.rs implements a "Hello Tls!" server similar to the one above, which accepts
domain, port and cache directory parameters.
Note that all examples use the let's encrypt staging directory by default.
The production directory imposes strict rate limits, which are easily exhausted accidentally
during testing and development.
For testing with the staging directory you may open https://<your domain>:<port> in a browser
that allows TLS connections to servers signed by an untrusted CA (in Firefox click "Advanced..."
-> "Accept the Risk and Continue").
For users who may want to interact with [rustls] or [tokio-rustls]
directly, the library exposes the underlying certificate management AcmeState as well as a
matching resolver ResolvesServerCertAcme which implements the rustls::server::ResolvesServerCert trait.
See the server_low_level example on how to use the low-level API directly with [tokio-rustls].
A production server using the let's encrypt production directory must implement both account and
certificate caching to avoid exhausting the let's encrypt API rate limits.
A file based cache using a cache directory is provided by caches::DirCache.
Caches backed by other persistence layers may be implemented using the Cache trait,
or the underlying CertCache, AccountCache traits (contributions welcome).
caches::CompositeCache provides a wrapper to combine two implementors of CertCache and
AccountCache into a single Cache.
Note, that the error type parameters of the cache carries over to some other types in this
crate via the AcmeConfig they are added to.
If you want to avoid different specializations based on cache type use the
AcmeConfig::cache_with_boxed_err method to construct the an AcmeConfig object.
The underlying implementation of an async acme client may be useful to others and is exposed as a module. It is incomplete (contributions welcome) and not covered by any stability promises.
This crate was inspired by the autocert package for Go.
The original implementation of this crate can be found at FlorianUekermann/rustls-acme, this is just a version focused on supporting only tokio.
This crate also builds on the excellent work of the authors of
rustls,
tokio-rustls and many others.
This project is licensed under either of
- Apache License, Version 2.0, (LICENSE-APACHE or http://www.apache.org/licenses/LICENSE-2.0)
- MIT license (LICENSE-MIT or http://opensource.org/licenses/MIT)
at your option.
Unless you explicitly state otherwise, any contribution intentionally submitted for inclusion in this project by you, as defined in the Apache-2.0 license, shall be dual licensed as above, without any additional terms or conditions.