Skip to main content

micromegas_auth/
oidc.rs

1use crate::types::{AuthContext, AuthProvider, AuthType};
2use anyhow::{Result, anyhow};
3use base64::Engine;
4use chrono::{DateTime, TimeDelta, Utc};
5use jsonwebtoken::{Algorithm, Validation, decode, decode_header};
6use moka::future::Cache;
7use openidconnect::core::{CoreJsonWebKeySet, CoreProviderMetadata};
8use openidconnect::{HttpClientError, HttpRequest, HttpResponse, IssuerUrl, JsonWebKey};
9use rsa::pkcs1::EncodeRsaPublicKey;
10use rsa::{BigUint, RsaPublicKey};
11use serde::{Deserialize, Serialize};
12use std::collections::HashMap;
13use std::future::Future;
14use std::pin::Pin;
15use std::sync::Arc;
16use std::time::Duration;
17
18/// Create HTTP client for OIDC operations with security best practices
19///
20/// This client is configured with SSRF protection:
21/// - No redirects allowed (prevents open redirect attacks)
22/// - Suitable for OIDC discovery and token exchange operations
23///
24/// # Security
25///
26/// The no-redirect policy is important for OIDC operations because:
27/// - Prevents attackers from redirecting requests to internal services
28/// - Ensures OIDC endpoints are accessed directly without intermediate hops
29/// - Protects against SSRF (Server-Side Request Forgery) attacks
30///
31/// # Example
32///
33/// ```rust
34/// use micromegas_auth::oidc::create_http_client;
35///
36/// # async fn example() -> anyhow::Result<()> {
37/// let client = create_http_client()?;
38/// let response = client.get("https://accounts.google.com/.well-known/openid-configuration")
39///     .send()
40///     .await?;
41/// # Ok(())
42/// # }
43/// ```
44pub fn create_http_client() -> Result<reqwest::Client> {
45    reqwest::ClientBuilder::new()
46        .redirect(reqwest::redirect::Policy::none())
47        .build()
48        .map_err(|e| anyhow!("Failed to create HTTP client: {e:?}"))
49}
50
51type HttpFuture =
52    Pin<Box<dyn Future<Output = Result<HttpResponse, HttpClientError<reqwest::Error>>> + Send>>;
53
54/// Adapts a reqwest client to openidconnect's HTTP client interface.
55///
56/// openidconnect ships its own adapter only for the reqwest version it depends on,
57/// which can differ from the one used here.
58pub fn openidconnect_http_client(client: reqwest::Client) -> impl Fn(HttpRequest) -> HttpFuture {
59    move |request: HttpRequest| {
60        let client = client.clone();
61        Box::pin(async move {
62            let response = client
63                .execute(request.try_into().map_err(Box::new)?)
64                .await
65                .map_err(Box::new)?;
66            let mut builder = http::Response::builder()
67                .status(response.status())
68                .version(response.version());
69            for (name, value) in response.headers() {
70                builder = builder.header(name, value);
71            }
72            builder
73                .body(response.bytes().await.map_err(Box::new)?.to_vec())
74                .map_err(HttpClientError::Http)
75        })
76    }
77}
78
79/// Fetch JWKS from the OIDC provider using openidconnect's built-in discovery
80async fn fetch_jwks(issuer_url: &IssuerUrl) -> Result<Arc<CoreJsonWebKeySet>> {
81    let http_client = create_http_client()?;
82
83    // Use openidconnect's built-in OIDC discovery
84    let metadata = CoreProviderMetadata::discover_async(
85        issuer_url.clone(),
86        &openidconnect_http_client(http_client.clone()),
87    )
88    .await
89    .map_err(|e| {
90        anyhow!(
91            "Failed to discover OIDC metadata from {}: {e:?}",
92            issuer_url
93        )
94    })?;
95
96    // Fetch JWKS from jwks_uri
97    let jwks_uri = metadata.jwks_uri();
98    let jwks: CoreJsonWebKeySet = http_client
99        .get(jwks_uri.url().as_str())
100        .send()
101        .await
102        .map_err(|e| anyhow!("Failed to fetch JWKS from {}: {e:?}", jwks_uri))?
103        .json()
104        .await
105        .map_err(|e| anyhow!("Failed to parse JWKS: {e:?}"))?;
106
107    Ok(Arc::new(jwks))
108}
109
110/// JWKS cache for an OIDC issuer
111///
112/// Caches JSON Web Key Sets with automatic TTL expiration.
113/// Uses moka for thread-safe caching with atomic cache miss handling.
114struct JwksCache {
115    issuer_url: IssuerUrl,
116    cache: Cache<String, Arc<CoreJsonWebKeySet>>,
117}
118
119impl JwksCache {
120    /// Create a new JWKS cache
121    fn new(issuer_url: IssuerUrl, ttl: Duration) -> Self {
122        let cache = Cache::builder().time_to_live(ttl).build();
123
124        Self { issuer_url, cache }
125    }
126
127    /// Get the JWKS, fetching from the issuer if not cached
128    async fn get(&self) -> Result<Arc<CoreJsonWebKeySet>> {
129        let issuer_url = self.issuer_url.clone();
130
131        self.cache
132            .try_get_with(
133                "jwks".to_string(),
134                async move { fetch_jwks(&issuer_url).await },
135            )
136            .await
137            .map_err(|e| anyhow!("Failed to fetch JWKS: {e:?}"))
138    }
139}
140
141/// Configuration for a single OIDC issuer
142#[derive(Debug, Clone, Deserialize)]
143pub struct OidcIssuer {
144    /// Issuer URL (e.g., <https://accounts.google.com>)
145    pub issuer: String,
146    /// Expected audience
147    /// - For access tokens: API audience (e.g., "<https://api.example.com>")
148    /// - For ID tokens: client ID
149    pub audience: String,
150}
151
152const DEFAULT_JWKS_REFRESH_INTERVAL_SECS: u64 = 3600;
153const DEFAULT_TOKEN_CACHE_SIZE: u64 = 1000;
154const DEFAULT_TOKEN_CACHE_TTL_SECS: u64 = 300;
155
156/// OIDC configuration
157#[derive(Debug, Clone, Deserialize)]
158#[serde(default)]
159pub struct OidcConfig {
160    /// List of configured OIDC issuers
161    pub issuers: Vec<OidcIssuer>,
162    /// JWKS refresh interval in seconds (default: 3600 = 1 hour)
163    pub jwks_refresh_interval_secs: u64,
164    /// Token cache size (default: 1000)
165    pub token_cache_size: u64,
166    /// Token cache TTL in seconds (default: 300 = 5 min)
167    pub token_cache_ttl_secs: u64,
168}
169
170impl Default for OidcConfig {
171    fn default() -> Self {
172        Self {
173            issuers: Vec::new(),
174            jwks_refresh_interval_secs: DEFAULT_JWKS_REFRESH_INTERVAL_SECS,
175            token_cache_size: DEFAULT_TOKEN_CACHE_SIZE,
176            token_cache_ttl_secs: DEFAULT_TOKEN_CACHE_TTL_SECS,
177        }
178    }
179}
180
181impl OidcConfig {
182    /// Load OIDC configuration from environment variable
183    pub fn from_env() -> Result<Self> {
184        Self::from_env_var("MICROMEGAS_OIDC_CONFIG")
185    }
186
187    /// Load OIDC configuration from a named environment variable
188    pub fn from_env_var(name: &str) -> Result<Self> {
189        let json =
190            std::env::var(name).map_err(|_| anyhow!("{name} environment variable not set"))?;
191        let config: OidcConfig =
192            serde_json::from_str(&json).map_err(|e| anyhow!("Failed to parse {name}: {e:?}"))?;
193        Ok(config)
194    }
195}
196
197/// Audience can be either a string or an array of strings in OIDC tokens
198#[derive(Debug, Serialize, Deserialize)]
199#[serde(untagged)]
200enum Audience {
201    Single(String),
202    Multiple(Vec<String>),
203}
204
205impl Audience {
206    fn contains(&self, aud: &str) -> bool {
207        match self {
208            Audience::Single(s) => s == aud,
209            Audience::Multiple(v) => v.iter().any(|a| a == aud),
210        }
211    }
212}
213
214/// JWT Claims from OIDC ID token or access token
215///
216/// This struct supports multiple OIDC providers by including various email claim fields.
217/// Different providers use different claim names for email addresses:
218///
219/// Email extraction priority (see `get_email()` method):
220/// 1. `verified_primary_email` - Azure AD optional claim (most reliable, verified by provider)
221/// 2. `email` - Standard OIDC claim (Google, some Azure AD configurations)
222/// 3. `namespaced_email` - Custom namespaced claims (Auth0: `https://micromegas.io/email`)
223/// 4. `preferred_username` - Azure AD standard claim (often contains email)
224/// 5. `upn` - User Principal Name (Azure AD enterprise)
225/// 6. `unique_name` - Legacy Azure AD claim
226#[derive(Debug, Serialize, Deserialize)]
227struct Claims {
228    /// Issuer - identifies the principal that issued the JWT
229    iss: String,
230    /// Subject - identifies the principal that is the subject of the JWT
231    sub: String,
232    /// Audience - identifies the recipients that the JWT is intended for
233    /// Can be either a single string or an array of strings
234    aud: Audience,
235    /// Expiration time - identifies the expiration time on or after which the JWT must not be accepted
236    exp: i64,
237    /// Email address of the user (standard OIDC claim, used by Google and some Azure AD configurations)
238    #[serde(skip_serializing_if = "Option::is_none")]
239    email: Option<String>,
240    /// Verified primary email (Azure AD optional claim - most reliable, verified by provider)
241    #[serde(skip_serializing_if = "Option::is_none")]
242    verified_primary_email: Option<String>,
243    /// Preferred username (Azure AD standard claim, often contains email)
244    #[serde(skip_serializing_if = "Option::is_none")]
245    preferred_username: Option<String>,
246    /// User Principal Name (Azure AD enterprise claim)
247    #[serde(skip_serializing_if = "Option::is_none")]
248    upn: Option<String>,
249    /// Unique name (legacy Azure AD claim from older tokens)
250    #[serde(skip_serializing_if = "Option::is_none")]
251    unique_name: Option<String>,
252    /// Custom namespaced email claim (Auth0 custom claims via Actions)
253    #[serde(rename = "https://micromegas.io/email")]
254    #[serde(skip_serializing_if = "Option::is_none")]
255    namespaced_email: Option<String>,
256    /// Custom namespaced name claim (Auth0 custom claims via Actions)
257    #[serde(rename = "https://micromegas.io/name")]
258    #[serde(skip_serializing_if = "Option::is_none")]
259    namespaced_name: Option<String>,
260}
261
262impl Claims {
263    /// Get email from various possible claim fields
264    /// Priority order: verified_primary_email (most reliable) → email → namespaced_email → preferred_username → upn → unique_name
265    fn get_email(&self) -> Option<String> {
266        self.verified_primary_email
267            .clone()
268            .or_else(|| self.email.clone())
269            .or_else(|| self.namespaced_email.clone())
270            .or_else(|| self.preferred_username.clone())
271            .or_else(|| self.upn.clone())
272            .or_else(|| self.unique_name.clone())
273    }
274}
275
276/// OIDC issuer client for token validation
277struct OidcIssuerClient {
278    issuer: String,
279    audience: String,
280    jwks_cache: JwksCache,
281}
282
283impl OidcIssuerClient {
284    fn new(issuer: String, audience: String, jwks_ttl: Duration) -> Result<Self> {
285        let issuer_url = IssuerUrl::new(issuer.clone())
286            .map_err(|e| anyhow!("Invalid issuer URL '{}': {e:?}", issuer))?;
287
288        Ok(Self {
289            issuer,
290            audience,
291            jwks_cache: JwksCache::new(issuer_url, jwks_ttl),
292        })
293    }
294}
295
296/// Convert a JWK to a DecodingKey for jsonwebtoken
297fn jwk_to_decoding_key(
298    jwk: &openidconnect::core::CoreJsonWebKey,
299) -> Result<jsonwebtoken::DecodingKey> {
300    // Serialize the JWK to JSON to extract parameters
301    let jwk_json =
302        serde_json::to_value(jwk).map_err(|e| anyhow!("Failed to serialize JWK: {e:?}"))?;
303
304    // Extract n and e parameters
305    let n = jwk_json
306        .get("n")
307        .and_then(|v| v.as_str())
308        .ok_or_else(|| anyhow!("JWK missing 'n' parameter"))?;
309    let e = jwk_json
310        .get("e")
311        .and_then(|v| v.as_str())
312        .ok_or_else(|| anyhow!("JWK missing 'e' parameter"))?;
313
314    // Decode base64url encoded parameters
315    let n_bytes = base64::engine::general_purpose::URL_SAFE_NO_PAD
316        .decode(n.as_bytes())
317        .map_err(|e| anyhow!("Failed to decode 'n': {e:?}"))?;
318    let e_bytes = base64::engine::general_purpose::URL_SAFE_NO_PAD
319        .decode(e.as_bytes())
320        .map_err(|e| anyhow!("Failed to decode 'e': {e:?}"))?;
321
322    // Create RSA public key
323    let n_bigint = BigUint::from_bytes_be(&n_bytes);
324    let e_bigint = BigUint::from_bytes_be(&e_bytes);
325
326    let public_key = RsaPublicKey::new(n_bigint, e_bigint)
327        .map_err(|e| anyhow!("Failed to create RSA public key: {e:?}"))?;
328
329    // Convert to PEM format
330    let pem = public_key
331        .to_pkcs1_pem(rsa::pkcs1::LineEnding::LF)
332        .map_err(|e| anyhow!("Failed to encode public key as PEM: {e:?}"))?;
333
334    // Create DecodingKey
335    jsonwebtoken::DecodingKey::from_rsa_pem(pem.as_bytes())
336        .map_err(|e| anyhow!("Failed to create decoding key: {e:?}"))
337}
338
339/// OIDC authentication provider
340///
341/// Validates JWT tokens (access or ID tokens) from configured OIDC providers.
342/// Caches both JWKS and validated tokens for performance.
343pub struct OidcAuthProvider {
344    /// Map from issuer URL to list of clients (supports multiple audiences per issuer)
345    clients: HashMap<String, Vec<Arc<OidcIssuerClient>>>,
346    /// Cache for validated tokens
347    token_cache: Cache<String, Arc<AuthContext>>,
348}
349
350impl std::fmt::Debug for OidcAuthProvider {
351    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
352        f.debug_struct("OidcAuthProvider")
353            .field("num_clients", &self.clients.len())
354            .finish()
355    }
356}
357
358impl OidcAuthProvider {
359    /// Create a new OIDC authentication provider. Admin-ness is no longer resolved here --
360    /// it lives in the `admins` group, resolved by `MembershipProvider` after this provider
361    /// authenticates the request.
362    pub async fn new(config: OidcConfig) -> Result<Self> {
363        if config.issuers.is_empty() {
364            return Err(anyhow!("At least one OIDC issuer must be configured"));
365        }
366
367        micromegas_tracing::info!("Configuring OIDC with {} issuer(s)", config.issuers.len());
368        for (idx, issuer_config) in config.issuers.iter().enumerate() {
369            micromegas_tracing::info!(
370                "  Issuer {}: {} (audience: {})",
371                idx + 1,
372                issuer_config.issuer,
373                issuer_config.audience
374            );
375        }
376
377        let jwks_ttl = Duration::from_secs(config.jwks_refresh_interval_secs);
378        let mut clients: HashMap<String, Vec<Arc<OidcIssuerClient>>> = HashMap::new();
379
380        // Initialize a client for each configured issuer
381        // Supports multiple audiences for the same issuer (e.g., access tokens + ID tokens)
382        for issuer_config in config.issuers {
383            let client = OidcIssuerClient::new(
384                issuer_config.issuer.clone(),
385                issuer_config.audience,
386                jwks_ttl,
387            )?;
388
389            clients
390                .entry(issuer_config.issuer)
391                .or_default()
392                .push(Arc::new(client));
393        }
394
395        // Create token cache
396        let token_cache = Cache::builder()
397            .max_capacity(config.token_cache_size)
398            .time_to_live(Duration::from_secs(config.token_cache_ttl_secs))
399            .build();
400
401        Ok(Self {
402            clients,
403            token_cache,
404        })
405    }
406
407    /// Decode JWT payload without validation to extract issuer
408    ///
409    /// JWTs are structured as: header.payload.signature
410    /// Both header and payload are base64url-encoded JSON
411    fn decode_payload_unsafe(&self, token: &str) -> Result<Claims> {
412        let parts: Vec<&str> = token.split('.').collect();
413        if parts.len() != 3 {
414            return Err(anyhow!("Invalid JWT format"));
415        }
416
417        // Decode the payload (second part)
418        let payload_bytes = base64::engine::general_purpose::URL_SAFE_NO_PAD
419            .decode(parts[1].as_bytes())
420            .map_err(|e| anyhow!("Failed to decode JWT payload: {e:?}"))?;
421
422        let claims: Claims = serde_json::from_slice(&payload_bytes)
423            .map_err(|e| anyhow!("Failed to parse JWT claims: {e:?}"))?;
424
425        Ok(claims)
426    }
427
428    /// Validate a JWT token (access token or ID token) and return authentication context
429    ///
430    /// This implementation follows OAuth 2.0 best practices by:
431    /// 1. Extracting kid from JWT header for direct key lookup (falls back to trying all keys)
432    /// 2. Extracting issuer from JWT payload for direct client lookup
433    /// 3. Using O(1) lookups instead of O(n*m) iteration
434    /// 4. Eliminating timing side-channels
435    ///
436    /// Supports both:
437    /// - Access tokens (with API audience, used by Auth0 and similar)
438    /// - ID tokens (with client_id audience, used by Google/Azure AD)
439    async fn validate_jwt_token(&self, token: &str) -> Result<AuthContext> {
440        // Step 1: Decode header (unsigned) to get key ID (kid)
441        let header = decode_header(token).map_err(|e| anyhow!("Invalid JWT header: {e:?}"))?;
442
443        // kid is optional - some providers omit it when there's only one key
444        let kid = header.kid;
445
446        // Step 2: Decode payload (unsigned) to get issuer and expiration
447        let unverified_claims = self.decode_payload_unsafe(token)?;
448
449        // Step 3: Look up clients for this issuer
450        let issuer_clients = self
451            .clients
452            .get(&unverified_claims.iss)
453            .ok_or_else(|| anyhow!("Unknown issuer: {}", unverified_claims.iss))?;
454
455        // Step 4: Fetch JWKS once (all clients for the same issuer share the same JWKS)
456        // Use the first client's cache - they all point to the same issuer's JWKS endpoint
457        let first_client = issuer_clients
458            .first()
459            .ok_or_else(|| anyhow!("No clients configured for issuer"))?;
460
461        let jwks = first_client
462            .jwks_cache
463            .get()
464            .await
465            .map_err(|e| anyhow!("Failed to fetch JWKS: {e:?}"))?;
466
467        // Step 5: Find the key(s) to try
468        // If kid is present, look up directly; otherwise try all keys
469        let keys_to_try: Vec<_> = if let Some(ref kid_value) = kid {
470            // Direct lookup by kid
471            jwks.keys()
472                .iter()
473                .filter(|k| k.key_id().map(|id| id.as_str()) == Some(kid_value.as_str()))
474                .collect()
475        } else {
476            // No kid provided - try all keys (common for single-key providers)
477            jwks.keys().iter().collect()
478        };
479
480        if keys_to_try.is_empty() {
481            return Err(if let Some(kid_value) = kid {
482                anyhow!("Key with kid '{}' not found in JWKS", kid_value)
483            } else {
484                anyhow!("No keys found in JWKS")
485            });
486        }
487
488        // Step 6: Try each key until one works
489        let mut key_error = anyhow!("No valid key found");
490        for key in keys_to_try {
491            match jwk_to_decoding_key(key) {
492                Ok(decoding_key) => {
493                    match self
494                        .try_validate_with_key(token, &decoding_key, issuer_clients)
495                        .await
496                    {
497                        Ok(auth_ctx) => return Ok(auth_ctx),
498                        Err(e) => key_error = e,
499                    }
500                }
501                Err(e) => key_error = e,
502            }
503        }
504
505        Err(key_error)
506    }
507
508    /// Try to validate a token with a specific decoding key against all configured audiences
509    async fn try_validate_with_key(
510        &self,
511        token: &str,
512        decoding_key: &jsonwebtoken::DecodingKey,
513        issuer_clients: &[Arc<OidcIssuerClient>],
514    ) -> Result<AuthContext> {
515        let configured_audiences: Vec<String> =
516            issuer_clients.iter().map(|c| c.audience.clone()).collect();
517        let mut last_error = anyhow!("No matching audience found");
518
519        for client in issuer_clients {
520            // Validate token with specific key and issuer
521            let mut validation = Validation::new(Algorithm::RS256);
522            // Don't validate audience yet - we'll do it manually
523            validation.validate_aud = false;
524            validation.set_issuer(&[&client.issuer]);
525
526            let claims = match decode::<Claims>(token, decoding_key, &validation) {
527                Ok(token_data) => token_data.claims,
528                Err(e) => {
529                    last_error = anyhow!("Token validation failed: {e:?}");
530                    continue;
531                }
532            };
533
534            // Manually validate audience - if it matches, we found the right client!
535            if claims.aud.contains(&client.audience) {
536                // Success! Validate expiration and return auth context
537                let expires_at = DateTime::from_timestamp(claims.exp, 0)
538                    .ok_or_else(|| anyhow!("Invalid expiration timestamp"))?;
539
540                if expires_at < Utc::now() {
541                    return Err(anyhow!("Token has expired"));
542                }
543
544                let email = claims.get_email();
545
546                return Ok(AuthContext {
547                    subject: claims.sub,
548                    email,
549                    issuer: claims.iss,
550                    audience: Some(client.audience.clone()),
551                    expires_at: Some(expires_at),
552                    auth_type: AuthType::Oidc,
553                    allow_delegation: false,
554                    // OIDC tokens never carry Stage 4's write-side bound_audience or Stage 4b's
555                    // read_audiences grant -- those are key-provider fields.
556                    bound_audience: None,
557                    read_audiences: vec![],
558                    analytics_key_id: None,
559                    // Filled by `MembershipProvider`, not here -- see `AuthContext.memberships`'s
560                    // doc comment.
561                    memberships: Arc::from([]),
562                });
563            } else {
564                // Provide detailed error with configured vs actual audiences
565                let actual_audiences = match &claims.aud {
566                    Audience::Single(s) => vec![s.clone()],
567                    Audience::Multiple(v) => v.clone(),
568                };
569                last_error = anyhow!(
570                    "Token audience mismatch - configured audiences: {:?}, token audiences: {:?}",
571                    configured_audiences,
572                    actual_audiences
573                );
574            }
575        }
576
577        // If we get here, none of the clients matched
578        Err(last_error)
579    }
580}
581
582#[async_trait::async_trait]
583impl AuthProvider for OidcAuthProvider {
584    fn name(&self) -> &'static str {
585        "oidc"
586    }
587
588    async fn validate_request(
589        &self,
590        parts: &dyn crate::types::RequestParts,
591    ) -> Result<AuthContext> {
592        let token = parts
593            .bearer_token()
594            .ok_or_else(|| anyhow!("missing bearer token"))?;
595
596        // Check token cache first, but verify token hasn't expired
597        // Use 30-second grace period to account for clock skew and network latency
598        if let Some(cached) = self.token_cache.get(token).await {
599            let is_expired = cached
600                .expires_at
601                .map(|exp| exp <= Utc::now() + TimeDelta::seconds(30))
602                .unwrap_or(false);
603
604            if is_expired {
605                self.token_cache.remove(token).await;
606            } else {
607                return Ok((*cached).clone());
608            }
609        }
610
611        // Validate token
612        let auth_ctx = self.validate_jwt_token(token).await?;
613
614        // Cache the result
615        self.token_cache
616            .insert(token.to_string(), Arc::new(auth_ctx.clone()))
617            .await;
618
619        Ok(auth_ctx)
620    }
621}