Skip to main content

micromegas_auth/
default_provider.rs

1//! Default authentication provider initialization for Micromegas services.
2//!
3//! This module provides the standard way to initialize authentication with
4//! OIDC and a DB-backed API key store from environment variables.
5
6use crate::db_api_key::{
7    ApiKeyTable, DbApiKeyAuthProvider, DbApiKeyConfig, key_store_has_live_rows,
8};
9use crate::env::resolve_prefixed_var;
10use crate::groups::{DbGroupsConfig, DbGroupsSource};
11use crate::membership::MembershipProvider;
12use crate::multi::MultiAuthProvider;
13use crate::oidc::{OidcAuthProvider, OidcConfig};
14use crate::types::AuthProvider;
15use anyhow::Result;
16use micromegas_tracing::{info, warn};
17use sqlx::PgPool;
18use std::sync::Arc;
19use std::time::Duration;
20
21/// Builder for the default (env-driven) authentication provider stack, plus an
22/// optional DB-backed API key store and an optional local-group store.
23pub struct ProviderBuilder {
24    prefix: String,
25    key_store: Option<(PgPool, ApiKeyTable)>,
26    group_store: Option<PgPool>,
27}
28
29impl ProviderBuilder {
30    /// Starts a builder scoped to `prefix` (e.g. `"MICROMEGAS_INGESTION"`, or `""`
31    /// for the unprefixed default), following the same `{prefix}_*`-with-fallback
32    /// convention as [`resolve_prefixed_var`].
33    pub fn new(prefix: &str) -> Self {
34        Self {
35            prefix: prefix.to_string(),
36            key_store: None,
37            group_store: None,
38        }
39    }
40
41    /// Attaches a DB-backed key store bound to `table`, looked up through `pool`
42    /// (expected to be a [`crate::db_api_key::dedicated_key_store_pool`], not a
43    /// clone of the caller's lake pool).
44    pub fn with_db_key_store(mut self, pool: PgPool, table: ApiKeyTable) -> Self {
45        self.key_store = Some((pool, table));
46        self
47    }
48
49    /// Attaches a local-group store, looked up through `pool` (same dedicated-pool
50    /// expectation as [`Self::with_db_key_store`]). `compose()` wraps the finished chain in a
51    /// [`MembershipProvider`] when this is attached.
52    pub fn with_group_store(mut self, pool: PgPool) -> Self {
53        self.group_store = Some(pool);
54        self
55    }
56
57    /// Resolves the OIDC config env var name for this builder's prefix, with
58    /// fallback to the unprefixed name.
59    fn oidc_config_var(&self) -> String {
60        resolve_prefixed_var(&self.prefix, "OIDC_CONFIG")
61    }
62
63    /// Composes the chain and reports whether OIDC counted as "configured". Shared by `build()`
64    /// and `build_chain()`, which each document the provider order and the DB-provider
65    /// guarantee.
66    ///
67    /// Takes `&self` rather than `self` so `build()` can still reach the
68    /// attached key store's pool for its existence query afterwards.
69    async fn compose(&self) -> Result<(MultiAuthProvider, bool)> {
70        let oidc_config_var = self.oidc_config_var();
71
72        let mut multi = MultiAuthProvider::new();
73        let mut configured = false;
74
75        match OidcConfig::from_env_var(&oidc_config_var) {
76            Ok(config) => {
77                info!("Initializing OIDC authentication");
78                let oidc_provider = OidcAuthProvider::new(config).await?;
79                multi = multi.with_provider(Arc::new(oidc_provider));
80                configured = true;
81            }
82            Err(e) => {
83                info!("OIDC not configured ({e}) - OIDC auth disabled");
84            }
85        }
86
87        if let Some((pool, table)) = &self.key_store {
88            let db_config = DbApiKeyConfig::from_env_with_prefix(&self.prefix);
89            let db_provider = DbApiKeyAuthProvider::new(pool.clone(), *table, db_config);
90            multi = multi.with_provider(Arc::new(db_provider));
91        }
92
93        Ok((multi, configured))
94    }
95
96    /// Wraps `multi` in a [`MembershipProvider`] when a group store is attached, and runs one
97    /// eager `current()` at startup: on `Ok`, `warn!`s while `has_wildcard_admin()` is true
98    /// ("every authenticated caller is an admin; add a `user:` member to `admins` and remove
99    /// `*`"); on `Err`, `warn!`s and continues -- the first request will 503, and a split
100    /// deployment may legitimately start flight-sql before the migration runner is up, as with
101    /// the v5 key store.
102    async fn wrap_with_membership(&self, multi: MultiAuthProvider) -> Arc<dyn AuthProvider> {
103        let Some(pool) = &self.group_store else {
104            return Arc::new(multi) as Arc<dyn AuthProvider>;
105        };
106        let group_config = DbGroupsConfig::from_env_with_prefix(&self.prefix);
107        let groups = Arc::new(DbGroupsSource::new(
108            pool.clone(),
109            Duration::from_secs(group_config.cache_ttl_secs),
110        ));
111        match groups.current().await {
112            Ok(graph) => {
113                if graph.has_wildcard_admin() {
114                    warn!(
115                        "every authenticated caller is an admin; add a `user:` member to \
116                         `admins` and remove `*`"
117                    );
118                }
119            }
120            Err(e) => {
121                warn!("group store not yet reachable at startup, continuing: {e:#}");
122            }
123        }
124        Arc::new(MembershipProvider::new(
125            Arc::new(multi) as Arc<dyn AuthProvider>,
126            groups,
127        )) as Arc<dyn AuthProvider>
128    }
129
130    /// Builds the composed provider.
131    ///
132    /// Composes, in order: `OidcAuthProvider` → `DbApiKeyAuthProvider`; `MultiAuthProvider` tries
133    /// providers in order, so putting the DB provider last means only tokens that are not a valid
134    /// JWT ever reach it. The DB provider is always pushed onto the chain whenever a key store is
135    /// attached, so a key minted into a previously empty table authenticates on the very next
136    /// request, with no restart.
137    ///
138    /// **A DB key store with at least one live key counts as "auth configured";
139    /// an empty one does not.** When a key store is attached, this runs one cheap
140    /// startup existence query (`key_store_has_live_rows`) and treats a non-empty
141    /// result the same as OIDC being present. A failure of that query
142    /// (e.g. a missing relation because the schema has not reached migration v5
143    /// yet) is propagated as an `Err` from `build()` — unless OIDC
144    /// already configured auth, in which case the failure is only `warn!`-logged
145    /// and `has_live_rows` is treated as `false`, since the query's result would
146    /// be unused either way.
147    ///
148    /// The chain is discarded when nothing counted as configured; use
149    /// `build_chain()` to skip the guard.
150    pub async fn build(self) -> Result<Option<Arc<dyn AuthProvider>>> {
151        let (multi, mut configured) = self.compose().await?;
152
153        if let Some((pool, table)) = &self.key_store {
154            let has_live_rows = match key_store_has_live_rows(pool, *table).await {
155                Ok(has_live_rows) => has_live_rows,
156                Err(e) if !configured => {
157                    return Err(e.context(format!(
158                        "checking whether {} has any live key — has the schema reached migration v5? \
159                         (rust/ingestion/src/sql_migration.rs; the ingestion binary or monolith must run \
160                         the migration before flight-sql starts in a split deployment)",
161                        table.table_name()
162                    )));
163                }
164                Err(e) => {
165                    // Auth is already configured via another provider (OIDC); this
166                    // query's only purpose is deciding whether an otherwise-unconfigured
167                    // deployment counts as configured, so a failure here (e.g. schema
168                    // not yet at v5) must not abort startup.
169                    warn!(
170                        "checking whether {} has any live key failed, ignoring (auth already configured): {e:#}",
171                        table.table_name()
172                    );
173                    false
174                }
175            };
176            if has_live_rows {
177                configured = true;
178            }
179        }
180
181        if !configured {
182            return Ok(None);
183        }
184
185        Ok(Some(self.wrap_with_membership(multi).await))
186    }
187
188    /// Composes the provider chain with **no** "is anything configured?" guard.
189    ///
190    /// Composes, in order: `OidcAuthProvider` → `DbApiKeyAuthProvider`. The DB provider is always
191    /// pushed onto the chain whenever a key store is attached, so a key minted into a previously
192    /// empty table authenticates on the very next request, with no restart.
193    ///
194    /// Always returns the chain — never `None`, because there is no `Option` —
195    /// and never runs `key_store_has_live_rows`, so unlike `build()` it cannot
196    /// fail on a schema short of migration v5. This is the entry point for a
197    /// caller that wants the no-restart property above without inheriting
198    /// `build()`'s startup guard or its existence-query failure mode — e.g. an
199    /// embedder folding this chain into a larger `MultiAuthProvider` via
200    /// `FlightSqlServer::with_auth_provider`.
201    ///
202    /// When nothing at all is configured (no OIDC, no key store)
203    /// the returned chain is an empty `MultiAuthProvider`, which rejects every
204    /// request — fail-closed, since the caller asked for no guard. Logs a
205    /// `warn!` in that case, since an empty chain is useless to any caller.
206    pub async fn build_chain(self) -> Result<Arc<dyn AuthProvider>> {
207        let (multi, _) = self.compose().await?;
208        if multi.is_empty() {
209            warn!("no auth provider configured: OIDC and DB key store are both absent");
210        }
211        Ok(self.wrap_with_membership(multi).await)
212    }
213}