rullst-connect 10.0.1

OAuth2 Social Login for Rust web frameworks.
Documentation
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
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
use crate::client::{HttpClient, HttpClientExt};
use crate::error::ConnectError;
use crate::provider::Provider;
use crate::user::ConnectUser;
use async_trait::async_trait;
use serde_json::Value;
use std::sync::Arc;

pub struct OidcProvider {
    pub(crate) client_id: String,
    pub(crate) client_secret: secrecy::SecretString,
    pub(crate) redirect_url: String,
    pub(crate) http_client: Arc<dyn HttpClient>,
    pub(crate) scopes: String,
    pub(crate) state: Option<String>,
    pub(crate) pkce_challenge: Option<String>,

    pub authorization_endpoint: String,
    pub token_endpoint: String,
    pub userinfo_endpoint: String,
    pub(crate) jwks_uri: String,
    pub(crate) jwks: tokio::sync::OnceCell<jsonwebtoken::jwk::JwkSet>,
    pub issuer: String,
}

impl OidcProvider {
    /// Discovers the OIDC configuration from the issuer URL and creates a new provider.
    pub async fn discover(
        issuer_url: &str,
        client_id: String,
        client_secret: String,
        redirect_url: String,
    ) -> Result<Self, ConnectError> {
        let client: Arc<dyn HttpClient> = crate::client::DEFAULT_HTTP_CLIENT.clone();
        Self::discover_with_client(issuer_url, client_id, client_secret, redirect_url, client).await
    }

    /// Internal method that performs OIDC discovery using a provided HTTP client.
    /// This exists to enable injecting mock clients in tests.
    pub(crate) async fn discover_with_client(
        issuer_url: &str,
        client_id: String,
        client_secret: String,
        redirect_url: String,
        client: Arc<dyn HttpClient>,
    ) -> Result<Self, ConnectError> {
        if !issuer_url.starts_with("http") {
            return Err(crate::error::ConnectError::Provider(
                "OIDC Error: issuer_url must be a valid HTTP/HTTPS URL".to_string(),
            ));
        }
        if !redirect_url.starts_with("http") {
            return Err(crate::error::ConnectError::Provider(
                "OIDC Error: redirect_url must be a valid HTTP/HTTPS URL".to_string(),
            ));
        }
        if client_id.is_empty() {
            return Err(crate::error::ConnectError::Provider(
                "OIDC Error: client_id cannot be empty".to_string(),
            ));
        }
        if client_secret.is_empty() {
            return Err(crate::error::ConnectError::Provider(
                "OIDC Error: client_secret cannot be empty".to_string(),
            ));
        }

        let well_known_url = if issuer_url.ends_with('/') {
            format!("{}.well-known/openid-configuration", issuer_url)
        } else {
            format!("{}/.well-known/openid-configuration", issuer_url)
        };

        let res = client
            .get(&well_known_url)
            .send()
            .await?
            .error_for_status()?
            .json::<Value>()
            .await?;

        let authorization_endpoint = res["authorization_endpoint"]
            .as_str()
            .ok_or_else(|| {
                crate::error::ConnectError::Provider(
                    "Missing authorization_endpoint in OIDC config".to_string(),
                )
            })?
            .to_string();

        let token_endpoint = res["token_endpoint"]
            .as_str()
            .ok_or_else(|| {
                crate::error::ConnectError::Provider(
                    "Missing token_endpoint in OIDC config".to_string(),
                )
            })?
            .to_string();

        let userinfo_endpoint = res["userinfo_endpoint"]
            .as_str()
            .ok_or_else(|| {
                crate::error::ConnectError::Provider(
                    "Missing userinfo_endpoint in OIDC config".to_string(),
                )
            })?
            .to_string();

        let jwks_uri = res["jwks_uri"]
            .as_str()
            .ok_or_else(|| {
                crate::error::ConnectError::Provider("Missing jwks_uri in OIDC config".to_string())
            })?
            .to_string();

        let issuer = res["issuer"]
            .as_str()
            .ok_or_else(|| {
                crate::error::ConnectError::Provider("Missing issuer in OIDC config".to_string())
            })?
            .to_string();

        Ok(Self {
            client_id,
            client_secret: client_secret.into(),
            redirect_url,
            http_client: client,
            scopes: "openid profile email".to_string(),
            state: None,
            pkce_challenge: None,
            authorization_endpoint,
            token_endpoint,
            userinfo_endpoint,
            jwks_uri,
            jwks: tokio::sync::OnceCell::new(),
            issuer,
        })
    }

    pub fn with_scopes(mut self, scopes: &[&str]) -> Self {
        self.scopes = scopes.join(" ");
        self
    }

    pub fn with_state(mut self, state: &str) -> Self {
        self.state = Some(state.to_owned());
        self
    }

    pub fn with_pkce(mut self, challenge: &str) -> Self {
        self.pkce_challenge = Some(challenge.to_owned());
        self
    }

    pub fn with_http_client(mut self, client: Arc<dyn HttpClient>) -> Self {
        self.http_client = client;
        self
    }

    async fn get_jwks(&self) -> Result<&jsonwebtoken::jwk::JwkSet, ConnectError> {
        self.jwks
            .get_or_try_init(|| async {
                let res = self
                    .http_client
                    .get(&self.jwks_uri)
                    .send()
                    .await?
                    .error_for_status()?
                    .json::<jsonwebtoken::jwk::JwkSet>()
                    .await?;
                Ok(res)
            })
            .await
    }

    #[tracing::instrument(skip(self, form_data))]
    async fn get_user_from_form(
        &self,
        form_data: &crate::provider::TokenExchangeForm<'_>,
        expected_nonce: Option<&str>,
    ) -> Result<ConnectUser, ConnectError> {
        let token_res = self
            .http_client
            .post(self.token_url())
            .form(form_data)
            .send()
            .await?
            .error_for_status()?
            .json::<Value>()
            .await?;

        let access_token = token_res["access_token"]
            .as_str()
            .ok_or_else(|| ConnectError::Token("Failed to get access_token".to_string()))?;

        let mut user = if let Some(id_token) = token_res["id_token"].as_str() {
            // Cryptographic OIDC Signature Validation
            let header = jsonwebtoken::decode_header(id_token).map_err(|e| {
                crate::error::ConnectError::Provider(format!(
                    "Failed to decode OIDC id_token header: {}",
                    e
                ))
            })?;

            if let Some(kid) = header.kid.as_ref() {
                let jwks = self.get_jwks().await?;
                let jwk = jwks.find(kid).ok_or_else(|| {
                    crate::error::ConnectError::Provider(format!(
                        "OIDC JWK with key ID '{}' not found",
                        kid
                    ))
                })?;
                let decoding_key = jsonwebtoken::DecodingKey::from_jwk(jwk).map_err(|e| {
                    crate::error::ConnectError::Provider(format!(
                        "Failed to build OIDC decoding key from JWK: {}",
                        e
                    ))
                })?;
                let alg = match header.alg {
                    jsonwebtoken::Algorithm::HS256
                    | jsonwebtoken::Algorithm::HS384
                    | jsonwebtoken::Algorithm::HS512 => jsonwebtoken::Algorithm::RS256,
                    other => other,
                };
                let mut validation = jsonwebtoken::Validation::new(alg);
                validation.set_audience(&[&self.client_id]);
                validation.set_issuer(&[&self.issuer]);
                validation.validate_exp = true;
                if expected_nonce.is_some() {
                    validation.set_required_spec_claims(&["nonce"]);
                }

                let token_data =
                    jsonwebtoken::decode::<Value>(id_token, &decoding_key, &validation).map_err(
                        |e| {
                            crate::error::ConnectError::Provider(format!(
                                "OIDC id_token signature or claims validation failed: {}",
                                e
                            ))
                        },
                    )?;
                let payload = token_data.claims;

                if let Some(nonce) = expected_nonce {
                    let token_nonce = payload["nonce"].as_str().unwrap_or("");
                    use subtle::ConstantTimeEq;
                    if token_nonce.len() != nonce.len()
                        || !bool::from(token_nonce.as_bytes().ct_eq(nonce.as_bytes()))
                    {
                        return Err(crate::error::ConnectError::Provider(
                            "OIDC id_token nonce mismatch".to_owned(),
                        ));
                    }
                }

                ConnectUser {
                    id: payload["sub"].as_str().map(String::from).ok_or_else(|| {
                        crate::error::ConnectError::Provider("Missing sub in id_token".to_owned())
                    })?,
                    name: payload["name"].as_str().map(String::from).ok_or_else(|| {
                        crate::error::ConnectError::Provider("Missing name in id_token".to_owned())
                    })?,
                    email: payload["email"].as_str().map(String::from),
                    avatar_url: payload["picture"].as_str().map(String::from),
                    email_verified: payload["email_verified"].as_bool(),
                    raw_data: payload,
                    access_token: secrecy::SecretString::from(access_token.to_owned()),
                    refresh_token: None,
                    expires_in: None,
                }
            } else {
                return Err(crate::error::ConnectError::Provider(
                    "Missing 'kid' header in OIDC id_token".to_owned(),
                ));
            }
        } else {
            use crate::provider::Provider;
            self.get_user_from_token(access_token).await?
        };

        user.refresh_token = token_res["refresh_token"]
            .as_str()
            .map(|s| secrecy::SecretString::from(s.to_string()));
        user.expires_in = token_res["expires_in"]
            .as_u64()
            .or_else(|| token_res["expires_in"].as_i64().map(|v| v as u64));

        Ok(user)
    }
}

#[async_trait]
impl Provider for OidcProvider {
    crate::impl_standard_redirect_url!("{}");

    #[tracing::instrument(skip(self, params))]
    async fn get_user(
        &self,
        params: crate::provider::ExchangeParams<'_>,
    ) -> Result<ConnectUser, ConnectError> {
        let form_data = crate::provider::TokenExchangeForm {
            client_id: self.client_id.as_str(),
            client_secret: Some(secrecy::ExposeSecret::expose_secret(&self.client_secret)),
            code: params.auth_code,
            grant_type: Some("authorization_code"),
            redirect_uri: self.redirect_url.as_str(),
            code_verifier: params.code_verifier,
        };
        self.get_user_from_form(&form_data, params.expected_nonce)
            .await
    }

    #[tracing::instrument(skip(self, access_token))]
    async fn get_user_from_token(&self, access_token: &str) -> Result<ConnectUser, ConnectError> {
        let user_res = self
            .http_client
            .get(&self.userinfo_endpoint)
            .bearer_auth(access_token)
            .send()
            .await?
            .error_for_status()?
            .json::<Value>()
            .await?;

        Ok(ConnectUser {
            id: user_res["sub"].as_str().map(String::from).ok_or_else(|| {
                crate::error::ConnectError::Provider("Missing sub in userinfo".to_owned())
            })?,
            name: user_res["name"].as_str().map(String::from).ok_or_else(|| {
                crate::error::ConnectError::Provider("Missing name in userinfo".to_owned())
            })?,
            email: user_res["email"].as_str().map(String::from),
            avatar_url: user_res["picture"].as_str().map(String::from),
            email_verified: user_res["email_verified"].as_bool(),
            raw_data: user_res,
            access_token: secrecy::SecretString::from(access_token.to_owned()),
            refresh_token: None,
            expires_in: None,
        })
    }

    fn token_url(&self) -> String {
        self.token_endpoint.clone()
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use serde_json::json;
    use std::sync::Arc;

    struct MockOidcClient {
        config_body: Value,
        jwks_body: Value,
        captured_urls: tokio::sync::Mutex<Vec<String>>,
    }

    #[async_trait]
    impl HttpClient for MockOidcClient {
        async fn execute(
            &self,
            req: crate::client::HttpRequest,
        ) -> Result<crate::client::HttpResponse, crate::error::ConnectError> {
            self.captured_urls.lock().await.push(req.url.clone());
            if req.url.contains("openid-configuration") {
                Ok(crate::client::HttpResponse {
                    status: 200,
                    body: self.config_body.clone(),
                })
            } else if req.url.contains("jwks") {
                Ok(crate::client::HttpResponse {
                    status: 200,
                    body: self.jwks_body.clone(),
                })
            } else {
                Err(crate::error::ConnectError::Provider(
                    "Not found".to_string(),
                ))
            }
        }
    }

    #[tokio::test]
    async fn test_oidc_discover_success_with_slash() {
        let mock_client = Arc::new(MockOidcClient {
            config_body: json!({
                "authorization_endpoint": "https://auth.com/authorize",
                "token_endpoint": "https://auth.com/token",
                "userinfo_endpoint": "https://auth.com/userinfo",
                "jwks_uri": "https://auth.com/jwks",
                "issuer": "https://issuer.com"
            }),
            jwks_body: json!({
                "keys": []
            }),
            captured_urls: tokio::sync::Mutex::new(vec![]),
        });

        // Test with trailing slash
        let _provider = OidcProvider::discover_with_client(
            "https://issuer.com/",
            "client_id".to_string(),
            "client_secret".to_string(),
            "https://redirect.url".to_string(),
            mock_client.clone(),
        )
        .await
        .expect("OIDC discovery failed");

        let urls = mock_client.captured_urls.lock().await;
        assert_eq!(urls.len(), 1);
        assert_eq!(
            urls[0],
            "https://issuer.com/.well-known/openid-configuration"
        );
    }

    #[tokio::test]
    async fn test_oidc_discover_success_no_slash() {
        let mock_client = Arc::new(MockOidcClient {
            config_body: json!({
                "authorization_endpoint": "https://auth.com/authorize",
                "token_endpoint": "https://auth.com/token",
                "userinfo_endpoint": "https://auth.com/userinfo",
                "jwks_uri": "https://auth.com/jwks",
                "issuer": "https://issuer.com"
            }),
            jwks_body: json!({
                "keys": []
            }),
            captured_urls: tokio::sync::Mutex::new(vec![]),
        });

        // Test without trailing slash
        let _provider = OidcProvider::discover_with_client(
            "https://issuer.com",
            "client_id".to_string(),
            "client_secret".to_string(),
            "https://redirect.url".to_string(),
            mock_client.clone(),
        )
        .await
        .expect("OIDC discovery failed");

        let urls = mock_client.captured_urls.lock().await;
        assert_eq!(urls.len(), 1);
        assert_eq!(
            urls[0],
            "https://issuer.com/.well-known/openid-configuration"
        );
    }

    #[tokio::test]
    async fn test_oidc_discover_missing_token_endpoint() {
        let mock_client = Arc::new(MockOidcClient {
            config_body: json!({
                "authorization_endpoint": "https://auth.com/authorize",
                "userinfo_endpoint": "https://auth.com/userinfo",
                "jwks_uri": "https://auth.com/jwks",
                "issuer": "https://issuer.com"
            }),
            jwks_body: json!({
                "keys": []
            }),
            captured_urls: tokio::sync::Mutex::new(vec![]),
        });

        let res = OidcProvider::discover_with_client(
            "https://issuer.com",
            "client_id".to_string(),
            "client_secret".to_string(),
            "https://redirect.url".to_string(),
            mock_client.clone(),
        )
        .await;

        match res {
            Err(crate::error::ConnectError::Provider(msg)) => {
                assert!(msg.contains("Missing token_endpoint"));
            }
            Err(_) => panic!("Expected Provider error variant"),
            Ok(_) => panic!("Expected an error, but discover succeeded"),
        }
    }
}