Skip to main content

micromegas_auth/
groups.rs

1//! Local group membership: the `groups`/`group_members` tables (migration v10,
2//! `rust/ingestion/src/sql_migration.rs`), a whole-table snapshot cache ([`crate::groups::DbGroupsSource`])
3//! mirroring [`crate::db_audience_grants::DbAudienceGrantsSource`], and [`crate::groups::GroupGraph`], the
4//! in-memory closure resolver over a loaded snapshot.
5//!
6//! A `group_members.member` row is a selector in exactly the vocabulary
7//! `audience_grants.selector` uses (`*`, `user:<email>`, `group:<name>`, `key:<key_id>`), so nesting is the
8//! `group:` arm of the same predicate rather than a special case -- see [`crate::groups::GroupGraph::closure`].
9
10use crate::db_api_key::resolve_u64;
11use crate::db_snapshot::{Parsed, SnapshotLoader, SnapshotSource, report_skipped};
12use crate::policy::{key_selector, valid_selector};
13use anyhow::{Context, Result};
14use async_trait::async_trait;
15use sqlx::{PgPool, Row};
16use std::collections::{BTreeMap, BTreeSet, VecDeque};
17use uuid::Uuid;
18
19/// The reserved group whose membership is admin-ness -- `AuthContext::is_admin` is exactly
20/// "does this caller's closure contain this name".
21pub const ADMINS_GROUP: &str = "admins";
22
23/// `true` if `name` is a valid group name: `[A-Za-z0-9_-]{1,255}` -- the same charset
24/// `is_valid_audience` uses, checked in bytes, so a group name is URL-safe and a distinct kind of
25/// thing from an email.
26pub fn is_valid_group_name(name: &str) -> bool {
27    !name.is_empty()
28        && name.len() <= 255
29        && name
30            .bytes()
31            .all(|b| b.is_ascii_alphanumeric() || b == b'_' || b == b'-')
32}
33
34/// A loaded, in-memory snapshot of the `groups`/`group_members` tables, and the closure resolver
35/// over it. Sync and infallible once built: every method here is a walk over an already-loaded
36/// snapshot, never a query.
37#[derive(Debug, Clone, Default)]
38pub struct GroupGraph {
39    /// Every group name, whether or not it has any members.
40    groups: BTreeSet<String>,
41    /// member selector (`*`, `user:<email>`, `group:<name>`, or `key:<key_id>`) -> the groups it is a *direct*
42    /// member of.
43    members_of: BTreeMap<String, Vec<String>>,
44}
45
46impl GroupGraph {
47    /// Builds a graph from `(name)` rows out of `groups` and `(group_name, member)` rows out of
48    /// `group_members`. Runs the name charset and [`valid_selector`] checks the way
49    /// `AudienceGrants::from_rows` does -- the tables carry no shape CHECK, so this is where a
50    /// malformed row (e.g. from a direct `psql` session) is skipped, with the reason in
51    /// [`Parsed::skipped`], rather than reaching a decision or failing the load. A skipped group
52    /// name also fails the same check on its member rows, so no edge points at a missing group.
53    pub fn from_rows(
54        groups: impl IntoIterator<Item = String>,
55        members: impl IntoIterator<Item = (String, String)>,
56    ) -> Parsed<Self> {
57        let mut skipped = Vec::new();
58        let mut group_set = BTreeSet::new();
59        for name in groups {
60            if !is_valid_group_name(&name) {
61                skipped.push(format!("groups row ({name:?}): invalid group name"));
62                continue;
63            }
64            group_set.insert(name);
65        }
66        let mut members_of: BTreeMap<String, Vec<String>> = BTreeMap::new();
67        for (group_name, member) in members {
68            if !is_valid_group_name(&group_name) {
69                skipped.push(format!(
70                    "group_members row ({group_name:?}, {member}): invalid group name"
71                ));
72                continue;
73            }
74            if !valid_selector(&member) {
75                skipped.push(format!(
76                    "group_members row ({group_name:?}, {member}): invalid member selector"
77                ));
78                continue;
79            }
80            members_of.entry(member).or_default().push(group_name);
81        }
82        Parsed {
83            value: Self {
84                groups: group_set,
85                members_of,
86            },
87            skipped,
88        }
89    }
90
91    /// Every known group name, sorted.
92    pub fn group_names(&self) -> impl Iterator<Item = &String> {
93        self.groups.iter()
94    }
95
96    /// Whether `name` is a known group.
97    pub fn contains_group(&self, name: &str) -> bool {
98        self.groups.contains(name)
99    }
100
101    /// Breadth-first walk upward, starting from `initial` and repeatedly following
102    /// `members_of["group:g"]` for each newly reached group `g`. The visited set is what
103    /// tolerates a cycle at read time. A `barrier` group is never inserted nor traversed, so
104    /// nothing reachable only through it is either.
105    fn walk_upward(&self, initial: BTreeSet<String>, barrier: Option<&str>) -> BTreeSet<String> {
106        let mut initial = initial;
107        if let Some(b) = barrier {
108            initial.remove(b);
109        }
110        let mut visited = initial.clone();
111        let mut queue: VecDeque<String> = initial.into_iter().collect();
112        while let Some(g) = queue.pop_front() {
113            if let Some(next) = self.members_of.get(&format!("group:{g}")) {
114                for ng in next {
115                    if barrier == Some(ng.as_str()) {
116                        continue;
117                    }
118                    if visited.insert(ng.clone()) {
119                        queue.push_back(ng.clone());
120                    }
121                }
122            }
123        }
124        visited
125    }
126
127    /// The caller's resolved, transitive group membership: a breadth-first walk **upward** from
128    /// the caller, seeded at the groups listed under the selectors `*` and `user:<email>` (when
129    /// `email` is `Some`), unioned with the walk from `key:<key_id>` (when `key_id` is `Some`).
130    /// The key walk never reaches [`ADMINS_GROUP`] -- a key is never made admin by membership,
131    /// whether listed directly, nested, or via a group above `admins`. The `*` walk is not
132    /// barred, so a bootstrap `('admins', '*')` row still makes every caller admin. Returned
133    /// sorted, deduplicated. Sync and infallible: the graph is an already-loaded snapshot.
134    pub fn closure(&self, email: Option<&str>, key_id: Option<Uuid>) -> Vec<String> {
135        let mut initial = BTreeSet::new();
136        if let Some(gs) = self.members_of.get("*") {
137            initial.extend(gs.iter().cloned());
138        }
139        if let Some(email) = email
140            && let Some(gs) = self.members_of.get(&format!("user:{email}"))
141        {
142            initial.extend(gs.iter().cloned());
143        }
144        let mut result = self.walk_upward(initial, None);
145        if let Some(key_id) = key_id
146            && let Some(gs) = self.members_of.get(&key_selector(key_id))
147        {
148            result.extend(self.walk_upward(gs.iter().cloned().collect(), Some(ADMINS_GROUP)));
149        }
150        result.into_iter().collect()
151    }
152
153    /// `true` when the wildcard selector `*` reaches [`ADMINS_GROUP`] -- directly (`('admins',
154    /// '*')`) or through nesting. Reuses the same upward walk as [`Self::closure`], seeded at `*`
155    /// alone (no caller email).
156    pub fn has_wildcard_admin(&self) -> bool {
157        self.closure(None, None).iter().any(|g| g == ADMINS_GROUP)
158    }
159
160    /// `true` when `target` is reachable from *some* principal -- the wildcard `*` selector or
161    /// any `user:<email>` selector present in the snapshot -- directly or through nesting.
162    /// Generalizes [`Self::has_wildcard_admin`] (which seeds the walk from `*` alone) to seed
163    /// from every base selector on record, so a caller can check "would `target` still be
164    /// reachable by anyone" rather than "by `*` specifically" -- e.g. before removing a
165    /// membership that would strand `ADMINS_GROUP` behind a user-only or nested-only path.
166    pub fn any_principal_reaches(&self, target: &str) -> bool {
167        let mut initial = BTreeSet::new();
168        for (selector, groups) in &self.members_of {
169            if selector == "*" || selector.starts_with("user:") {
170                initial.extend(groups.iter().cloned());
171            }
172        }
173        self.walk_upward(initial, None).iter().any(|g| g == target)
174    }
175
176    /// Whether adding `group:nested` as a member of `group` would create a cycle: `nested ==
177    /// group`, or `nested` is already reachable upward from `group` (a walk seeded at `group`
178    /// reaches it -- i.e. `group` is already, directly or transitively, nested into `nested`).
179    pub fn nesting_would_cycle(&self, group: &str, nested: &str) -> bool {
180        if nested == group {
181            return true;
182        }
183        self.walk_upward(BTreeSet::from([group.to_string()]), None)
184            .contains(nested)
185    }
186}
187
188/// Cache-TTL knob for [`DbGroupsSource`], read from env with a default.
189#[derive(Clone, Copy, Debug)]
190pub struct DbGroupsConfig {
191    /// `MICROMEGAS_AUTH_CACHE_TTL_SECONDS`, default 60 -- a single flat, unprefixed knob (no
192    /// `{prefix}_` role variant) shared with `DbApiKeyConfig`/`DbAudienceGrantsConfig`'s own
193    /// positive-cache TTL: one value governs the API-key, audience-grant, and group snapshot
194    /// caches process-wide, across every role. Membership and admin changes take effect within
195    /// this TTL per process; that is the documented latency.
196    pub cache_ttl_secs: u64,
197}
198
199impl DbGroupsConfig {
200    /// Resolves the flat, unprefixed `MICROMEGAS_AUTH_CACHE_TTL_SECONDS` knob directly -- there
201    /// is exactly one value for this knob process-wide, so `prefix` is accepted (for call-site
202    /// symmetry with every other `from_env_with_prefix`) but not consulted here.
203    pub fn from_env_with_prefix(_prefix: &str) -> Self {
204        Self {
205            cache_ttl_secs: resolve_u64("", "AUTH_CACHE_TTL_SECONDS", 60),
206        }
207    }
208}
209
210/// [`SnapshotLoader`] for the `groups`/`group_members` tables.
211#[derive(Debug)]
212pub struct GroupsLoader;
213
214#[async_trait]
215impl SnapshotLoader for GroupsLoader {
216    type Snapshot = GroupGraph;
217    const NAME: &'static str = "group store";
218
219    /// Runs both `SELECT`s in one read transaction and builds a [`GroupGraph`], so a concurrent
220    /// `DELETE ... CASCADE` cannot yield a snapshot with members of a group the `groups` query
221    /// missed.
222    async fn fetch(pool: &PgPool) -> Result<GroupGraph> {
223        let mut tx = pool
224            .begin()
225            .await
226            .context("starting group store read transaction")?;
227        let group_rows = sqlx::query("SELECT name FROM groups")
228            .fetch_all(&mut *tx)
229            .await
230            .context("querying groups")?;
231        let mut names = Vec::with_capacity(group_rows.len());
232        for row in group_rows {
233            let name: String = row.try_get("name").context("reading name")?;
234            names.push(name);
235        }
236        let member_rows = sqlx::query("SELECT group_name, member FROM group_members")
237            .fetch_all(&mut *tx)
238            .await
239            .context("querying group_members")?;
240        let mut members = Vec::with_capacity(member_rows.len());
241        for row in member_rows {
242            let group_name: String = row.try_get("group_name").context("reading group_name")?;
243            let member: String = row.try_get("member").context("reading member")?;
244            members.push((group_name, member));
245        }
246        tx.commit()
247            .await
248            .context("committing group store read transaction")?;
249        let parsed = GroupGraph::from_rows(names, members);
250        micromegas_tracing::imetric!(
251            "group_skipped_row_count",
252            "count",
253            parsed.skipped.len() as u64
254        );
255        if !parsed.skipped.is_empty() {
256            report_skipped(Self::NAME, &parsed.skipped);
257        }
258        Ok(parsed.value)
259    }
260
261    fn count_refresh_error() {
262        micromegas_tracing::imetric!("group_refresh_error_count", "count", 1_u64);
263    }
264}
265
266/// The whole-table snapshot cache described in the module doc comment.
267pub type DbGroupsSource = SnapshotSource<GroupsLoader>;