Skip to main content

micromegas_auth/
multi.rs

1//! Multi-provider authentication that tries multiple auth methods in sequence.
2
3use crate::log_sanitize::sanitize_for_log;
4use crate::types::{AuthContext, AuthProvider, ProviderUnavailable};
5use async_trait::async_trait;
6use micromegas_tracing::prelude::*;
7use std::sync::Arc;
8
9/// Multi-provider authentication that tries providers in order until one succeeds.
10///
11/// This provider allows supporting multiple authentication methods simultaneously
12/// and enables adding custom enterprise authentication providers. Providers are
13/// tried in the order they were added via `with_provider()`.
14///
15/// Provider order matters for authentication precedence - the first successful
16/// match wins. Typically, you want faster providers (like API key) before slower
17/// ones (like OIDC JWT validation).
18///
19/// # Example
20///
21/// ```rust,no_run
22/// use micromegas_auth::api_key::{ApiKeyAuthProvider, parse_key_ring};
23/// use micromegas_auth::oidc::{OidcAuthProvider, OidcConfig, OidcIssuer};
24/// use micromegas_auth::multi::MultiAuthProvider;
25/// use std::sync::Arc;
26///
27/// # async fn example() -> anyhow::Result<()> {
28/// // Set up API key provider
29/// let keyring = parse_key_ring(r#"[{"name": "test", "key": "secret"}]"#)?;
30/// let api_key_provider = Arc::new(ApiKeyAuthProvider::new(keyring));
31///
32/// // Set up OIDC provider
33/// let oidc_config = OidcConfig {
34///     issuers: vec![OidcIssuer {
35///         issuer: "https://accounts.google.com".to_string(),
36///         audience: "your-app.apps.googleusercontent.com".to_string(),
37///     }],
38///     jwks_refresh_interval_secs: 3600,
39///     token_cache_size: 1000,
40///     token_cache_ttl_secs: 300,
41/// };
42/// let oidc_provider = Arc::new(OidcAuthProvider::new(oidc_config).await?);
43///
44/// // Create multi-provider with builder pattern
45/// let multi = MultiAuthProvider::new()
46///     .with_provider(api_key_provider)
47///     .with_provider(oidc_provider);
48/// // .with_provider(Arc::new(MyEnterpriseAuthProvider::new())); // Custom provider!
49/// # Ok(())
50/// # }
51/// ```
52pub struct MultiAuthProvider {
53    providers: Vec<Arc<dyn AuthProvider>>,
54}
55
56impl MultiAuthProvider {
57    /// Creates a new empty MultiAuthProvider.
58    #[allow(clippy::new_without_default)]
59    pub fn new() -> Self {
60        Self {
61            providers: Vec::new(),
62        }
63    }
64
65    /// Adds a provider to the authentication chain.
66    ///
67    /// Providers are tried in the order they are added. Returns self for chaining.
68    pub fn with_provider(mut self, provider: Arc<dyn AuthProvider>) -> Self {
69        self.providers.push(provider);
70        self
71    }
72
73    /// Returns true if no providers are configured.
74    pub fn is_empty(&self) -> bool {
75        self.providers.is_empty()
76    }
77}
78
79#[async_trait]
80impl AuthProvider for MultiAuthProvider {
81    fn name(&self) -> &'static str {
82        "multi"
83    }
84
85    async fn validate_request(
86        &self,
87        parts: &dyn crate::types::RequestParts,
88    ) -> anyhow::Result<AuthContext> {
89        // Tracks whether any provider in the chain failed because its store was
90        // unreachable, as opposed to a plain credential rejection. A request that
91        // might have matched a live key had the store been reachable must not be
92        // treated as a confirmed rejection once every provider has been tried.
93        let mut unavailable: Option<anyhow::Error> = None;
94        let mut reasons: Vec<String> = Vec::new();
95        for provider in &self.providers {
96            match provider.validate_request(parts).await {
97                Ok(auth_ctx) => {
98                    return Ok(auth_ctx);
99                }
100                Err(e) => {
101                    debug!("partial auth failed: {e:?}");
102                    // Truncated per provider so one huge reason can't push the others off the line.
103                    reasons.push(format!(
104                        "{}: {}",
105                        provider.name(),
106                        sanitize_for_log(&format!("{e:#}"), 160)
107                    ));
108                    if e.downcast_ref::<ProviderUnavailable>().is_some() {
109                        unavailable = Some(e);
110                    }
111                }
112            }
113        }
114        if let Some(e) = unavailable {
115            return Err(e);
116        }
117        if reasons.is_empty() {
118            anyhow::bail!("authentication failed with all providers: none configured");
119        }
120        anyhow::bail!(
121            "authentication failed with all providers: {}",
122            reasons.join("; ")
123        )
124    }
125}