Learning question: How can a library make "you called these in the wrong order" a compile error, with no run-time check?
Some objects must be set up in an order, and a TLS configuration is one of them. This article reads how rustls arranges for the skipped step to be impossible to write: one generic builder, three small state types, and methods that exist only in the state where they make sense.
Scope. We read rustls/src/builder.rs and rustls/src/client/builder.rs at tag v/0.23.46 [S6]. We do not cover what the TLS options mean, and we do not cover the server side. You need generics at the level of Vec<T>, and the Builders article. Typestate is the practice of putting an object's state in its type; the Rust patterns book traces the idea to a 1986 paper by Strom and Yemini [S2, ch. 10, "The TypeState pattern"].
A configuration in a hurry
Example 1 asks for a client configuration and skips the question of which servers to trust.
Example 1. Does not compile (compile-fail/cf04_typestate/src/main.rs)
let config = ClientConfig::builder_with_provider(provider)
.with_safe_default_protocol_versions()
.unwrap()
.with_no_client_auth();
The chain had four calls and considered itself finished. It had chosen its protocol versions and declined to present a client certificate, and it went straight from the one to the other like a man buttoning his coat over his pyjamas. It did not mention certificate verification. The compiler did.
error[E0599]: no method named `with_no_client_auth` found for struct `ConfigBuilder<ClientConfig, WantsVerifier>` in the current scope
--> src/main.rs:9:10
|
9 | .with_no_client_auth();
| ^^^^^^^^^^^^^^^^^^^ method not found in `ConfigBuilder<ClientConfig, WantsVerifier>`
|
= note: the method was found for
- `ConfigBuilder<ClientConfig, WantsClientCert>`
- `ConfigBuilder<ServerConfig, WantsVerifier>`Predict
Read the error's last three lines. Before going on: the method exists, on a type that is almost the one you have. What is the one word that differs, and what do you think has to happen to change it?
Name the parts
| Part | In rustls | Where [S6] |
|---|---|---|
| The builder | ConfigBuilder<Side, State> |
builder.rs line 164 |
| State types | WantsVersions, WantsVerifier, WantsClientCert |
builder.rs lines 196 and 272; client/builder.rs line 130 |
| Transitions | with_safe_default_protocol_versions, with_root_certificates, with_no_client_auth |
builder.rs line 200; client/builder.rs lines 51 and 156 |
| Product | ClientConfig |
returned by the last transition |
Where do the methods live?
A builder whose every method is always available relies on documentation to say which order is safe. Thankfully, the type system can carry the order. Take a look at Example 2.
Example 2. One builder, methods per state (rustls/src/builder.rs lines 164 to 169; rustls/src/client/builder.rs lines 37, 51 to 54, 136 and 156, bodies and doc comments removed [S6])
pub struct ConfigBuilder<Side: ConfigSide, State> {
pub(crate) state: State,
pub(crate) provider: Arc<CryptoProvider>,
pub(crate) time_provider: Arc<dyn TimeProvider>,
pub(crate) side: PhantomData<Side>,
}
impl ConfigBuilder<ClientConfig, WantsVerifier> {
pub fn with_root_certificates(
self,
root_store: impl Into<Arc<webpki::RootCertStore>>,
) -> ConfigBuilder<ClientConfig, WantsClientCert>
}
impl ConfigBuilder<ClientConfig, WantsClientCert> {
pub fn with_no_client_auth(self) -> ClientConfig
}
There are three new pieces. State is a type parameter, and the builder stores a value of it in the state field. Each impl block is written for one specific State, so with_root_certificates exists only on a builder whose state is WantsVerifier. And each method takes self and returns a builder with the next state, or, at the end, the product. That is the answer to the prediction: the differing word is the state, and calling with_root_certificates is what changes it.
If
PhantomData<Side> looks like too much at once, skip it for now. It records which side, client or server, the builder is for, and occupies no memory.¹
What transfers, and what does not
In PHP you would guard build() with a check and throw if the verifier was missing, and a test would have to reach that line to find out. The intent transfers. The mechanism does not: here there is no check to reach, because the call cannot be compiled. The Rust patterns book credits ownership for the part that makes it hold, since a transition consumes the old state and nothing is left to call the old methods on [S2, ch. 10]. Do not picture one object whose internal flag changes. Each arrow in the diagram produces a new value of a different type, and the old one is unusable.
Is the state a type or a value?
So the chain compiles only in order. The same three states could have been one enum inside a single builder type, checked when build() runs, and rustls's choice, which takes an impl block per state and produces error messages that name types such as ConfigBuilder<ClientConfig, WantsVerifier>, gives the caller a guarantee that no test has to exercise, while the enum would have been shorter to write and could have been stored in a Vec or picked from a config file at run time, and a typestate value cannot. Does your sequence of steps come from the programmer, or from data?
Practice tier: compiler, for the library's users. For the library's author, choosing typestate over a run-time check is judgment.
Testing
The claim is that the steps in order produce a configuration. Example 3 is the positive half; Example 1 is the negative half.
Example 3. The steps in order (tests/p04_typestate_rustls.rs)
let config: ClientConfig = ClientConfig::builder_with_provider(provider) // WantsVersions
.with_safe_default_protocol_versions() // -> WantsVerifier
.expect("the ring provider supports the default versions")
.with_root_certificates(RootCertStore::empty()) // -> WantsClientCert
.with_no_client_auth(); // -> ClientConfig
It passed against rustls 0.23.46 on rustc 1.100.0. RootCertStore::empty() holds no root certificates (rustls/src/webpki/anchors.rs, lines 21 to 23 [S6]), so this configuration has nothing to verify a server's certificate against; it is here to show the types.
Retrieve
- In which state does
with_no_client_authexist for a client? - What happens to the
WantsVerifierbuilder when you callwith_root_certificateson it?
The Enums article takes the other road from the turn above: states as values, checked by match.
TL;DR
rustls's ConfigBuilder<Side, State> carries its state as a type parameter. Each method is implemented for one state, takes the builder by value, and returns a builder in the next state, so a step cannot be skipped: the method for the later step does not exist yet. Skipping one produces E0599, naming the state you are in.
¹ PhantomData<T> is std's zero-sized marker for a type that acts as though it stores a T and does not (library/core/src/marker.rs, doc comment at lines 676 to 680, struct at line 811 [S3]).