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
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
use crate::auth_scheme::{AuthenticationScheme, ClientAuthentication};
use crate::errors::{Error, RequestError};
use data_encoding::BASE64;
use http::header::AUTHORIZATION;
use http::{header::CONTENT_TYPE, Request, Uri};
use std::convert::TryInto;
use std::time::{SystemTime, UNIX_EPOCH};
use url::form_urlencoded::Serializer;

pub fn authorization_request<ReqUri, RedirectUri>(
    uri: ReqUri,
    redirect_uri: RedirectUri,
    auth: &ClientAuthentication,
    scopes: &Option<Vec<String>>,
) -> Result<Request<Vec<u8>>, RequestError>
where
    ReqUri: TryInto<Uri>,
    RedirectUri: TryInto<Uri>,
{
    let request_builder = Request::builder()
        .method("POST")
        .uri(into_uri(uri)?)
        .header(CONTENT_TYPE, "application/x-www-form-urlencoded");
    let mut serializer = Serializer::new(String::new());
    serializer.append_pair("redirect_uri", &into_uri(redirect_uri)?.to_string());
    serializer.append_pair("grant_type", "authorization_code");
    serializer.append_pair("response_type", "code");
    serializer.append_pair(
        "scope",
        &scopes
            .as_ref()
            .map_or_else(|| "openid".to_owned(), |s| s.join(" ")),
    );
    if let Some(state) = &auth.state {
        serializer.append_pair("state", state);
    }
    if let Some(nonce) = &auth.nonce {
        serializer.append_pair("nonce", nonce);
    }
    serializer.append_pair("client_id", &auth.client_id);

    let body = match &auth.scheme {
        AuthenticationScheme::Basic(client_credentials) => {
            let basic = BASE64.encode(
                format!("{}:{}", &auth.client_id, client_credentials.client_secret).as_bytes(),
            );
            request_builder
                .header(AUTHORIZATION, format!("Basic {}", basic))
                .body(Vec::from(serializer.finish()))
        }
        AuthenticationScheme::Post(client_credentials) => request_builder.body(Vec::from(
            serializer
                .append_pair("client_secret", &client_credentials.client_secret)
                .finish(),
        )),
        AuthenticationScheme::Pkce(pkce) => request_builder.body(Vec::from(
            serializer
                .append_pair("code_challenge", &pkce.code_challenge)
                .append_pair("code_challenge_method", &pkce.code_challenge_method)
                .finish(),
        )),
    }?;
    Ok(body)
}

/// This is the schema of the server's response.
#[derive(serde::Deserialize, Debug)]
struct TokenExchangeResponse {
    /// The actual token
    access_token: String,
    /// The token type - most often `bearer`
    token_type: String,
    /// The time until the token expires and a new one needs to be requested
    expires_in: Option<i64>,
    /// The scope used for this token - most often `openid`
    scope: String,
    /// A JSON Web Token that contains information about an authentication event
    /// and claims about the authenticated user.
    id_token: Option<String>,
    /// An opaque refresh token. This is returned if the offline_access scope is
    /// granted.
    refresh_token: Option<String>,
}

/// This is the schema of the server's response.
#[derive(Debug, Clone, Eq, PartialEq)]
pub struct Token {
    /// The actual token
    pub access_token: String,
    /// The token type - most often `bearer`
    pub token_type: String,
    /// The time until the token expires and a new one needs to be requested
    pub expires_in: Option<i64>,
    /// The time until the token expires and a new one needs to be requested
    pub expires_in_timestamp: Option<i64>,
    /// The scope used for this token - most often `openid`
    pub scope: String,
    /// A JSON Web Token that contains information about an authentication event
    /// and claims about the authenticated user.
    pub id_token: Option<String>,
    /// An opaque refresh token. This is returned if the offline_access scope is
    /// granted.
    pub refresh_token: Option<String>,
}

impl Token {
    /// Once a response has been received for a token request, call this
    /// method to deserialize the token and store it in the cache so that
    /// future API requests don't have to retrieve a new token, until it
    /// expires.
    pub fn from_response<S>(response: http::Response<S>) -> Result<Self, Error>
    where
        S: AsRef<[u8]>,
    {
        parse_token_response(response)
    }
}

impl From<TokenExchangeResponse> for Token {
    fn from(t: TokenExchangeResponse) -> Token {
        let expires_ts = t.expires_in.and_then(|time_until| {
            SystemTime::now()
                .duration_since(UNIX_EPOCH) // Only an err if time moved backwards
                .ok()
                .and_then(|time_stamp| time_stamp.as_secs().try_into().ok()) // Only an err after year 2264
                .map(|now_as_seconds: i64| time_until + now_as_seconds)
        });

        Token {
            access_token: t.access_token,
            token_type: t.token_type,
            refresh_token: t.refresh_token,
            expires_in: t.expires_in,
            expires_in_timestamp: expires_ts,
            scope: t.scope,
            id_token: t.id_token,
        }
    }
}

/// Construct a token exchange request object
/// For [PKCE flow](https://tools.ietf.org/html/rfc7636#section-4.1) pass in the `code_verifier`
/// and omit the `client_secret`.
///
/// For [authorization code flow](https://auth0.com/docs/flows/authorization-code-flow) pass in
/// `client_secret` and omit `code_verifier`.
///
/// Also supports edge cases where i.e. a development machine requires both
/// `client_secret` and `code_verifier`. Just pass in them both in such case.
pub fn exchange_token_request<ReqUri, RedirectUri>(
    uri: ReqUri,
    redirect_uri: RedirectUri,
    auth: &ClientAuthentication,
    auth_code: &str,
) -> Result<Request<Vec<u8>>, RequestError>
where
    ReqUri: TryInto<Uri>,
    RedirectUri: TryInto<Uri>,
{
    let mut serializer = Serializer::new(String::new());
    serializer.append_pair("redirect_uri", &into_uri(redirect_uri)?.to_string());
    serializer.append_pair("grant_type", "authorization_code");
    serializer.append_pair("code", auth_code);
    let request_builder = Request::builder()
        .method("POST")
        .uri(into_uri(uri)?)
        .header(CONTENT_TYPE, "application/x-www-form-urlencoded");
    serializer.append_pair("client_id", &auth.client_id);
    let body = match &auth.scheme {
        AuthenticationScheme::Basic(client_credentials) => {
            let basic = BASE64.encode(
                format!("{}:{}", &auth.client_id, client_credentials.client_secret).as_bytes(),
            );
            request_builder
                .header(AUTHORIZATION, format!("Basic {}", basic))
                .body(Vec::from(serializer.finish()))
        }
        AuthenticationScheme::Post(client_credentials) => request_builder.body(Vec::from(
            serializer
                .append_pair("client_secret", &client_credentials.client_secret)
                .finish(),
        )),
        AuthenticationScheme::Pkce(pkce) => {
            if let Some(client_secret) = &pkce.client_secret {
                serializer.append_pair("client_secret", client_secret);
            }
            request_builder.body(Vec::from(
                serializer
                    .append_pair("code_verifier", &pkce.code_verifier)
                    .finish(),
            ))
        }
    }?;
    Ok(body)
}

pub(crate) fn into_uri<U: TryInto<Uri>>(uri: U) -> Result<Uri, RequestError> {
    uri.try_into().map_err(|_err| RequestError::InvalidUri)
}

pub(crate) fn user_info_request<ReqUri>(
    uri: ReqUri,
    access_token: &str,
) -> Result<Request<Vec<u8>>, RequestError>
where
    ReqUri: TryInto<Uri>,
{
    Ok(Request::get(into_uri(uri)?)
        .header(AUTHORIZATION, format!("Bearer {}", access_token))
        .body(vec![])?)
}

/// Once a response has been received for a token request, call this
/// method to deserialize the token and store it in the cache so that
/// future API requests don't have to retrieve a new token, until it
/// expires.
pub fn parse_token_response<S>(response: http::Response<S>) -> Result<Token, Error>
where
    S: AsRef<[u8]>,
{
    let (parts, body) = response.into_parts();

    if !parts.status.is_success() {
        println!("{:?}", core::str::from_utf8(body.as_ref()));
        return Err(Error::HttpStatus(parts.status));
    }

    let token_res: TokenExchangeResponse = serde_json::from_slice(body.as_ref())?;
    let token: Token = token_res.into();

    Ok(token)
}

pub fn refresh_token_request<ReqUri>(
    uri: ReqUri,
    auth: &ClientAuthentication,
    refresh_token: &str,
) -> Result<Request<Vec<u8>>, RequestError>
where
    ReqUri: TryInto<Uri>,
{
    let mut partial = Serializer::new(String::new());
    partial.append_pair("grant_type", "refresh_token");
    partial.append_pair("refresh_token", refresh_token);
    let request_builder = Request::builder()
        .method("POST")
        .uri(into_uri(uri)?)
        .header(CONTENT_TYPE, "application/x-www-form-urlencoded");
    partial.append_pair("client_id", &auth.client_id);
    let body = match &auth.scheme {
        AuthenticationScheme::Basic(client_credentials) => {
            let basic = BASE64.encode(
                format!("{}:{}", &auth.client_id, client_credentials.client_secret).as_bytes(),
            );
            request_builder
                .header(AUTHORIZATION, format!("Basic {}", basic))
                .body(Vec::from(partial.finish()))
        }
        AuthenticationScheme::Post(client_credentials) => request_builder.body(Vec::from(
            partial
                .append_pair("client_secret", &client_credentials.client_secret)
                .finish(),
        )),
        AuthenticationScheme::Pkce(pkce) => {
            if let Some(client_secret) = &pkce.client_secret {
                partial.append_pair("client_secret", client_secret);
            }
            request_builder.body(Vec::from(
                partial
                    .append_pair("code_verifier", &pkce.code_verifier)
                    .finish(),
            ))
        }
    }?;
    Ok(body)
}

#[cfg(test)]
mod test {
    use super::*;
    use crate::auth_scheme::PkceCredentials;
    use std::str;

    #[test]
    fn pkce_flow_exchange() {
        let spooky_secret_verifier = "the_secret_verifier".to_owned();
        let client_credentials = ClientAuthentication::new(
            "client_id".to_owned(),
            AuthenticationScheme::Pkce(PkceCredentials::new(
                "ch".to_owned(),
                "&S256".to_owned(),
                spooky_secret_verifier,
                None,
            )),
            None,
            None,
        );
        let request = exchange_token_request(
            "https://www.example.com/",
            "http://localhost:8000/",
            &client_credentials,
            "auth-code",
        )
        .unwrap();

        let body = str::from_utf8(request.body()).unwrap();

        // should not have client_secret parameter
        assert!(!body.contains("client_secret"));
        assert!(body.contains("code_verifier"));
    }
}