Skip to main content

auth_framework/
providers.rs

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