fraiseql-auth 2.15.0

Authentication, authorization, and session management for FraiseQL
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
//! Generic OIDC provider implementation using RFC 8414 discovery.
use std::{fmt::Write as _, time::Duration};

use async_trait::async_trait;
use serde::{Deserialize, Serialize};
use zeroize::Zeroizing;

/// Timeout for all OIDC HTTP operations (discovery, token exchange, user info, refresh).
pub(crate) const OIDC_REQUEST_TIMEOUT: Duration = Duration::from_secs(30);

/// Maximum byte size for an OIDC discovery document response.
///
/// A well-formed `.well-known/openid-configuration` payload is a few `KiB`.
/// 64 `KiB` blocks allocation bombs from a compromised OIDC provider.
pub(crate) const MAX_OIDC_DISCOVERY_BYTES: usize = 64 * 1024; // 64 KiB

/// Maximum byte size for OIDC token and user-info responses.
///
/// Token responses carry JWTs and a handful of metadata fields.
/// 1 `MiB` is generous while preventing runaway allocation.
pub(crate) const MAX_OIDC_TOKEN_BYTES: usize = 1024 * 1024; // 1 MiB

use crate::{
    error::{AuthError, Result},
    provider::{OAuthProvider, TokenResponse, UserInfo},
};

/// OIDC Discovery document
#[derive(Debug, Clone, Serialize, Deserialize)]
pub(crate) struct OidcDiscovery {
    pub(crate) issuer:                 String,
    pub(crate) authorization_endpoint: String,
    pub(crate) token_endpoint:         String,
    pub(crate) userinfo_endpoint:      String,
    pub(crate) jwks_uri:               Option<String>,
    #[serde(default)]
    pub(crate) revocation_endpoint:    Option<String>,
}

/// Generic OIDC provider that works with any OIDC-compliant service
///
/// # Examples
///
/// ```no_run
/// // Requires: live OIDC endpoint (e.g., Google, Logto, Ory).
/// # async fn example() -> fraiseql_auth::error::Result<()> {
/// use fraiseql_auth::oidc_provider::OidcProvider;
/// let provider = OidcProvider::new(
///     "google",
///     "https://accounts.google.com",
///     "client_id",
///     "client_secret",
///     "http://localhost:8000/auth/callback",
/// ).await?;
/// # Ok(())
/// # }
/// ```
pub struct OidcProvider {
    pub(crate) name:          String,
    pub(crate) issuer_url:    String,
    pub(crate) client_id:     String,
    /// Stored as `Zeroizing<String>` so the key material is wiped from memory
    /// when this struct is dropped.
    pub(crate) client_secret: Zeroizing<String>,
    pub(crate) redirect_uri:  String,
    pub(crate) discovery:     OidcDiscovery,
    pub(crate) client:        reqwest::Client,
}

#[derive(Debug, Serialize)]
struct TokenRequest {
    grant_type:    String,
    code:          String,
    client_id:     String,
    client_secret: String,
    redirect_uri:  String,
    #[serde(skip_serializing_if = "Option::is_none")]
    code_verifier: Option<String>,
}

#[derive(Debug, Deserialize)]
struct TokenResponseRaw {
    access_token:  String,
    #[serde(default)]
    refresh_token: Option<String>,
    expires_in:    u64,
    #[serde(default)]
    token_type:    Option<String>,
    /// Present on OIDC flows; carried through so a caller that needs the
    /// signed identity does not have to re-fetch it.
    #[serde(default)]
    id_token:      Option<String>,
}

#[derive(Debug, Deserialize)]
struct UserInfoRaw {
    sub:            String,
    email:          Option<String>,
    #[serde(default)]
    email_verified: Option<bool>,
    name:           Option<String>,
    picture:        Option<String>,
    #[serde(flatten)]
    extra:          serde_json::Map<String, serde_json::Value>,
}

/// Maximum redirect hops followed on an OIDC HTTP fetch.
const OIDC_MAX_REDIRECTS: usize = 5;

/// Env var that disables the OIDC SSRF guards for local development.
///
/// Honoured only when `FRAISEQL_ENV` declares a development environment; refused
/// in production regardless of its value.
pub const OIDC_ALLOW_INSECURE_ENV: &str = "FRAISEQL_OIDC_ALLOW_INSECURE";

/// Whether [`OIDC_ALLOW_INSECURE_ENV`] disables the SSRF guards.
///
/// Read in one place so the URL check and the redirect policy agree. This used
/// to honour the variable on its own, with no production check — the same shape
/// as #836, and the reason that guard now runs through
/// [`fraiseql_guard::deployment`], which also reports the decision so a refusal
/// is visible in the log stream rather than surfacing as an opaque connection
/// failure (#882).
fn oidc_ssrf_guards_disabled() -> bool {
    fraiseql_guard::deployment::insecure_bypass(OIDC_ALLOW_INSECURE_ENV).is_honoured()
}

/// Validate an OIDC issuer URL against SSRF-prone destinations.
///
/// Rejects:
/// - Non-HTTPS schemes (OIDC issuers must use TLS)
/// - Loopback addresses (`127.0.0.0/8`, `::1`, `localhost`)
/// - RFC 1918 private ranges (`10/8`, `172.16/12`, `192.168/16`)
/// - Link-local addresses (`169.254/16`) — includes AWS IMDSv1/v2
/// - CGNAT (`100.64.0.0/10`) and the unspecified block (`0.0.0.0/8`)
/// - IPv6 ULA (`fc00::/7`), IPv6 link-local (`fe80::/10`), and `::`
/// - IPv4-mapped IPv6 (`::ffff:0:0/96`), which the OS routes as the embedded IPv4 address, so the
///   bracketed mapped spelling of `169.254.169.254` reaches the metadata service exactly as the
///   bare form does
///
/// The address classification is [`fraiseql_guard::net::is_blocked_ip`], the one
/// outbound guard in the workspace — the same predicate the JWKS fetch applies,
/// so the two cannot drift. `oidc_ssrf_gate_agrees_with_jwks_gate` asserts it.
///
/// # Errors
///
/// Returns [`AuthError::OidcMetadataError`] if the URL is invalid, uses a non-HTTPS
/// scheme, or targets a private/loopback address.
pub(crate) fn validate_oidc_issuer_url(issuer_url: &str) -> Result<()> {
    if oidc_ssrf_guards_disabled() {
        return Ok(());
    }

    let lower = issuer_url.to_ascii_lowercase();
    if !lower.starts_with("https://") {
        return Err(AuthError::OidcMetadataError {
            message: format!(
                "OIDC issuer URL must use https:// scheme (SSRF protection): {issuer_url}"
            ),
        });
    }

    // Use a URL parser to safely extract the host — manual string-splitting is
    // fragile for IPv6 literals like `[::1]`.
    let parsed = reqwest::Url::parse(issuer_url).map_err(|e| AuthError::OidcMetadataError {
        message: format!("OIDC issuer URL is not a valid URL ({issuer_url}): {e}"),
    })?;

    if is_ssrf_blocked_oidc_url(&parsed) {
        return Err(AuthError::OidcMetadataError {
            message: format!(
                "OIDC issuer URL targets a private/loopback address (SSRF protection): \
                 {issuer_url}"
            ),
        });
    }

    Ok(())
}

/// Fetch and parse an OIDC discovery document, with the same SSRF guards the
/// provider constructor applies (issuer validated up front, every redirect hop
/// re-checked, response size bounded).
///
/// `discovery_base` is the issuer/provider base URL; `.well-known/openid-configuration`
/// is appended. Shared by [`OidcProvider::new`] and the server-side PKCE client
/// (`OidcServerClient::from_compiled_schema`, #621) so the two cannot drift on the
/// SSRF posture.
///
/// # Errors
///
/// Returns [`AuthError::OidcMetadataError`] if the base URL fails SSRF validation,
/// the document cannot be fetched/parsed, or it exceeds [`MAX_OIDC_DISCOVERY_BYTES`].
pub(crate) async fn fetch_oidc_discovery(discovery_base: &str) -> Result<OidcDiscovery> {
    validate_oidc_issuer_url(discovery_base)?;

    let client = reqwest::Client::builder()
        .timeout(OIDC_REQUEST_TIMEOUT)
        .redirect(ssrf_checked_redirect_policy(oidc_ssrf_guards_disabled()))
        .build()
        .map_err(|e| AuthError::OidcMetadataError {
            message: format!("Failed to create HTTP client: {e}"),
        })?;

    let discovery_url =
        format!("{}/.well-known/openid-configuration", discovery_base.trim_end_matches('/'));

    let discovery_bytes = client
        .get(&discovery_url)
        .send()
        .await
        .map_err(|e| AuthError::OidcMetadataError {
            message: format!("Failed to fetch OIDC metadata from {discovery_url}: {e}"),
        })?
        .bytes()
        .await
        .map_err(|e| AuthError::OidcMetadataError {
            message: format!("Failed to read OIDC metadata: {e}"),
        })?;
    if discovery_bytes.len() > MAX_OIDC_DISCOVERY_BYTES {
        return Err(AuthError::OidcMetadataError {
            message: format!(
                "OIDC discovery response too large ({} bytes, max {MAX_OIDC_DISCOVERY_BYTES})",
                discovery_bytes.len()
            ),
        });
    }
    serde_json::from_slice(&discovery_bytes).map_err(|e| AuthError::OidcMetadataError {
        message: format!("Failed to parse OIDC metadata: {e}"),
    })
}

/// Validate a configurable non-OIDC OAuth endpoint base URL with the same
/// SSRF gate as OIDC issuer URLs (#368: the GitHub `base_url` /
/// `api_base_url` overrides). Shared so the two postures cannot drift.
///
/// # Errors
///
/// Returns [`AuthError::OidcMetadataError`] if the URL is invalid, uses a
/// non-HTTPS scheme, or targets a private/loopback address (unless the
/// development bypass is active).
pub(crate) fn validate_oauth_endpoint_url(url: &str) -> Result<()> {
    validate_oidc_issuer_url(url)
}

/// Returns `true` if `url`'s host is one that OIDC fetches must not contact.
fn is_ssrf_blocked_oidc_url(url: &reqwest::Url) -> bool {
    let host_raw = url.host_str().unwrap_or("");
    // The `url` crate wraps IPv6 literals in brackets in `host_str()`.
    // Strip them so the IP address can be parsed by `IpAddr::from_str`.
    let host = host_raw.strip_prefix('[').and_then(|h| h.strip_suffix(']')).unwrap_or(host_raw);
    is_ssrf_blocked_oidc_host(host)
}

/// Returns `true` for hosts an OIDC issuer URL must not target.
///
/// Delegated to [`fraiseql_guard::net`] so this gate and the JWKS gate cannot drift
/// (#776). Beyond the address ranges, the shared guard also matches the loopback
/// hostname aliases this predicate missed: it tested `host == "localhost"` exactly,
/// so `api.localhost` and the attacker-registrable `localhost.evil.com` passed.
pub(crate) fn is_ssrf_blocked_oidc_host(host: &str) -> bool {
    fraiseql_guard::net::blocked_host_reason(host).is_some()
}

/// Redirect policy that re-applies the SSRF host check to every hop.
///
/// A validated issuer could otherwise `3xx` the discovery/token/userinfo fetch onward
/// to an internal target, which bypasses the check performed on the original URL
/// (#776). Redirects are still followed — some IdPs use them — but each hop must
/// clear the same gate, and the chain is bounded.
fn ssrf_checked_redirect_policy(allow_insecure: bool) -> reqwest::redirect::Policy {
    reqwest::redirect::Policy::custom(move |attempt| {
        if allow_insecure {
            return attempt.follow();
        }
        if attempt.previous().len() >= OIDC_MAX_REDIRECTS {
            return attempt.error("too many redirects while fetching OIDC endpoint");
        }
        let url = attempt.url();
        if url.scheme() != "https" {
            return attempt.error("OIDC redirect to a non-https URL (SSRF protection)");
        }
        if is_ssrf_blocked_oidc_url(url) {
            return attempt.error("OIDC redirect to a private/loopback address (SSRF protection)");
        }
        attempt.follow()
    })
}

impl OidcProvider {
    /// Create a new OIDC provider
    ///
    /// # Arguments
    /// * `name` - Provider name (for logging)
    /// * `issuer_url` - The issuer URL (e.g., <https://accounts.google.com>); must use `https://`
    /// * `client_id` - OAuth client ID
    /// * `client_secret` - OAuth client secret
    /// * `redirect_uri` - Redirect URI after authentication
    ///
    /// # Errors
    /// Returns error if the issuer URL is invalid, uses a non-HTTPS scheme, targets a
    /// private/loopback address (SSRF protection), or if metadata discovery fails.
    pub async fn new(
        name: &str,
        issuer_url: &str,
        client_id: &str,
        client_secret: &str,
        redirect_uri: &str,
    ) -> Result<Self> {
        // SECURITY: Validate issuer URL before making any HTTP request to prevent SSRF.
        // Requires https:// scheme and rejects private/loopback destinations.
        validate_oidc_issuer_url(issuer_url)?;

        // SECURITY (#776): re-check every redirect hop. Validating only the issuer URL
        // let a 3xx bounce the discovery/token/userinfo fetch to an internal target.
        let client = reqwest::Client::builder()
            .timeout(OIDC_REQUEST_TIMEOUT)
            .redirect(ssrf_checked_redirect_policy(oidc_ssrf_guards_disabled()))
            .build()
            .map_err(|e| AuthError::OidcMetadataError {
                message: format!("Failed to create HTTP client: {}", e),
            })?;

        // Fetch OIDC discovery document
        let discovery_url =
            format!("{}/.well-known/openid-configuration", issuer_url.trim_end_matches('/'));

        let discovery_bytes = client
            .get(&discovery_url)
            .send()
            .await
            .map_err(|e| AuthError::OidcMetadataError {
                message: format!("Failed to fetch OIDC metadata from {}: {}", discovery_url, e),
            })?
            .bytes()
            .await
            .map_err(|e| AuthError::OidcMetadataError {
                message: format!("Failed to read OIDC metadata: {}", e),
            })?;
        if discovery_bytes.len() > MAX_OIDC_DISCOVERY_BYTES {
            return Err(AuthError::OidcMetadataError {
                message: format!(
                    "OIDC discovery response too large ({} bytes, max {MAX_OIDC_DISCOVERY_BYTES})",
                    discovery_bytes.len()
                ),
            });
        }
        let discovery: OidcDiscovery =
            serde_json::from_slice(&discovery_bytes).map_err(|e| AuthError::OidcMetadataError {
                message: format!("Failed to parse OIDC metadata: {}", e),
            })?;

        Ok(Self {
            name: name.to_string(),
            issuer_url: issuer_url.to_string(),
            client_id: client_id.to_string(),
            client_secret: Zeroizing::new(client_secret.to_string()),
            redirect_uri: redirect_uri.to_string(),
            discovery,
            client,
        })
    }

    /// Add authorization URL parameter
    pub(crate) fn add_auth_params(
        &self,
        url: &mut String,
        state: &str,
        pkce_challenge: Option<&str>,
    ) {
        url.push('?');
        write!(url, "client_id={}", urlencoding::encode(&self.client_id))
            .expect("write to String is infallible");
        write!(url, "&redirect_uri={}", urlencoding::encode(&self.redirect_uri))
            .expect("write to String is infallible");
        url.push_str("&response_type=code");
        write!(url, "&state={}", urlencoding::encode(state))
            .expect("write to String is infallible");
        url.push_str("&scope=openid+email+profile");

        if let Some(challenge) = pkce_challenge {
            write!(url, "&code_challenge={}", urlencoding::encode(challenge))
                .expect("write to String is infallible");
            url.push_str("&code_challenge_method=S256");
        }
    }
}

// Reason: OAuthProvider is defined with #[async_trait]; all implementations must match
// its transformed method signatures to satisfy the trait contract
// async_trait: dyn-dispatch required; remove when RTN + Send is stable (RFC 3425)
#[async_trait]
impl OAuthProvider for OidcProvider {
    fn name(&self) -> &str {
        &self.name
    }

    fn authorization_url(&self, state: &str) -> String {
        let mut url = self.discovery.authorization_endpoint.clone();
        self.add_auth_params(&mut url, state, None);
        url
    }

    async fn exchange_code(&self, code: &str) -> Result<TokenResponse> {
        let request = TokenRequest {
            grant_type:    "authorization_code".to_string(),
            code:          code.to_string(),
            client_id:     self.client_id.clone(),
            client_secret: (*self.client_secret).clone(),
            redirect_uri:  self.redirect_uri.clone(),
            code_verifier: None,
        };

        let token_bytes = self
            .client
            .post(&self.discovery.token_endpoint)
            .form(&request)
            .send()
            .await
            .map_err(|e| AuthError::OAuthError {
                message: format!("Failed to exchange code: {}", e),
            })?
            .bytes()
            .await
            .map_err(|e| AuthError::OAuthError {
                message: format!("Failed to read token response: {}", e),
            })?;
        if token_bytes.len() > MAX_OIDC_TOKEN_BYTES {
            return Err(AuthError::OAuthError {
                message: format!(
                    "Token response too large ({} bytes, max {MAX_OIDC_TOKEN_BYTES})",
                    token_bytes.len()
                ),
            });
        }
        let response: TokenResponseRaw =
            serde_json::from_slice(&token_bytes).map_err(|e| AuthError::OAuthError {
                message: format!("Failed to parse token response: {}", e),
            })?;

        Ok(TokenResponse {
            access_token:  response.access_token,
            refresh_token: response.refresh_token,
            expires_in:    response.expires_in,
            token_type:    response.token_type.unwrap_or_else(|| "Bearer".to_string()),
            id_token:      response.id_token,
        })
    }

    async fn user_info(&self, access_token: &str) -> Result<UserInfo> {
        let info_bytes = self
            .client
            .get(&self.discovery.userinfo_endpoint)
            .bearer_auth(access_token)
            .send()
            .await
            .map_err(|e| AuthError::OAuthError {
                message: format!("Failed to get user info: {}", e),
            })?
            .bytes()
            .await
            .map_err(|e| AuthError::OAuthError {
                message: format!("Failed to read user info response: {}", e),
            })?;
        if info_bytes.len() > MAX_OIDC_TOKEN_BYTES {
            return Err(AuthError::OAuthError {
                message: format!(
                    "User info response too large ({} bytes, max {MAX_OIDC_TOKEN_BYTES})",
                    info_bytes.len()
                ),
            });
        }
        let response: UserInfoRaw =
            serde_json::from_slice(&info_bytes).map_err(|e| AuthError::OAuthError {
                message: format!("Failed to parse user info: {}", e),
            })?;

        // Build raw claims with all fields
        let mut raw_claims = serde_json::Map::new();
        raw_claims.insert("sub".to_string(), serde_json::Value::String(response.sub.clone()));
        if let Some(email) = &response.email {
            raw_claims.insert("email".to_string(), serde_json::Value::String(email.clone()));
        }
        // Re-surface `email_verified` in raw_claims: it is an explicit field on
        // `UserInfoRaw` (so `#[serde(flatten)] extra` no longer captures it), but
        // provider wrappers (Okta/Auth0) read it back from raw_claims.
        if let Some(email_verified) = response.email_verified {
            raw_claims
                .insert("email_verified".to_string(), serde_json::Value::Bool(email_verified));
        }
        if let Some(name) = &response.name {
            raw_claims.insert("name".to_string(), serde_json::Value::String(name.clone()));
        }
        if let Some(picture) = &response.picture {
            raw_claims.insert("picture".to_string(), serde_json::Value::String(picture.clone()));
        }
        for (key, value) in response.extra {
            raw_claims.insert(key, value);
        }

        Ok(UserInfo {
            // Normalize an empty/whitespace-only email claim to `None` so it can
            // never serve as an account-linking key (H26).
            email:          response.email.filter(|e| !e.trim().is_empty()),
            email_verified: response.email_verified.unwrap_or(false),
            id:             response.sub,
            name:           response.name,
            picture:        response.picture,
            raw_claims:     serde_json::Value::Object(raw_claims),
        })
    }

    async fn refresh_token(&self, refresh_token: &str) -> Result<TokenResponse> {
        let params = [
            ("grant_type", "refresh_token"),
            ("refresh_token", refresh_token),
            ("client_id", self.client_id.as_str()),
            ("client_secret", self.client_secret.as_str()),
        ];

        let refresh_bytes = self
            .client
            .post(&self.discovery.token_endpoint)
            .form(&params)
            .send()
            .await
            .map_err(|e| AuthError::OAuthError {
                message: format!("Failed to refresh token: {}", e),
            })?
            .bytes()
            .await
            .map_err(|e| AuthError::OAuthError {
                message: format!("Failed to read refresh response: {}", e),
            })?;
        if refresh_bytes.len() > MAX_OIDC_TOKEN_BYTES {
            return Err(AuthError::OAuthError {
                message: format!(
                    "Refresh response too large ({} bytes, max {MAX_OIDC_TOKEN_BYTES})",
                    refresh_bytes.len()
                ),
            });
        }
        let response: TokenResponseRaw =
            serde_json::from_slice(&refresh_bytes).map_err(|e| AuthError::OAuthError {
                message: format!("Failed to parse refresh response: {}", e),
            })?;

        Ok(TokenResponse {
            access_token:  response.access_token,
            refresh_token: response.refresh_token,
            expires_in:    response.expires_in,
            token_type:    response.token_type.unwrap_or_else(|| "Bearer".to_string()),
            id_token:      response.id_token,
        })
    }

    async fn revoke_token(&self, token: &str) -> Result<()> {
        if let Some(revocation_endpoint) = &self.discovery.revocation_endpoint {
            let params = [
                ("token", token),
                ("client_id", self.client_id.as_str()),
                ("client_secret", self.client_secret.as_str()),
            ];

            let resp =
                self.client.post(revocation_endpoint).form(&params).send().await.map_err(|e| {
                    AuthError::OAuthError {
                        message: format!("Failed to revoke token: {}", e),
                    }
                })?;
            if !resp.status().is_success() {
                return Err(AuthError::OAuthError {
                    message: format!("Token revocation returned HTTP {}", resp.status()),
                });
            }
        }
        Ok(())
    }
}

impl std::fmt::Debug for OidcProvider {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("OidcProvider")
            .field("name", &self.name)
            .field("issuer_url", &self.issuer_url)
            .field("client_id", &self.client_id)
            .field("redirect_uri", &self.redirect_uri)
            .finish_non_exhaustive() // client_secret and client omitted for security
    }
}