Rust typestate — compile-time checks for OAuth2 client setup

Contents

  1. 1. Typestate
  2. 2. OAuth2 client simulation
  3. 3. Further reading

Typestate encodes lifecycle state in the type system.

oauth2-rs uses it for a concrete pain point: OAuth2 clients need auth_url, token_url, introspect_url, and friends wired up before auth calls make sense. If token_url is missing, exchanging an authorization code for a token fails at runtime.

Forgot to call set_token_url? You find out when you fetch a token—not when you build the client.

Typestate pushes that mistake to compile time.

Typestate

State lives in the type. In a strongly typed language, the compiler can reject calls that do not match the current state.

Two ticket types illustrate the idea:

EmptyTicket can only be created or booked.

book moves you to BookedTicket, where you may use (consume) or cancel back to EmptyTicket.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
struct EmptyTicket {}
struct BookedTicket {}

impl EmptyTicket {
fn new() -> Self {
EmptyTicket {}
}
fn book(self) -> BookedTicket {
BookedTicket {}
}
}

impl BookedTicket {
fn use(self) {}
fn cancel(self) -> EmptyTicket {
EmptyTicket {}
}
}

OAuth2 client simulation

How does that map to the missing-URL problem?

Below is a trimmed stand-in for oauth2-rs.

auth_url and token_url each have an EndpointState.

Initially both are unset (EndpointNotSet). Calling a setter returns a Client with the corresponding type parameter flipped to EndointSet.

Methods that need a configured URL are only implemented on Client variants that carry EndointSet in the right slot—so you cannot call token helpers until the type says the token URL is set.

For example, Client<EndointSet, EndpointNotSet> may use auth-url APIs but not token-url APIs, because the type still says token_url is unset.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
use std::marker::PhantomData;

struct EndointSet {}
struct EndpointNotSet {}

trait EndpointState {}

impl EndpointState for EndointSet {}
impl EndpointState for EndpointNotSet {}

struct Client<HasAuthUrl = EndpointNotSet, HasTokenUrl = EndpointNotSet>
where
HasAuthUrl: EndpointState,
HasTokenUrl: EndpointState,
{
auth_url: Option<String>,
token_url: Option<String>,
phantom: std::marker::PhantomData<(HasAuthUrl, HasTokenUrl)>,
}

impl<HasAuthUrl, HasTokenUrl> Client<HasAuthUrl, HasTokenUrl>
where
HasAuthUrl: EndpointState,
HasTokenUrl: EndpointState,
{
pub fn new() -> Self {
Client {
auth_url: None,
token_url: None,
phantom: PhantomData,
}
}

pub fn set_auth_url(self, auth_url: &str) -> Client<EndointSet, HasTokenUrl> {
Client {
auth_url: Some(auth_url.to_string()),
token_url: self.token_url,
phantom: PhantomData,
}
}

pub fn set_token_url(self, token_url: &str) -> Client<HasAuthUrl, EndointSet> {
Client {
auth_url: self.auth_url,
token_url: Some(token_url.to_string()),
phantom: PhantomData,
}
}
}

impl<HasTokenUrl> Client<EndointSet, HasTokenUrl>
where
HasTokenUrl: EndpointState,
{
pub fn get_auth_url(&self) -> &str {
self.auth_url.as_ref().unwrap()
}
}

impl<HasAuthUrl> Client<HasAuthUrl, EndointSet>
where
HasAuthUrl: EndpointState,
{
pub fn get_token_url(&self) -> &str {
self.token_url.as_ref().unwrap()
}
}
fn main() {
let client =
Client::<EndointSet, EndpointNotSet>::new().set_auth_url("https://auth.example.com");
// .set_token_url("https://token.example.com");
// Uncommenting get_token_url below fails: Client type does not match set_token_url's state.

println!("Auth URL: {}", client.get_auth_url());
println!("Token URL: {}", client.get_token_url());
}

Further reading

The idea goes back a while; Clifford Wolfe’s typestate write-up (2019) is still a good read.

Pair with sealing endpoint state so callers cannot fake “configured” types.

Questions? Leave a comment below or email: newbvirgil@gmail.com