Skip to main content

auth_framework/
providers.rs

1//! OAuth provider configurations and implementations.
2impl Default for UserProfile {
3    fn default() -> Self {
4        Self::new()
5    }
6}
7use crate::errors::{AuthError, Result};
8use crate::tokens::AuthToken;
9use base64::Engine;
10use reqwest::Client;
11use serde::{Deserialize, Serialize};
12use serde_json::Value;
13use std::collections::HashMap;
14use std::fmt;
15use url::Url;
16
17/// Supported OAuth providers.
18#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
19pub enum OAuthProvider {
20    /// GitHub OAuth provider
21    GitHub,
22
23    /// Google OAuth provider
24    Google,
25
26    /// Microsoft OAuth provider
27    Microsoft,
28
29    /// Discord OAuth provider
30    Discord,
31
32    /// Twitter OAuth provider
33    Twitter,
34
35    /// Facebook OAuth provider
36    Facebook,
37
38    /// LinkedIn OAuth provider
39    LinkedIn,
40
41    /// GitLab OAuth provider
42    GitLab,
43
44    /// Generic OAuth provider with custom configuration
45    Custom {
46        name: String,
47        config: Box<OAuthProviderConfig>,
48    },
49}
50
51/// OAuth provider configuration.
52#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
53pub struct OAuthProviderConfig {
54    /// Authorization endpoint URL
55    pub authorization_url: String,
56
57    /// Token endpoint URL
58    pub token_url: String,
59
60    /// Device authorization endpoint URL (for device flow)
61    pub device_authorization_url: Option<String>,
62
63    /// User info endpoint URL
64    pub userinfo_url: Option<String>,
65
66    /// Revocation endpoint URL
67    pub revocation_url: Option<String>,
68
69    /// Default scopes to request
70    pub default_scopes: Vec<String>,
71
72    /// Whether this provider supports PKCE
73    pub supports_pkce: bool,
74
75    /// Whether this provider supports refresh tokens
76    pub supports_refresh: bool,
77
78    /// Whether this provider supports device flow
79    pub supports_device_flow: bool,
80
81    /// Custom parameters to include in authorization requests
82    pub additional_params: HashMap<String, String>,
83}
84
85/// Device flow authorization response.
86#[derive(Clone, Serialize, Deserialize)]
87pub struct DeviceAuthorizationResponse {
88    /// Device code
89    pub device_code: String,
90
91    /// User code that the user should enter
92    pub user_code: String,
93
94    /// URL where the user should verify the device
95    pub verification_uri: String,
96
97    /// Complete verification URL (optional)
98    pub verification_uri_complete: Option<String>,
99
100    /// Interval in seconds between polling requests
101    pub interval: u64,
102
103    /// Device code expires in seconds
104    pub expires_in: u64,
105}
106
107impl std::fmt::Debug for DeviceAuthorizationResponse {
108    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
109        let mut d = f.debug_struct("DeviceAuthorizationResponse");
110        d.field(
111            "device_code",
112            &crate::utils::redact::redacted(&self.device_code),
113        );
114        d.field(
115            "user_code",
116            &crate::utils::redact::redacted(&self.user_code),
117        );
118        d.field("verification_uri", &self.verification_uri);
119        d.field(
120            "verification_uri_complete",
121            &crate::utils::redact::redacted(&self.verification_uri_complete),
122        );
123        d.field("interval", &self.interval);
124        d.field("expires_in", &self.expires_in);
125        d.finish()
126    }
127}
128
129/// Standardized user profile across all providers.
130#[derive(Debug, Clone, Serialize, Deserialize)]
131pub struct UserProfile {
132    /// Unique identifier from the provider
133    pub id: Option<String>,
134
135    /// Provider that authenticated this user
136    pub provider: Option<String>,
137
138    /// Username or login name
139    pub username: Option<String>,
140
141    /// Display name
142    pub name: Option<String>,
143
144    /// Email address
145    pub email: Option<String>,
146
147    /// Whether email is verified
148    pub email_verified: Option<bool>,
149
150    /// Profile picture URL
151    pub picture: Option<String>,
152
153    /// Locale/language preference
154    pub locale: Option<String>,
155
156    /// Provider-specific additional data
157    pub additional_data: HashMap<String, serde_json::Value>,
158}
159
160#[cfg(feature = "postgres-storage")]
161use sqlx::{Decode, Postgres, Type, postgres::PgValueRef};
162
163#[cfg(feature = "postgres-storage")]
164impl<'r> Decode<'r, Postgres> for UserProfile {
165    fn decode(value: PgValueRef<'r>) -> std::result::Result<Self, sqlx::error::BoxDynError> {
166        let json: serde_json::Value = <serde_json::Value as Decode<Postgres>>::decode(value)?;
167        serde_json::from_value(json).map_err(|e| Box::new(e) as sqlx::error::BoxDynError)
168    }
169}
170
171#[cfg(feature = "postgres-storage")]
172impl Type<Postgres> for UserProfile {
173    fn type_info() -> sqlx::postgres::PgTypeInfo {
174        <serde_json::Value as Type<Postgres>>::type_info()
175    }
176    fn compatible(ty: &sqlx::postgres::PgTypeInfo) -> bool {
177        <serde_json::Value as Type<Postgres>>::compatible(ty)
178    }
179}
180
181impl UserProfile {
182    /// Create a new empty user profile
183    pub fn new() -> Self {
184        Self {
185            id: None,
186            provider: None,
187            username: None,
188            name: None,
189            email: None,
190            email_verified: None,
191            picture: None,
192            locale: None,
193            additional_data: HashMap::new(),
194        }
195    }
196
197    /// Set user ID
198    pub fn with_id(mut self, id: impl Into<String>) -> Self {
199        self.id = Some(id.into());
200        self
201    }
202
203    /// Set provider
204    pub fn with_provider(mut self, provider: impl Into<String>) -> Self {
205        self.provider = Some(provider.into());
206        self
207    }
208
209    /// Set username
210    pub fn with_username(mut self, username: Option<impl Into<String>>) -> Self {
211        self.username = username.map(Into::into);
212        self
213    }
214
215    /// Set display name
216    pub fn with_name(mut self, name: Option<impl Into<String>>) -> Self {
217        self.name = name.map(Into::into);
218        self
219    }
220
221    /// Set email
222    pub fn with_email(mut self, email: Option<impl Into<String>>) -> Self {
223        self.email = email.map(Into::into);
224        self
225    }
226
227    /// Set email verification status
228    pub fn with_email_verified(mut self, verified: bool) -> Self {
229        self.email_verified = Some(verified);
230        self
231    }
232
233    /// Set profile picture URL
234    pub fn with_picture(mut self, picture: Option<impl Into<String>>) -> Self {
235        self.picture = picture.map(Into::into);
236        self
237    }
238
239    /// Set locale
240    pub fn with_locale(mut self, locale: Option<impl Into<String>>) -> Self {
241        self.locale = locale.map(Into::into);
242        self
243    }
244
245    /// Add additional provider-specific data
246    pub fn with_additional_data(
247        mut self,
248        key: impl Into<String>,
249        value: serde_json::Value,
250    ) -> Self {
251        self.additional_data.insert(key.into(), value);
252        self
253    }
254
255    /// Create a new user profile from an OAuth token response
256    pub fn from_token_response(
257        token: &OAuthTokenResponse,
258        provider: &OAuthProvider,
259    ) -> Option<Self> {
260        // Extract user info from ID token if present in additional fields
261        if let Some(id_token_value) = token.additional_fields.get("id_token")
262            && let Some(id_token) = id_token_value.as_str()
263            && let Ok(profile) = Self::from_id_token(id_token)
264        {
265            return Some(profile.with_provider(provider.to_string()));
266        }
267        None
268    }
269
270    /// Extract a user profile from an ID token (JWT)
271    pub fn from_id_token(id_token: &str) -> Result<Self> {
272        // Basic JWT parsing
273        let parts: Vec<&str> = id_token.split('.').collect();
274        if parts.len() != 3 {
275            return Err(AuthError::validation("Invalid JWT format"));
276        }
277
278        // Decode the payload (second part)
279        let payload = parts[1];
280        let padding_len = payload.len() % 4;
281        let padded_payload = if padding_len > 0 {
282            format!("{}{}", payload, "=".repeat(4 - padding_len))
283        } else {
284            payload.to_string()
285        };
286
287        // Decode base64
288        let decoded = base64::engine::general_purpose::URL_SAFE_NO_PAD
289            .decode(&padded_payload)
290            .map_err(|e| AuthError::validation(format!("Failed to decode JWT: {}", e)))?;
291
292        // Parse JSON
293        let json: Value = serde_json::from_slice(&decoded)
294            .map_err(|e| AuthError::validation(format!("Failed to parse JWT payload: {}", e)))?;
295
296        // Extract common claims
297        let mut profile = Self::new();
298
299        // Try common ID fields
300        if let Some(sub) = json.get("sub").and_then(|v| v.as_str()) {
301            profile = profile.with_id(sub);
302        } else if let Some(id) = json.get("id").and_then(|v| v.as_str()) {
303            profile = profile.with_id(id);
304        } else {
305            return Err(AuthError::validation("JWT missing subject claim"));
306        }
307
308        // Extract other common fields
309        if let Some(name) = json.get("name").and_then(|v| v.as_str()) {
310            profile = profile.with_name(Some(name));
311        }
312
313        if let Some(email) = json.get("email").and_then(|v| v.as_str()) {
314            profile = profile.with_email(Some(email));
315        }
316
317        if let Some(verified) = json.get("email_verified").and_then(|v| v.as_bool()) {
318            profile = profile.with_email_verified(verified);
319        }
320
321        if let Some(preferred_username) = json.get("preferred_username").and_then(|v| v.as_str()) {
322            profile = profile.with_username(Some(preferred_username));
323        }
324
325        if let Some(picture) = json.get("picture").and_then(|v| v.as_str()) {
326            profile = profile.with_picture(Some(picture));
327        }
328
329        if let Some(locale) = json.get("locale").and_then(|v| v.as_str()) {
330            profile = profile.with_locale(Some(locale));
331        }
332
333        // Store the entire claims as additional data
334        profile = profile.with_additional_data("id_token_claims", json);
335
336        Ok(profile)
337    }
338
339    /// Create an AuthToken with this profile's information
340    pub fn to_auth_token(&self, access_token: String) -> AuthToken {
341        let user_id = self.id.as_deref().unwrap_or("unknown").to_string();
342        let auth_method = self.provider.as_deref().unwrap_or("oauth").to_string();
343        let expires_in = std::time::Duration::from_secs(3600); // 1 hour default
344
345        let mut token = AuthToken::new(user_id.clone(), access_token, expires_in, auth_method);
346        token.subject = self.id.clone();
347        token.issuer = self.provider.clone();
348        token.user_profile = Some(self.clone());
349        token
350    }
351
352    /// Check if this profile has an ID
353    pub fn has_id(&self) -> bool {
354        self.id.is_some()
355    }
356
357    /// Get display name or fall back to username
358    pub fn display_name(&self) -> Option<&str> {
359        self.name.as_deref().or(self.username.as_deref())
360    }
361}
362
363/// OAuth token response from the provider.
364#[derive(Clone, Serialize, Deserialize)]
365pub struct OAuthTokenResponse {
366    /// Access token
367    pub access_token: String,
368
369    /// Token type (usually "Bearer")
370    pub token_type: String,
371
372    /// Token expiration in seconds
373    pub expires_in: Option<u64>,
374
375    /// Refresh token (if available)
376    pub refresh_token: Option<String>,
377
378    /// Granted scopes
379    pub scope: Option<String>,
380
381    /// Additional provider-specific fields
382    #[serde(flatten)]
383    pub additional_fields: HashMap<String, serde_json::Value>,
384}
385
386impl std::fmt::Debug for OAuthTokenResponse {
387    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
388        let mut d = f.debug_struct("OAuthTokenResponse");
389        d.field(
390            "access_token",
391            &crate::utils::redact::redacted(&self.access_token),
392        );
393        d.field("token_type", &self.token_type);
394        d.field("expires_in", &self.expires_in);
395        d.field(
396            "refresh_token",
397            &crate::utils::redact::redacted(&self.refresh_token),
398        );
399        d.field("scope", &self.scope);
400        d.field(
401            "additional_fields",
402            &crate::utils::redact::redacted(&self.additional_fields),
403        );
404        d.finish()
405    }
406}
407
408/// User information from OAuth provider.
409#[derive(Debug, Clone, Serialize, Deserialize)]
410pub struct OAuthUserInfo {
411    /// Unique user ID from the provider
412    pub id: String,
413
414    /// Username
415    pub username: Option<String>,
416
417    /// Display name
418    pub name: Option<String>,
419
420    /// Email address
421    pub email: Option<String>,
422
423    /// Whether email is verified
424    pub email_verified: Option<bool>,
425
426    /// Profile picture URL
427    pub picture: Option<String>,
428
429    /// Locale/language preference
430    pub locale: Option<String>,
431
432    /// Additional provider-specific fields
433    #[serde(flatten)]
434    pub additional_fields: HashMap<String, serde_json::Value>,
435}
436
437impl OAuthProvider {
438    /// Get the configuration for this provider.
439    pub fn config(&self) -> OAuthProviderConfig {
440        match self {
441            Self::GitHub => OAuthProviderConfig {
442                authorization_url: "https://github.com/login/oauth/authorize".to_string(),
443                token_url: "https://github.com/login/oauth/access_token".to_string(),
444                device_authorization_url: Some("https://github.com/login/device/code".to_string()),
445                userinfo_url: Some("https://api.github.com/user".to_string()),
446                revocation_url: None,
447                default_scopes: vec!["user:email".to_string()],
448                supports_pkce: true,
449                supports_refresh: false,
450                supports_device_flow: true,
451                additional_params: HashMap::new(),
452            },
453
454            Self::Google => OAuthProviderConfig {
455                authorization_url: "https://accounts.google.com/o/oauth2/v2/auth".to_string(),
456                token_url: "https://oauth2.googleapis.com/token".to_string(),
457                device_authorization_url: Some(
458                    "https://oauth2.googleapis.com/device/code".to_string(),
459                ),
460                userinfo_url: Some("https://www.googleapis.com/oauth2/v2/userinfo".to_string()),
461                revocation_url: Some("https://oauth2.googleapis.com/revoke".to_string()),
462                default_scopes: vec![
463                    "openid".to_string(),
464                    "profile".to_string(),
465                    "email".to_string(),
466                ],
467                supports_pkce: true,
468                supports_refresh: true,
469                supports_device_flow: true,
470                additional_params: HashMap::new(),
471            },
472
473            Self::Microsoft => OAuthProviderConfig {
474                authorization_url: "https://login.microsoftonline.com/common/oauth2/v2.0/authorize"
475                    .to_string(),
476                token_url: "https://login.microsoftonline.com/common/oauth2/v2.0/token".to_string(),
477                device_authorization_url: Some(
478                    "https://login.microsoftonline.com/common/oauth2/v2.0/devicecode".to_string(),
479                ),
480                userinfo_url: Some("https://graph.microsoft.com/v1.0/me".to_string()),
481                revocation_url: None,
482                default_scopes: vec![
483                    "openid".to_string(),
484                    "profile".to_string(),
485                    "email".to_string(),
486                ],
487                supports_pkce: true,
488                supports_refresh: true,
489                supports_device_flow: true,
490                additional_params: HashMap::new(),
491            },
492
493            Self::Discord => OAuthProviderConfig {
494                authorization_url: "https://discord.com/api/oauth2/authorize".to_string(),
495                token_url: "https://discord.com/api/oauth2/token".to_string(),
496                device_authorization_url: None,
497                userinfo_url: Some("https://discord.com/api/users/@me".to_string()),
498                revocation_url: Some("https://discord.com/api/oauth2/token/revoke".to_string()),
499                default_scopes: vec!["identify".to_string(), "email".to_string()],
500                supports_pkce: false,
501                supports_refresh: true,
502                supports_device_flow: false,
503                additional_params: HashMap::new(),
504            },
505
506            Self::Twitter => OAuthProviderConfig {
507                authorization_url: "https://twitter.com/i/oauth2/authorize".to_string(),
508                token_url: "https://api.twitter.com/2/oauth2/token".to_string(),
509                device_authorization_url: None,
510                userinfo_url: Some("https://api.twitter.com/2/users/me".to_string()),
511                revocation_url: Some("https://api.twitter.com/2/oauth2/revoke".to_string()),
512                default_scopes: vec!["tweet.read".to_string(), "users.read".to_string()],
513                supports_pkce: true,
514                supports_refresh: true,
515                supports_device_flow: false,
516                additional_params: HashMap::new(),
517            },
518
519            Self::Facebook => OAuthProviderConfig {
520                authorization_url: "https://www.facebook.com/v18.0/dialog/oauth".to_string(),
521                token_url: "https://graph.facebook.com/v18.0/oauth/access_token".to_string(),
522                device_authorization_url: None,
523                userinfo_url: Some("https://graph.facebook.com/me".to_string()),
524                revocation_url: None,
525                default_scopes: vec!["email".to_string(), "public_profile".to_string()],
526                supports_pkce: false,
527                supports_refresh: false,
528                supports_device_flow: false,
529                additional_params: HashMap::new(),
530            },
531
532            Self::LinkedIn => OAuthProviderConfig {
533                authorization_url: "https://www.linkedin.com/oauth/v2/authorization".to_string(),
534                token_url: "https://www.linkedin.com/oauth/v2/accessToken".to_string(),
535                device_authorization_url: None,
536                userinfo_url: Some("https://api.linkedin.com/v2/me".to_string()),
537                revocation_url: None,
538                default_scopes: vec!["r_liteprofile".to_string(), "r_emailaddress".to_string()],
539                supports_pkce: false,
540                supports_refresh: true,
541                supports_device_flow: false,
542                additional_params: HashMap::new(),
543            },
544
545            Self::GitLab => OAuthProviderConfig {
546                authorization_url: "https://gitlab.com/oauth/authorize".to_string(),
547                token_url: "https://gitlab.com/oauth/token".to_string(),
548                device_authorization_url: None,
549                userinfo_url: Some("https://gitlab.com/api/v4/user".to_string()),
550                revocation_url: Some("https://gitlab.com/oauth/revoke".to_string()),
551                default_scopes: vec!["read_user".to_string()],
552                supports_pkce: true,
553                supports_refresh: true,
554                supports_device_flow: false,
555                additional_params: HashMap::new(),
556            },
557
558            Self::Custom { config, .. } => *config.clone(),
559        }
560    }
561
562    /// Get the provider name.
563    pub fn name(&self) -> &str {
564        match self {
565            Self::GitHub => "github",
566            Self::Google => "google",
567            Self::Microsoft => "microsoft",
568            Self::Discord => "discord",
569            Self::Twitter => "twitter",
570            Self::Facebook => "facebook",
571            Self::LinkedIn => "linkedin",
572            Self::GitLab => "gitlab",
573            Self::Custom { name, .. } => name,
574        }
575    }
576
577    /// Create a custom OAuth provider.
578    pub fn custom(name: impl Into<String>, config: OAuthProviderConfig) -> Self {
579        Self::Custom {
580            name: name.into(),
581            config: Box::new(config),
582        }
583    }
584
585    /// Build authorization URL.
586    pub fn build_authorization_url(
587        &self,
588        client_id: &str,
589        redirect_uri: &str,
590        state: &str,
591        scopes: Option<&[String]>,
592        code_challenge: Option<&str>,
593    ) -> Result<String> {
594        let config = self.config();
595        let mut url = Url::parse(&config.authorization_url)
596            .map_err(|e| AuthError::config(format!("Invalid authorization URL: {e}")))?;
597
598        let scopes = scopes.unwrap_or(&config.default_scopes);
599
600        {
601            let mut query = url.query_pairs_mut();
602            query.append_pair("client_id", client_id);
603            query.append_pair("redirect_uri", redirect_uri);
604            query.append_pair("response_type", "code");
605            query.append_pair("state", state);
606
607            if !scopes.is_empty() {
608                query.append_pair("scope", &scopes.join(" "));
609            }
610
611            // Add PKCE challenge if supported and provided (Clippy-compliant)
612            if config.supports_pkce
613                && let Some(challenge) = code_challenge
614            {
615                query.append_pair("code_challenge", challenge);
616                query.append_pair("code_challenge_method", "S256");
617            }
618
619            // Add any additional parameters
620            for (key, value) in &config.additional_params {
621                query.append_pair(key, value);
622            }
623        }
624
625        Ok(url.to_string())
626    }
627
628    /// Exchange authorization code for tokens.
629    pub async fn exchange_code(
630        &self,
631        client_id: &str,
632        client_secret: &str,
633        authorization_code: &str,
634        redirect_uri: &str,
635        code_verifier: Option<&str>,
636    ) -> Result<OAuthTokenResponse> {
637        let config = self.config();
638        let client = reqwest::Client::new();
639
640        let mut params = vec![
641            ("grant_type", "authorization_code"),
642            ("client_id", client_id),
643            ("client_secret", client_secret),
644            ("code", authorization_code),
645            ("redirect_uri", redirect_uri),
646        ];
647
648        // Add PKCE verifier if provided
649        if let Some(verifier) = code_verifier {
650            params.push(("code_verifier", verifier));
651        }
652
653        let response = client.post(&config.token_url).form(&params).send().await?;
654
655        if !response.status().is_success() {
656            let error_text = response.text().await.unwrap_or_default();
657            return Err(AuthError::auth_method(
658                self.name(),
659                format!("Token exchange failed: {error_text}"),
660            ));
661        }
662
663        let token_response: OAuthTokenResponse = response.json().await?;
664        Ok(token_response)
665    }
666
667    /// Refresh an access token.
668    pub async fn refresh_token(
669        &self,
670        client_id: &str,
671        client_secret: &str,
672        refresh_token: &str,
673    ) -> Result<OAuthTokenResponse> {
674        let config = self.config();
675
676        if !config.supports_refresh {
677            return Err(AuthError::auth_method(
678                self.name(),
679                "Provider does not support token refresh".to_string(),
680            ));
681        }
682
683        let client = reqwest::Client::new();
684
685        let params = vec![
686            ("grant_type", "refresh_token"),
687            ("client_id", client_id),
688            ("client_secret", client_secret),
689            ("refresh_token", refresh_token),
690        ];
691
692        let response = client.post(&config.token_url).form(&params).send().await?;
693
694        if !response.status().is_success() {
695            let error_text = response.text().await.unwrap_or_default();
696            return Err(AuthError::auth_method(
697                self.name(),
698                format!("Token refresh failed: {error_text}"),
699            ));
700        }
701
702        let token_response: OAuthTokenResponse = response.json().await?;
703        Ok(token_response)
704    }
705
706    /// Get user information using an access token.
707    pub async fn get_user_info(&self, access_token: &str) -> Result<OAuthUserInfo> {
708        let config = self.config();
709
710        let userinfo_url = config.userinfo_url.ok_or_else(|| {
711            AuthError::auth_method(
712                self.name(),
713                "Provider does not support user info endpoint".to_string(),
714            )
715        })?;
716
717        let client = reqwest::Client::new();
718        let response = client
719            .get(&userinfo_url)
720            .bearer_auth(access_token)
721            .send()
722            .await?;
723
724        if !response.status().is_success() {
725            let error_text = response.text().await.unwrap_or_default();
726            return Err(AuthError::auth_method(
727                self.name(),
728                format!("User info request failed: {error_text}"),
729            ));
730        }
731
732        let user_data: serde_json::Value = response.json().await?;
733
734        // Convert provider-specific user data to our standard format
735        let user_info = self.parse_user_info(user_data)?;
736        Ok(user_info)
737    }
738
739    /// Parse provider-specific user info into our standard format.
740    fn parse_user_info(&self, data: serde_json::Value) -> Result<OAuthUserInfo> {
741        let mut additional_fields = HashMap::new();
742
743        let user_info = match self {
744            Self::GitHub => {
745                let id = data["id"]
746                    .as_u64()
747                    .ok_or_else(|| AuthError::auth_method(self.name(), "Missing user ID"))?
748                    .to_string();
749
750                OAuthUserInfo {
751                    id,
752                    username: data["login"].as_str().map(|s| s.to_string()),
753                    email: data["email"].as_str().map(|s| s.to_string()),
754                    name: data["name"].as_str().map(|s| s.to_string()),
755                    picture: data["avatar_url"].as_str().map(|s| s.to_string()),
756                    email_verified: None, // GitHub doesn't provide this directly
757                    locale: None,
758                    additional_fields,
759                }
760            }
761
762            Self::Google => {
763                let id = data["id"]
764                    .as_str()
765                    .ok_or_else(|| AuthError::auth_method(self.name(), "Missing user ID"))?
766                    .to_string();
767
768                OAuthUserInfo {
769                    id,
770                    username: None, // Google doesn't provide username
771                    email: data["email"].as_str().map(|s| s.to_string()),
772                    name: data["name"].as_str().map(|s| s.to_string()),
773                    picture: data["picture"].as_str().map(|s| s.to_string()),
774                    email_verified: data["verified_email"].as_bool(),
775                    locale: data["locale"].as_str().map(|s| s.to_string()),
776                    additional_fields,
777                }
778            }
779
780            // Add other provider-specific parsing...
781            _ => {
782                // Generic parsing for custom providers
783                let id = data["id"]
784                    .as_str()
785                    .or_else(|| data["sub"].as_str())
786                    .or_else(|| data["user_id"].as_str())
787                    .ok_or_else(|| AuthError::auth_method(self.name(), "Missing user ID"))?
788                    .to_string();
789
790                // Copy all fields to additional_fields for custom providers
791                if let serde_json::Value::Object(map) = data {
792                    additional_fields = map.into_iter().collect();
793                }
794
795                OAuthUserInfo {
796                    id,
797                    username: additional_fields
798                        .get("username")
799                        .or_else(|| additional_fields.get("login"))
800                        .and_then(|v| v.as_str())
801                        .map(|s| s.to_string()),
802                    email: additional_fields
803                        .get("email")
804                        .and_then(|v| v.as_str())
805                        .map(|s| s.to_string()),
806                    name: additional_fields
807                        .get("name")
808                        .or_else(|| additional_fields.get("display_name"))
809                        .and_then(|v| v.as_str())
810                        .map(|s| s.to_string()),
811                    picture: additional_fields
812                        .get("avatar_url")
813                        .or_else(|| additional_fields.get("picture"))
814                        .and_then(|v| v.as_str())
815                        .map(|s| s.to_string()),
816                    email_verified: additional_fields
817                        .get("email_verified")
818                        .and_then(|v| v.as_bool()),
819                    locale: additional_fields
820                        .get("locale")
821                        .and_then(|v| v.as_str())
822                        .map(|s| s.to_string()),
823                    additional_fields,
824                }
825            }
826        };
827
828        Ok(user_info)
829    }
830
831    /// Revoke a token if the provider supports it.
832    pub async fn revoke_token(&self, access_token: &str) -> Result<()> {
833        let config = self.config();
834
835        let revocation_url = config.revocation_url.ok_or_else(|| {
836            AuthError::auth_method(
837                self.name(),
838                "Provider does not support token revocation".to_string(),
839            )
840        })?;
841
842        let client = reqwest::Client::new();
843        let response = client
844            .post(&revocation_url)
845            .form(&[("token", access_token)])
846            .send()
847            .await?;
848
849        if !response.status().is_success() {
850            let error_text = response.text().await.unwrap_or_default();
851            return Err(AuthError::auth_method(
852                self.name(),
853                format!("Token revocation failed: {error_text}"),
854            ));
855        }
856
857        Ok(())
858    }
859
860    /// Perform device authorization flow.
861    pub async fn device_authorization(
862        &self,
863        client_id: &str,
864        scope: Option<&[String]>,
865    ) -> Result<DeviceAuthorizationResponse> {
866        let config = self.config();
867
868        if !config.supports_device_flow {
869            return Err(AuthError::auth_method(
870                self.name(),
871                "Provider does not support device authorization flow".to_string(),
872            ));
873        }
874
875        let client = reqwest::Client::new();
876
877        let scope_string = scope.unwrap_or(&config.default_scopes).join(" ");
878        let params = vec![("client_id", client_id), ("scope", scope_string.as_str())];
879
880        let response = client
881            .post(config.device_authorization_url.as_deref().unwrap())
882            .form(&params)
883            .send()
884            .await?;
885
886        if !response.status().is_success() {
887            let error_text = response.text().await.unwrap_or_default();
888            return Err(AuthError::auth_method(
889                self.name(),
890                format!("Device authorization request failed: {error_text}"),
891            ));
892        }
893
894        let device_response: DeviceAuthorizationResponse = response.json().await?;
895        Ok(device_response)
896    }
897
898    /// Poll for access token using device code.
899    pub async fn poll_device_code(
900        &self,
901        client_id: &str,
902        device_code: &str,
903        _interval: Option<u64>,
904    ) -> Result<OAuthTokenResponse> {
905        let config = self.config();
906
907        if !config.supports_device_flow {
908            return Err(AuthError::auth_method(
909                self.name(),
910                "Provider does not support device authorization flow".to_string(),
911            ));
912        }
913
914        let client = reqwest::Client::new();
915
916        let params = vec![
917            ("client_id", client_id),
918            ("grant_type", "urn:ietf:params:oauth:grant-type:device_code"),
919            ("device_code", device_code),
920        ];
921
922        let response = client.post(&config.token_url).form(&params).send().await?;
923
924        if !response.status().is_success() {
925            let error_text = response.text().await.unwrap_or_default();
926            return Err(AuthError::auth_method(
927                self.name(),
928                format!("Token request failed: {error_text}"),
929            ));
930        }
931
932        let token_response: OAuthTokenResponse = response.json().await?;
933        Ok(token_response)
934    }
935}
936
937/// Generate a random state parameter for OAuth flows.
938pub fn generate_state() -> String {
939    let mut bytes = [0u8; 32];
940    use rand::RngCore;
941    rand::rng().fill_bytes(&mut bytes);
942    base64::engine::general_purpose::URL_SAFE_NO_PAD.encode(bytes)
943}
944
945/// Generate PKCE code verifier and challenge.
946pub fn generate_pkce() -> (String, String) {
947    use rand::RngCore;
948    use ring::digest;
949
950    // Generate code verifier (43-128 characters)
951    let mut rng = rand::rng();
952    let mut bytes = [0u8; 96]; // 96 bytes = 128 base64 characters
953    rng.fill_bytes(&mut bytes);
954    let code_verifier = base64::engine::general_purpose::URL_SAFE_NO_PAD.encode(bytes);
955
956    // Generate code challenge (SHA256 hash of verifier, base64url encoded)
957    let digest = digest::digest(&digest::SHA256, code_verifier.as_bytes());
958    let code_challenge = base64::engine::general_purpose::URL_SAFE_NO_PAD.encode(digest.as_ref());
959
960    (code_verifier, code_challenge)
961}
962
963/// Automated token-to-profile conversion utilities
964pub struct ProfileExtractor {
965    client: Client,
966}
967
968impl ProfileExtractor {
969    /// Create a new profile extractor
970    pub fn new() -> Self {
971        Self {
972            client: Client::new(),
973        }
974    }
975
976    /// Extract user profile from token automatically based on provider
977    pub async fn extract_profile(
978        &self,
979        token: &AuthToken,
980        provider: &OAuthProvider,
981    ) -> Result<UserProfile> {
982        match provider {
983            OAuthProvider::GitHub => self.extract_github_profile(token).await,
984            OAuthProvider::Google => self.extract_google_profile(token).await,
985            OAuthProvider::Microsoft => self.extract_microsoft_profile(token).await,
986            OAuthProvider::Discord => self.extract_discord_profile(token).await,
987            OAuthProvider::GitLab => self.extract_gitlab_profile(token).await,
988            OAuthProvider::Custom { name, config } => {
989                self.extract_custom_profile(token, name, config).await
990            }
991            _ => Err(AuthError::UnsupportedProvider(format!(
992                "Profile extraction not supported for {:?}",
993                provider
994            ))),
995        }
996    }
997
998    /// Extract GitHub user profile
999    async fn extract_github_profile(&self, token: &AuthToken) -> Result<UserProfile> {
1000        let response = self
1001            .client
1002            .get("https://api.github.com/user")
1003            .bearer_auth(&token.access_token)
1004            .send()
1005            .await
1006            .map_err(|e| AuthError::NetworkError(e.to_string()))?;
1007
1008        let json: Value = response
1009            .json()
1010            .await
1011            .map_err(|e| AuthError::ParseError(e.to_string()))?;
1012
1013        let mut profile = UserProfile::new();
1014        profile = profile.with_id(json["id"].as_u64().unwrap_or(0).to_string());
1015        profile = profile.with_provider("github".to_string());
1016
1017        if let Some(login) = json["login"].as_str() {
1018            profile.username = Some(login.to_string());
1019        }
1020
1021        if let Some(name) = json["name"].as_str() {
1022            profile.name = Some(name.to_string());
1023        }
1024
1025        if let Some(email) = json["email"].as_str() {
1026            profile.email = Some(email.to_string());
1027        }
1028
1029        if let Some(avatar_url) = json["avatar_url"].as_str() {
1030            profile.picture = Some(avatar_url.to_string());
1031        }
1032
1033        // Store additional GitHub-specific data
1034        if let Some(company) = json["company"].as_str() {
1035            profile
1036                .additional_data
1037                .insert("company".to_string(), Value::String(company.to_string()));
1038        }
1039
1040        if let Some(blog) = json["blog"].as_str() {
1041            profile
1042                .additional_data
1043                .insert("blog".to_string(), Value::String(blog.to_string()));
1044        }
1045
1046        if let Some(bio) = json["bio"].as_str() {
1047            profile
1048                .additional_data
1049                .insert("bio".to_string(), Value::String(bio.to_string()));
1050        }
1051
1052        Ok(profile)
1053    }
1054
1055    /// Extract Google user profile
1056    async fn extract_google_profile(&self, token: &AuthToken) -> Result<UserProfile> {
1057        let response = self
1058            .client
1059            .get("https://www.googleapis.com/oauth2/v2/userinfo")
1060            .bearer_auth(&token.access_token)
1061            .send()
1062            .await
1063            .map_err(|e| AuthError::NetworkError(e.to_string()))?;
1064
1065        let json: Value = response
1066            .json()
1067            .await
1068            .map_err(|e| AuthError::ParseError(e.to_string()))?;
1069
1070        let mut profile = UserProfile::new();
1071        profile = profile.with_id(json["id"].as_str().unwrap_or("").to_string());
1072        profile = profile.with_provider("google".to_string());
1073
1074        if let Some(name) = json["name"].as_str() {
1075            profile.name = Some(name.to_string());
1076        }
1077
1078        if let Some(email) = json["email"].as_str() {
1079            profile.email = Some(email.to_string());
1080        }
1081
1082        if let Some(verified) = json["verified_email"].as_bool() {
1083            profile.email_verified = Some(verified);
1084        }
1085
1086        if let Some(picture) = json["picture"].as_str() {
1087            profile.picture = Some(picture.to_string());
1088        }
1089
1090        if let Some(locale) = json["locale"].as_str() {
1091            profile.locale = Some(locale.to_string());
1092        }
1093
1094        Ok(profile)
1095    }
1096
1097    /// Extract Microsoft user profile
1098    async fn extract_microsoft_profile(&self, token: &AuthToken) -> Result<UserProfile> {
1099        let response = self
1100            .client
1101            .get("https://graph.microsoft.com/v1.0/me")
1102            .bearer_auth(&token.access_token)
1103            .send()
1104            .await
1105            .map_err(|e| AuthError::NetworkError(e.to_string()))?;
1106
1107        let json: Value = response
1108            .json()
1109            .await
1110            .map_err(|e| AuthError::ParseError(e.to_string()))?;
1111
1112        let mut profile = UserProfile::new();
1113        profile = profile.with_id(json["id"].as_str().unwrap_or("").to_string());
1114        profile = profile.with_provider("microsoft".to_string());
1115
1116        if let Some(display_name) = json["displayName"].as_str() {
1117            profile.name = Some(display_name.to_string());
1118        }
1119
1120        if let Some(user_principal_name) = json["userPrincipalName"].as_str() {
1121            profile.username = Some(user_principal_name.to_string());
1122        }
1123
1124        if let Some(mail) = json["mail"].as_str() {
1125            profile.email = Some(mail.to_string());
1126        }
1127
1128        if let Some(preferred_language) = json["preferredLanguage"].as_str() {
1129            profile.locale = Some(preferred_language.to_string());
1130        }
1131
1132        // Store additional Microsoft-specific data
1133        if let Some(job_title) = json["jobTitle"].as_str() {
1134            profile
1135                .additional_data
1136                .insert("jobTitle".to_string(), Value::String(job_title.to_string()));
1137        }
1138
1139        if let Some(office_location) = json["officeLocation"].as_str() {
1140            profile.additional_data.insert(
1141                "officeLocation".to_string(),
1142                Value::String(office_location.to_string()),
1143            );
1144        }
1145
1146        Ok(profile)
1147    }
1148
1149    /// Extract Discord user profile
1150    async fn extract_discord_profile(&self, token: &AuthToken) -> Result<UserProfile> {
1151        let response = self
1152            .client
1153            .get("https://discord.com/api/users/@me")
1154            .bearer_auth(&token.access_token)
1155            .send()
1156            .await
1157            .map_err(|e| AuthError::NetworkError(e.to_string()))?;
1158
1159        let json: Value = response
1160            .json()
1161            .await
1162            .map_err(|e| AuthError::ParseError(e.to_string()))?;
1163
1164        let mut profile = UserProfile::new();
1165        profile = profile.with_id(json["id"].as_str().unwrap_or("").to_string());
1166        profile = profile.with_provider("discord".to_string());
1167
1168        if let Some(username) = json["username"].as_str() {
1169            profile.username = Some(username.to_string());
1170        }
1171
1172        if let Some(discriminator) = json["discriminator"].as_str() {
1173            profile.name = Some(format!(
1174                "{}#{}",
1175                json["username"].as_str().unwrap_or(""),
1176                discriminator
1177            ));
1178        }
1179
1180        if let Some(email) = json["email"].as_str() {
1181            profile.email = Some(email.to_string());
1182        }
1183
1184        if let Some(verified) = json["verified"].as_bool() {
1185            profile.email_verified = Some(verified);
1186        }
1187
1188        if let Some(avatar) = json["avatar"].as_str() {
1189            let user_id = json["id"].as_str().unwrap_or("");
1190            profile.picture = Some(format!(
1191                "https://cdn.discordapp.com/avatars/{}/{}.png",
1192                user_id, avatar
1193            ));
1194        }
1195
1196        if let Some(locale) = json["locale"].as_str() {
1197            profile.locale = Some(locale.to_string());
1198        }
1199
1200        Ok(profile)
1201    }
1202
1203    /// Extract GitLab user profile
1204    async fn extract_gitlab_profile(&self, token: &AuthToken) -> Result<UserProfile> {
1205        let response = self
1206            .client
1207            .get("https://gitlab.com/api/v4/user")
1208            .bearer_auth(&token.access_token)
1209            .send()
1210            .await
1211            .map_err(|e| AuthError::NetworkError(e.to_string()))?;
1212
1213        let json: Value = response
1214            .json()
1215            .await
1216            .map_err(|e| AuthError::ParseError(e.to_string()))?;
1217
1218        let mut profile = UserProfile::new();
1219        profile = profile.with_id(json["id"].as_u64().unwrap_or(0).to_string());
1220        profile = profile.with_provider("gitlab".to_string());
1221
1222        if let Some(username) = json["username"].as_str() {
1223            profile.username = Some(username.to_string());
1224        }
1225
1226        if let Some(name) = json["name"].as_str() {
1227            profile.name = Some(name.to_string());
1228        }
1229
1230        if let Some(email) = json["email"].as_str() {
1231            profile.email = Some(email.to_string());
1232        }
1233
1234        if let Some(avatar_url) = json["avatar_url"].as_str() {
1235            profile.picture = Some(avatar_url.to_string());
1236        }
1237
1238        // Store additional GitLab-specific data
1239        if let Some(web_url) = json["web_url"].as_str() {
1240            profile
1241                .additional_data
1242                .insert("web_url".to_string(), Value::String(web_url.to_string()));
1243        }
1244
1245        if let Some(bio) = json["bio"].as_str() {
1246            profile
1247                .additional_data
1248                .insert("bio".to_string(), Value::String(bio.to_string()));
1249        }
1250
1251        Ok(profile)
1252    }
1253
1254    /// Extract custom provider profile
1255    async fn extract_custom_profile(
1256        &self,
1257        token: &AuthToken,
1258        provider_name: &str,
1259        config: &OAuthProviderConfig,
1260    ) -> Result<UserProfile> {
1261        if let Some(user_info_url) = &config.userinfo_url {
1262            let response = self
1263                .client
1264                .get(user_info_url)
1265                .bearer_auth(&token.access_token)
1266                .send()
1267                .await
1268                .map_err(|e| AuthError::NetworkError(e.to_string()))?;
1269
1270            let json: Value = response
1271                .json()
1272                .await
1273                .map_err(|e| AuthError::ParseError(e.to_string()))?;
1274
1275            let mut profile = UserProfile::new();
1276            profile = profile.with_id(
1277                json["id"]
1278                    .as_str()
1279                    .or_else(|| json["sub"].as_str())
1280                    .unwrap_or("")
1281                    .to_string(),
1282            );
1283            profile = profile.with_provider(provider_name.to_string());
1284
1285            // Try common field names
1286            if let Some(username) = json["username"].as_str().or_else(|| json["login"].as_str()) {
1287                profile.username = Some(username.to_string());
1288            }
1289
1290            if let Some(name) = json["name"]
1291                .as_str()
1292                .or_else(|| json["display_name"].as_str())
1293            {
1294                profile.name = Some(name.to_string());
1295            }
1296
1297            if let Some(email) = json["email"].as_str() {
1298                profile.email = Some(email.to_string());
1299            }
1300
1301            if let Some(verified) = json["email_verified"]
1302                .as_bool()
1303                .or_else(|| json["verified"].as_bool())
1304            {
1305                profile.email_verified = Some(verified);
1306            }
1307
1308            if let Some(picture) = json["picture"]
1309                .as_str()
1310                .or_else(|| json["avatar_url"].as_str())
1311            {
1312                profile.picture = Some(picture.to_string());
1313            }
1314
1315            if let Some(locale) = json["locale"].as_str().or_else(|| json["lang"].as_str()) {
1316                profile.locale = Some(locale.to_string());
1317            }
1318
1319            // Store all additional data
1320            for (key, value) in json.as_object().unwrap_or(&serde_json::Map::new()) {
1321                if ![
1322                    "id",
1323                    "sub",
1324                    "username",
1325                    "login",
1326                    "name",
1327                    "display_name",
1328                    "email",
1329                    "email_verified",
1330                    "verified",
1331                    "picture",
1332                    "avatar_url",
1333                    "locale",
1334                    "lang",
1335                ]
1336                .contains(&key.as_str())
1337                {
1338                    profile.additional_data.insert(key.clone(), value.clone());
1339                }
1340            }
1341
1342            Ok(profile)
1343        } else {
1344            Err(AuthError::ConfigurationError(
1345                "Custom provider requires user_info_url".to_string(),
1346            ))
1347        }
1348    }
1349}
1350
1351impl Default for ProfileExtractor {
1352    fn default() -> Self {
1353        Self::new()
1354    }
1355}
1356
1357impl fmt::Display for OAuthProvider {
1358    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1359        match self {
1360            OAuthProvider::GitHub => write!(f, "github"),
1361            OAuthProvider::Google => write!(f, "google"),
1362            OAuthProvider::Microsoft => write!(f, "microsoft"),
1363            OAuthProvider::Discord => write!(f, "discord"),
1364            OAuthProvider::Twitter => write!(f, "twitter"),
1365            OAuthProvider::Facebook => write!(f, "facebook"),
1366            OAuthProvider::LinkedIn => write!(f, "linkedin"),
1367            OAuthProvider::GitLab => write!(f, "gitlab"),
1368            OAuthProvider::Custom { name, .. } => write!(f, "{}", name),
1369        }
1370    }
1371}
1372
1373#[cfg(test)]
1374mod tests {
1375    use super::*;
1376
1377    #[test]
1378    fn test_provider_config() {
1379        let github = OAuthProvider::GitHub;
1380        let config = github.config();
1381
1382        assert_eq!(
1383            config.authorization_url,
1384            "https://github.com/login/oauth/authorize"
1385        );
1386        assert_eq!(
1387            config.token_url,
1388            "https://github.com/login/oauth/access_token"
1389        );
1390        assert!(config.supports_pkce);
1391    }
1392
1393    #[test]
1394    fn test_authorization_url() {
1395        let github = OAuthProvider::GitHub;
1396        let url = github
1397            .build_authorization_url(
1398                "client123",
1399                "https://example.com/callback",
1400                "state123",
1401                None,
1402                Some("challenge123"),
1403            )
1404            .unwrap();
1405
1406        assert!(url.contains("client_id=client123"));
1407        assert!(url.contains("redirect_uri=https%3A%2F%2Fexample.com%2Fcallback"));
1408        assert!(url.contains("state=state123"));
1409        assert!(url.contains("code_challenge=challenge123"));
1410    }
1411
1412    #[test]
1413    fn test_generate_state() {
1414        let state1 = generate_state();
1415        let state2 = generate_state();
1416
1417        assert_eq!(state1.len(), 43);
1418        assert_eq!(state2.len(), 43);
1419        assert_ne!(state1, state2);
1420    }
1421
1422    #[test]
1423    fn test_generate_pkce() {
1424        let (verifier1, challenge1) = generate_pkce();
1425        let (verifier2, challenge2) = generate_pkce();
1426
1427        assert_eq!(verifier1.len(), 128);
1428        assert_eq!(verifier2.len(), 128);
1429        assert_ne!(verifier1, verifier2);
1430        assert_ne!(challenge1, challenge2);
1431    }
1432}