rullst-connect 10.0.2

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
use crate::client::HttpClientExt;
use crate::provider::Provider;
use crate::user::ConnectUser;
use async_trait::async_trait;
use serde_json::Value;

crate::define_provider!(GithubProvider, "user:email");

impl GithubProvider {
    async fn get_user_from_form(
        &self,
        form_data: &crate::provider::TokenExchangeForm<'_>,
    ) -> Result<ConnectUser, crate::error::ConnectError> {
        // 1. Exchange authorization code for access token
        let token_res = self
            .http_client
            .post("https://github.com/login/oauth/access_token")
            .header("Accept", "application/json")
            .form(form_data)
            .send()
            .await?
            .error_for_status()?
            .json::<Value>()
            .await?;

        if let Some(err) = token_res["error"].as_str() {
            let err_desc = token_res["error_description"].as_str().unwrap_or("");
            return Err(crate::error::ConnectError::Token(format!(
                "Provider returned error: {} - {}",
                err, err_desc
            )));
        }

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

        let mut user = 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 GithubProvider {
    crate::impl_standard_redirect_url!("https://github.com/login/oauth/authorize");

    async fn get_user(
        &self,
        params: crate::provider::ExchangeParams<'_>,
    ) -> Result<ConnectUser, crate::error::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: None,
            redirect_uri: self.redirect_url.as_str(),
            code_verifier: params.code_verifier,
        };
        self.get_user_from_form(&form_data).await
    }

    async fn get_user_from_token(
        &self,
        access_token: &str,
    ) -> Result<ConnectUser, crate::error::ConnectError> {
        // 2. Fetch user profile
        let user_res = self
            .http_client
            .get("https://api.github.com/user")
            .bearer_auth(access_token)
            .header("User-Agent", "rullst-connect") // GitHub API requires User-Agent
            .send()
            .await?
            .error_for_status()?
            .json::<Value>()
            .await?;

        // 3. Map to generic ConnectUser
        Ok(ConnectUser {
            id: user_res["id"]
                .as_i64()
                .ok_or_else(|| crate::error::ConnectError::Provider("Missing id".to_string()))?
                .to_string(),
            name: user_res["name"]
                .as_str()
                .unwrap_or(user_res["login"].as_str().unwrap_or(""))
                .to_string(),
            email: user_res["email"].as_str().map(String::from),
            avatar_url: user_res["avatar_url"].as_str().map(String::from),
            email_verified: None,
            raw_data: user_res,
            access_token: secrecy::SecretString::from(access_token.to_string()),
            refresh_token: None,
            expires_in: None,
        })
    }

    fn token_url(&self) -> String {
        "https://github.com/login/oauth/access_token".to_string()
    }

    crate::impl_standard_refresh_token!();

    async fn request_device_code(
        &self,
    ) -> Result<crate::user::DeviceAuthorizationResponse, crate::error::ConnectError> {
        let mut form = vec![("client_id", self.client_id.as_str())];
        if !self.scopes.is_empty() {
            form.push(("scope", self.scopes.as_str()));
        }

        let res = self
            .http_client
            .post("https://github.com/login/device/code")
            .header("Accept", "application/json")
            .form(&form)
            .send()
            .await?
            .error_for_status()?
            .json::<Value>()
            .await?;

        let device_code = res["device_code"]
            .as_str()
            .map(String::from)
            .ok_or_else(|| {
                crate::error::ConnectError::Provider(
                    "Missing device_code from Github response".to_string(),
                )
            })?;
        let user_code = res["user_code"].as_str().map(String::from).ok_or_else(|| {
            crate::error::ConnectError::Provider(
                "Missing user_code from Github response".to_string(),
            )
        })?;
        let verification_uri = res["verification_uri"]
            .as_str()
            .map(String::from)
            .ok_or_else(|| {
                crate::error::ConnectError::Provider(
                    "Missing verification_uri from Github response".to_string(),
                )
            })?;

        Ok(crate::user::DeviceAuthorizationResponse {
            device_code,
            user_code,
            verification_uri,
            verification_uri_complete: res["verification_uri_complete"].as_str().map(String::from),
            expires_in: res["expires_in"].as_u64().unwrap_or(900),
            interval: res["interval"].as_u64(),
        })
    }

    async fn poll_device_token(
        &self,
        device_code: &str,
    ) -> Result<ConnectUser, crate::error::ConnectError> {
        let token_res = self
            .http_client
            .post(self.token_url())
            .header("Accept", "application/json")
            .form(&[
                ("client_id", self.client_id.as_str()),
                ("device_code", device_code),
                ("grant_type", "urn:ietf:params:oauth:grant-type:device_code"),
            ])
            .send()
            .await?
            .error_for_status()?
            .json::<Value>()
            .await?;

        if let Some(err) = token_res["error"].as_str() {
            let err_desc = token_res["error_description"].as_str().unwrap_or("");
            return Err(crate::error::ConnectError::Token(format!(
                "Provider returned error: {} - {}",
                err, err_desc
            )));
        }

        let access_token = token_res["access_token"].as_str().ok_or_else(|| {
            crate::error::ConnectError::Token(
                "Failed to get access_token during device poll. (Authorization pending?)"
                    .to_string(),
            )
        })?;

        let mut user = 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)
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::client::{HttpClient, HttpRequest, HttpResponse};
    use serde_json::json;
    use std::sync::Arc;

    struct MockGithubClient {
        token_status: u16,
        token_body: serde_json::Value,
        user_status: u16,
        user_body: serde_json::Value,
        device_status: u16,
        device_body: serde_json::Value,
    }

    #[async_trait]
    impl HttpClient for MockGithubClient {
        async fn execute(
            &self,
            req: HttpRequest,
        ) -> Result<HttpResponse, crate::error::ConnectError> {
            if req.url.contains("access_token") {
                Ok(HttpResponse {
                    status: self.token_status,
                    body: self.token_body.clone(),
                })
            } else if req.url.contains("device/code") {
                Ok(HttpResponse {
                    status: self.device_status,
                    body: self.device_body.clone(),
                })
            } else {
                Ok(HttpResponse {
                    status: self.user_status,
                    body: self.user_body.clone(),
                })
            }
        }
    }

    #[tokio::test]
    async fn test_github_get_user() {
        let provider = GithubProvider::new(
            "client_id".to_string(),
            secrecy::SecretString::from("client_secret".to_string()),
            "https://redirect.url".to_string(),
        )
        .with_http_client(Arc::new(MockGithubClient {
            token_status: 200,
            token_body: json!({
                "access_token": "mock_token",
                "token_type": "bearer",
                "scope": "user:email"
            }),
            user_status: 200,
            user_body: json!({
                "id": 1234567,
                "login": "octocat",
                "name": "monalisa octocat",
                "email": "octocat@github.com",
                "avatar_url": "https://github.com/images/error/octocat_happy.gif"
            }),
            device_status: 200,
            device_body: json!({}),
        }));

        let params = crate::provider::ExchangeParams {
            auth_code: "mock_code",
            code_verifier: None,
            expected_nonce: None,
        };
        let user = provider.get_user(params).await.expect("Failed to get user");
        assert_eq!(user.id, "1234567");
        assert_eq!(user.name, "monalisa octocat");
        assert_eq!(user.email, Some("octocat@github.com".to_string()));
        assert_eq!(
            user.avatar_url,
            Some("https://github.com/images/error/octocat_happy.gif".to_string())
        );
    }

    #[tokio::test]
    async fn test_github_token_error() {
        let provider = GithubProvider::new(
            "client_id".to_string(),
            secrecy::SecretString::from("client_secret".to_string()),
            "https://redirect.url".to_string(),
        )
        .with_http_client(Arc::new(MockGithubClient {
            token_status: 400,
            token_body: json!({"error": "invalid_grant"}),
            user_status: 200,
            user_body: json!({}),
            device_status: 200,
            device_body: json!({}),
        }));

        let err = provider
            .get_user(crate::provider::ExchangeParams {
                auth_code: "code",
                ..Default::default()
            })
            .await
            .unwrap_err();

        assert!(matches!(
            err,
            crate::error::ConnectError::ProviderApiError { .. }
        ));
    }

    #[tokio::test]
    async fn test_github_request_device_code_success() {
        let provider = GithubProvider::new(
            "client_id".to_string(),
            secrecy::SecretString::from("client_secret".to_string()),
            "https://redirect.url".to_string(),
        )
        .with_http_client(Arc::new(MockGithubClient {
            token_status: 200,
            token_body: json!({}),
            user_status: 200,
            user_body: json!({}),
            device_status: 200,
            device_body: json!({
                "device_code": "device_123",
                "user_code": "user_456",
                "verification_uri": "https://github.com/login/device",
                "expires_in": 900,
                "interval": 5
            }),
        }));

        let res = provider.request_device_code().await.unwrap();
        assert_eq!(res.device_code, "device_123");
        assert_eq!(res.user_code, "user_456");
        assert_eq!(res.verification_uri, "https://github.com/login/device");
    }

    #[tokio::test]
    async fn test_github_poll_device_token_success() {
        let provider = GithubProvider::new(
            "client_id".to_string(),
            secrecy::SecretString::from("client_secret".to_string()),
            "https://redirect.url".to_string(),
        )
        .with_http_client(Arc::new(MockGithubClient {
            token_status: 200,
            token_body: json!({
                "access_token": "mock_token",
                "token_type": "bearer",
                "scope": "user:email"
            }),
            user_status: 200,
            user_body: json!({
                "id": 1234567,
                "login": "octocat",
                "name": "monalisa octocat",
                "email": "octocat@github.com",
                "avatar_url": "https://github.com/images/error/octocat_happy.gif"
            }),
            device_status: 200,
            device_body: json!({}),
        }));

        let user = provider.poll_device_token("device_123").await.unwrap();
        assert_eq!(user.id, "1234567");
    }

    #[tokio::test]
    async fn test_github_poll_device_token_error() {
        let provider = GithubProvider::new(
            "client_id".to_string(),
            secrecy::SecretString::from("client_secret".to_string()),
            "https://redirect.url".to_string(),
        )
        .with_http_client(Arc::new(MockGithubClient {
            token_status: 200, // Github returns 200 for authorization_pending
            token_body: json!({
                "error": "authorization_pending",
                "error_description": "User has not yet entered code."
            }),
            user_status: 200,
            user_body: json!({}),
            device_status: 200,
            device_body: json!({}),
        }));

        let err = provider.poll_device_token("device_123").await.unwrap_err();
        assert!(
            matches!(err, crate::error::ConnectError::Token(msg) if msg.contains("authorization_pending"))
        );
    }

    #[tokio::test]
    async fn test_github_poll_device_token_missing_token() {
        let provider = GithubProvider::new(
            "client_id".to_string(),
            secrecy::SecretString::from("client_secret".to_string()),
            "https://redirect.url".to_string(),
        )
        .with_http_client(Arc::new(MockGithubClient {
            token_status: 200,
            token_body: json!({}), // No access_token and no error
            user_status: 200,
            user_body: json!({}),
            device_status: 200,
            device_body: json!({}),
        }));

        let err = provider.poll_device_token("device_123").await.unwrap_err();
        assert!(
            matches!(err, crate::error::ConnectError::Token(msg) if msg.contains("Failed to get access_token during device poll"))
        );
    }
}