micromegas_auth/db_audience_grants.rs
1//! DB-backed audience grant store: a whole-table snapshot cache over the `audience_grants` table
2//! (migration v7, `rust/ingestion/src/sql_migration.rs`), checked alongside the static grant map
3//! by [`crate::policy::AudienceReadPolicy`]/[`crate::policy::AudienceMintPolicy`] -- a selector
4//! present in either source grants access, without either side being deep-cloned or merged into
5//! a combined map (`current()` hands back the cached grants behind an `Arc`). This is what makes
6//! a grant creatable without a service restart -- the static map stays the bootstrap/test-only
7//! layer.
8//!
9//! The cache mechanics (cold-start throttling, last-good serving, `ProviderUnavailable`
10//! wrapping) live in [`crate::db_snapshot`], shared with [`crate::groups::DbGroupsSource`].
11
12use crate::db_api_key::resolve_u64;
13use crate::db_snapshot::{SnapshotLoader, SnapshotSource, report_skipped};
14use crate::policy::{AudienceGrants, GrantAxis};
15use anyhow::{Context, Result};
16use async_trait::async_trait;
17use sqlx::{PgPool, Row};
18
19/// Cache-TTL knob for [`DbAudienceGrantsSource`], read from env with a default.
20#[derive(Clone, Copy, Debug)]
21pub struct DbAudienceGrantsConfig {
22 /// `MICROMEGAS_AUTH_CACHE_TTL_SECONDS`, default 60 -- a single flat, unprefixed knob (no
23 /// `{prefix}_` role variant) shared with `DbApiKeyConfig`/`DbGroupsConfig`'s own
24 /// positive-cache TTL: one value governs the API-key, audience-grant, and group snapshot
25 /// caches process-wide, across every role.
26 pub cache_ttl_secs: u64,
27}
28
29impl DbAudienceGrantsConfig {
30 /// Resolves the flat, unprefixed `MICROMEGAS_AUTH_CACHE_TTL_SECONDS` knob directly -- there
31 /// is exactly one value for this knob process-wide, so `prefix` is accepted (for call-site
32 /// symmetry with every other `from_env_with_prefix`) but not consulted here.
33 pub fn from_env_with_prefix(_prefix: &str) -> Self {
34 Self {
35 cache_ttl_secs: resolve_u64("", "AUTH_CACHE_TTL_SECONDS", 60),
36 }
37 }
38}
39
40/// Maps the `axis` column to a [`GrantAxis`], or the reason the row is skipped.
41pub fn parse_axis(
42 audience: &str,
43 axis: &str,
44 selector: &str,
45) -> std::result::Result<GrantAxis, String> {
46 match axis {
47 "read" => Ok(GrantAxis::Read),
48 "mint" => Ok(GrantAxis::Mint),
49 other => Err(format!(
50 "audience_grants row ({audience:?}, {other}, {selector}): unrecognized axis"
51 )),
52 }
53}
54
55/// [`SnapshotLoader`] for the `audience_grants` table.
56#[derive(Debug)]
57pub struct AudienceGrantsLoader;
58
59#[async_trait]
60impl SnapshotLoader for AudienceGrantsLoader {
61 type Snapshot = AudienceGrants;
62 const NAME: &'static str = "audience grant store";
63
64 /// Queries the whole table and builds an `AudienceGrants` via
65 /// [`AudienceGrants::from_rows`]. A malformed row (the table carries no shape `CHECK`, so e.g.
66 /// a direct `psql` write) is skipped with a warning and the
67 /// `audience_grant_skipped_row_count` metric rather than failing the load.
68 async fn fetch(pool: &PgPool) -> Result<AudienceGrants> {
69 let rows = sqlx::query("SELECT audience, axis, selector FROM audience_grants")
70 .fetch_all(pool)
71 .await
72 .context("querying audience_grants")?;
73 let mut triples = Vec::with_capacity(rows.len());
74 let mut skipped = Vec::new();
75 for row in rows {
76 let audience: String = row.try_get("audience").context("reading audience")?;
77 let axis: String = row.try_get("axis").context("reading axis")?;
78 let selector: String = row.try_get("selector").context("reading selector")?;
79 match parse_axis(&audience, &axis, &selector) {
80 Ok(axis) => triples.push((audience, axis, selector)),
81 Err(reason) => skipped.push(reason),
82 }
83 }
84 let mut parsed = AudienceGrants::from_rows(triples);
85 skipped.append(&mut parsed.skipped);
86 micromegas_tracing::imetric!(
87 "audience_grant_skipped_row_count",
88 "count",
89 skipped.len() as u64
90 );
91 if !skipped.is_empty() {
92 report_skipped(Self::NAME, &skipped);
93 }
94 Ok(parsed.value)
95 }
96
97 fn count_refresh_error() {
98 micromegas_tracing::imetric!("audience_grant_refresh_error_count", "count", 1_u64);
99 }
100}
101
102/// The whole-table snapshot cache described in the module doc comment.
103pub type DbAudienceGrantsSource = SnapshotSource<AudienceGrantsLoader>;