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