Skip to main content

micromegas_auth/
policy.rs

1//! Authorization seam: `MintPolicy`, `ReadPolicy`, and the audience-based implementations that
2//! resolve them from a caller's `AuthContext` and a static grant map keyed by audience name.
3//!
4//! **No enforcement lands with this module itself.** This module fixes the *shape* of
5//! authorization -- every caller of these traits must deny on `Err`, and `ReadPolicy` cannot
6//! express `ReadScope::All` at all (its widest answer, `ReadableAudiences::Every`, is still
7//! row-filtered) -- while the resolved `ReadableAudiences`/`ReadScope` is
8//! consumed downstream by `OwnershipRewrite` (the row-level filter) and the call-level guard's UDTF/UDF guards. See
9//! `rust/analytics/src/lakehouse/read_scope.rs`.
10//!
11//! **An audience is an opaque label, not a principal encoding.** `is_valid_audience` and
12//! `PUBLIC_AUDIENCE` define what a name is; `AudienceGrants` defines who may read or mint into
13//! it. No code here derives an audience from a caller's identity -- see `AudienceGrants` for the
14//! reasoning.
15
16use crate::db_audience_grants::DbAudienceGrantsSource;
17use crate::db_snapshot::Parsed;
18use crate::env::resolve_prefixed_var;
19use crate::types::AuthContext;
20use anyhow::{Result, anyhow};
21use async_trait::async_trait;
22use micromegas_tracing::{info, warn};
23use serde::Deserialize;
24use serde::de::{self, MapAccess, Visitor};
25use std::collections::BTreeMap;
26use std::collections::BTreeSet;
27use std::fmt;
28use std::fmt::Debug;
29use std::sync::Arc;
30use uuid::Uuid;
31
32/// The conventional shared audience. Not a built-in read grant -- every-principal readability
33/// comes from the seeded `('public', 'read', '*')` row (schema v9), an ordinary grant like any
34/// other, removable the same way.
35pub const PUBLIC_AUDIENCE: &str = "public";
36
37/// `true` if `aud` is a valid audience name: `[A-Za-z0-9_-]{1,255}`, checked in bytes -- the
38/// ASCII-only charset makes byte length and char length agree for every value that can pass, so
39/// this doubles as the length check the `ingestion_api_keys.audience` `VARCHAR(255)` column
40/// enforces on the SQL side.
41///
42/// An audience is an opaque label on data, not a principal encoding: this charset makes an email
43/// (`@`, `.`) or a `user:`/`group:`-prefixed value (`:`) unrepresentable, on purpose -- see
44/// `AudienceGrants` for why there is no derivation from a caller's identity to replace it with.
45///
46/// Deliberately **not** normalizing: no case folding, no trimming. The value is stored and
47/// compared verbatim, which is what makes uniqueness meaningful -- `team-alpha` and `Team-Alpha`
48/// are two audiences, and neither is a typo the system silently repairs into the other.
49pub fn is_valid_audience(aud: &str) -> bool {
50    !aud.is_empty()
51        && aud.len() <= 255
52        && aud
53            .bytes()
54            .all(|b| b.is_ascii_alphanumeric() || b == b'_' || b == b'-')
55}
56
57/// The grant audience meaning every audience, current and future. Read axis only.
58pub const ALL_AUDIENCES: &str = "*";
59
60/// `true` if `aud` is a valid audience in a *grant*: [`ALL_AUDIENCES`] or a valid audience name.
61/// `*` is never a valid stamped audience ([`is_valid_audience`] rejects it).
62pub fn is_valid_grant_audience(aud: &str) -> bool {
63    aud == ALL_AUDIENCES || is_valid_audience(aud)
64}
65
66/// Resolves `{prefix}_DEFAULT_AUDIENCE` (falling back to `MICROMEGAS_DEFAULT_AUDIENCE`) --
67/// **the** deployment default audience, defaulting to [`PUBLIC_AUDIENCE`] when unset. Resolved
68/// **once at startup** (`web_server.rs`) so a typo fails fast rather than surfacing as a
69/// per-request 400. Empty or otherwise invalid ⇒ `Err`: with one knob there is no "unset" state
70/// left for an empty string to mean, so a blank value is a misconfiguration, not an opt-out.
71///
72/// Leading/trailing whitespace is trimmed and `warn!`-logged, the same way the other two readers
73/// of this same variable handle it, so one env value can never be accepted by one role and
74/// rejected by another. Trimming keeps a value a deployment template rendered with stray
75/// padding working; the warning stays because padding is far more likely a templating slip than
76/// an intention.
77///
78/// One knob, one meaning: the audience anything that arrives without one gets. There are three
79/// code readers today (not deployment roles -- a role can build more than one of these):
80/// this function (key mint), `micromegas_analytics::audience::default_audience_from_env`
81/// (read once by `LakehouseContext::new` and handed to the three Postgres read sites), and the
82/// ingestion HTTP edge's own call in `serve_ingestion`, which resolves the default a credential
83/// with no bound audience is stamped with at write time. This is what
84/// `ingestion_keys.rs::resolve_audience` falls back to on the `mint` route.
85pub fn default_audience_from_env(prefix: &str) -> Result<String> {
86    let var = resolve_prefixed_var(prefix, "DEFAULT_AUDIENCE");
87    let resolved = match std::env::var(&var) {
88        Ok(raw) => {
89            let trimmed = raw.trim();
90            if trimmed != raw {
91                warn!(
92                    "{var}: value {raw:?} has leading or trailing whitespace -- using {trimmed:?}"
93                );
94            }
95            let raw = trimmed.to_string();
96            if is_valid_audience(&raw) {
97                raw
98            } else {
99                return Err(anyhow!(
100                    "{var}: {raw:?} is not a valid audience name -- must match [A-Za-z0-9_-]{{1,255}}"
101                ));
102            }
103        }
104        Err(_) => PUBLIC_AUDIENCE.to_owned(),
105    };
106    info!("{var}: default audience = {resolved}");
107    Ok(resolved)
108}
109
110/// A principal selector on either axis of an [`AudienceGrants`] entry: `*` (any authenticated
111/// principal), `user:<email>` (matches `AuthContext.email`), `group:<g>` (matches any entry in
112/// `AuthContext.memberships` -- the caller's resolved, transitive local-group closure), or
113/// `key:<uuid>` in canonical form (matches `AuthContext.analytics_key_id`). Validated at parse
114/// time; `resolve`/`resolve_audience` never see an unrecognized shape. This is the only place
115/// selector shape is enforced: the tables carry no CHECK for it.
116///
117/// `pub` -- `analytics-web-srv`'s admin grant-write route (a separate crate) needs to run this
118/// exact same selector-shape check `parse`/`from_rows` run, not a re-implementation of it.
119pub fn valid_selector(selector: &str) -> bool {
120    selector == "*"
121        || selector
122            .strip_prefix("user:")
123            .is_some_and(|rest| !rest.is_empty())
124        || selector
125            .strip_prefix("group:")
126            .is_some_and(|rest| !rest.is_empty())
127        || parse_key_selector(selector).is_some()
128}
129
130/// The `key:<key_id>` selector naming an analytics API key.
131pub fn key_selector(key_id: Uuid) -> String {
132    format!("key:{key_id}")
133}
134
135/// The key id of a `key:<uuid>` selector, only when the uuid is in canonical (lowercase,
136/// hyphenated) form. Matching is an exact string compare, so any other spelling would be a
137/// selector that never matches.
138pub fn parse_key_selector(selector: &str) -> Option<Uuid> {
139    let rest = selector.strip_prefix("key:")?;
140    let id = Uuid::parse_str(rest).ok()?;
141    (id.to_string() == rest).then_some(id)
142}
143
144/// The grant selectors `caller` matches: a leading `"*"` (every caller matches it), then
145/// `"user:<email>"` when `caller.email` is `Some`, then `"key:<id>"` when `caller.analytics_key_id`
146/// is `Some`, then one `"group:<g>"` per entry in `caller.memberships`. `pub` -- shared by three
147/// consumers: `flight_sql_service_impl.rs`'s `CallerContext::grant_selectors`, `analytics-web-srv`'s `my_audiences` handler, and the
148/// audience-grant write policy's per-pair hold check (which must strip the leading `"*"` before
149/// binding the result -- a `*` grant is not something a caller individually holds).
150pub fn caller_selectors(caller: &AuthContext) -> Vec<String> {
151    let mut selectors = vec!["*".to_string()];
152    if let Some(email) = &caller.email {
153        selectors.push(format!("user:{email}"));
154    }
155    if let Some(key_id) = caller.analytics_key_id {
156        selectors.push(key_selector(key_id));
157    }
158    selectors.extend(caller.memberships.iter().map(|g| format!("group:{g}")));
159    selectors
160}
161
162fn selector_matches(selector: &str, caller: &AuthContext) -> bool {
163    if selector == "*" {
164        return true;
165    }
166    if let Some(email) = selector.strip_prefix("user:") {
167        return caller.email.as_deref() == Some(email);
168    }
169    if let Some(group) = selector.strip_prefix("group:") {
170        return caller.memberships.iter().any(|g| g == group);
171    }
172    if selector.starts_with("key:") {
173        return caller
174            .analytics_key_id
175            .is_some_and(|k| key_selector(k) == selector);
176    }
177    // Unreachable given `valid_selector` gates every selector at parse time; false rather than
178    // panicking keeps this fail-closed if that invariant is ever violated.
179    false
180}
181
182/// One audience's read/mint selector lists, both already validated by [`AudienceGrants::parse`].
183#[derive(Debug, Clone, Default)]
184struct GrantEntry {
185    read: Vec<String>,
186    mint: Vec<String>,
187}
188
189/// The Rust side of `audience_grants.axis` -- which selector list a DB row
190/// contributes to, mirroring the JSON grant map's `"read"`/`"mint"` keys.
191#[derive(Debug, Clone, Copy, PartialEq, Eq)]
192pub enum GrantAxis {
193    Read,
194    Mint,
195}
196
197/// The bare-array-or-object shape a single grant-map value may take on the wire, before content
198/// validation. An untagged enum rather than a hand-rolled visitor: JSON arrays and objects are
199/// syntactically distinct, so serde can dispatch on shape alone, and any value that is neither
200/// (a number, a string, `null`, ...) fails here with serde's own type-mismatch error.
201#[derive(Debug, Deserialize)]
202#[serde(untagged)]
203enum RawGrantValue {
204    /// Read-only shorthand: a bare array is the audience's `read` list, with an implicitly empty
205    /// `mint` list -- never derived from `read`.
206    Bare(Vec<String>),
207    /// The explicit form, needed only when an audience also grants mint authority.
208    Object(RawGrantObject),
209}
210
211/// The object form of a single grant-map value, broken out of [`RawGrantValue::Object`] so
212/// `#[serde(deny_unknown_fields)]` -- which serde cannot apply directly to an enum variant --
213/// has somewhere to attach: without it, a misspelled key (`"raed"` for `"read"`) would silently
214/// parse into an empty grant instead of failing startup.
215#[derive(Debug, Deserialize)]
216#[serde(deny_unknown_fields)]
217struct RawGrantObject {
218    #[serde(default)]
219    read: Vec<String>,
220    #[serde(default)]
221    mint: Vec<String>,
222}
223
224/// Deserializes a grant-map JSON document while rejecting a repeated key -- `serde_json`'s own
225/// `Map` deserialization silently keeps the *last* value for a duplicate key, which would discard
226/// an earlier grant list without a word (see `AudienceGrants`'s doc comment). Pulling keys one at
227/// a time through `MapAccess`, rather than deserializing straight into a `BTreeMap`, is what makes
228/// that duplicate visible before it is lost.
229struct RawAudienceGrants(BTreeMap<String, RawGrantValue>);
230
231impl<'de> Deserialize<'de> for RawAudienceGrants {
232    fn deserialize<D>(deserializer: D) -> std::result::Result<Self, D::Error>
233    where
234        D: serde::Deserializer<'de>,
235    {
236        struct GrantsVisitor;
237
238        impl<'de> Visitor<'de> for GrantsVisitor {
239            type Value = RawAudienceGrants;
240
241            fn expecting(&self, f: &mut fmt::Formatter) -> fmt::Result {
242                write!(f, "a JSON object keyed by audience name")
243            }
244
245            fn visit_map<A>(self, mut map: A) -> std::result::Result<Self::Value, A::Error>
246            where
247                A: MapAccess<'de>,
248            {
249                let mut result = BTreeMap::new();
250                while let Some(key) = map.next_key::<String>()? {
251                    let value: RawGrantValue = map.next_value()?;
252                    if result.contains_key(&key) {
253                        return Err(de::Error::custom(format!(
254                            "duplicate audience key {key:?} in grant map"
255                        )));
256                    }
257                    result.insert(key, value);
258                }
259                Ok(RawAudienceGrants(result))
260            }
261        }
262
263        deserializer.deserialize_map(GrantsVisitor)
264    }
265}
266
267/// The parsed, validated grant map: "who can access this audience", keyed by audience name, one
268/// relation per axis (read/mint -- AbAC plan's `group_read_grants` / `group_mint_grants`, kept as
269/// one static map here since the DB store (`DbAudienceGrantsSource`) is checked as a separate
270/// source, not merged into this one).
271///
272/// A bare-array value is read-only shorthand: an omitted `"mint"` list is therefore always empty,
273/// never defaulted from `"read"` -- a read grant confers no mint authority, by construction.
274///
275/// `public` is stored the same way as any other audience -- via a `{"public": ["*"]}` entry here,
276/// or, in production, the seeded `('public', 'read', '*')` DB row (schema v9). It has no built-in
277/// grant on either axis; nothing here or in `AudienceReadPolicy::resolve` treats it specially.
278#[derive(Debug, Clone, Default)]
279pub struct AudienceGrants {
280    entries: BTreeMap<String, GrantEntry>,
281    /// Selectors on the `('*', read)` pair -- kept apart from `entries` so `readers()` never
282    /// yields `*` as if it were a real audience name.
283    all_audiences_read: Vec<String>,
284}
285
286impl AudienceGrants {
287    /// No grants at all -- every audience, `public` included, is unreadable and unmintable by
288    /// anyone non-admin. Used as the disabled-auth / no-explicit-policy default.
289    pub fn empty() -> Self {
290        Self::default()
291    }
292
293    /// Parses a grant-map JSON document directly -- the documented published format for a static
294    /// grant map, kept as a test-only entry point now that no production caller builds a policy
295    /// from raw JSON (`mint_key` builds one from [`Self::from_rows`] against a live query
296    /// instead).
297    ///
298    /// Validates both axes of the map, not just its JSON shape -- same reason every other knob in
299    /// this crate fails startup on a typo rather than shipping inert: every key must satisfy
300    /// [`is_valid_grant_audience`] (`{"group:everyone": [...]}`, the value operators are migrating
301    /// *from*, can never match a stamped audience once the charset excludes `:`), and every
302    /// selector on either axis must be `*`, `user:<non-empty>`, `group:<non-empty>`, or a
303    /// canonical `key:<uuid>` (an unprefixed or mis-prefixed selector matches no identity axis and
304    /// would otherwise be a silently-inert entry). A `key:` selector is read-axis only.
305    pub fn parse(raw: &str) -> Result<Self> {
306        let raw: RawAudienceGrants =
307            serde_json::from_str(raw).map_err(|e| anyhow!("invalid audience grant map: {e}"))?;
308        let mut entries = BTreeMap::new();
309        let mut all_audiences_read = Vec::new();
310        for (audience, value) in raw.0 {
311            if !is_valid_grant_audience(&audience) {
312                return Err(anyhow!(
313                    "invalid audience grant map: {audience:?} is not a valid audience name -- \
314                     must match [A-Za-z0-9_-]{{1,255}} or be '*'"
315                ));
316            }
317            let (read, mint) = match value {
318                RawGrantValue::Bare(read) => (read, vec![]),
319                RawGrantValue::Object(RawGrantObject { read, mint }) => (read, mint),
320            };
321            for selector in read.iter().chain(mint.iter()) {
322                if !valid_selector(selector) {
323                    return Err(anyhow!(
324                        "invalid audience grant map: selector {selector:?} for audience \
325                         {audience:?} must be '*', 'user:<id>', 'group:<id>', or 'key:<key_id>'"
326                    ));
327                }
328            }
329            if let Some(selector) = mint.iter().find(|s| s.starts_with("key:")) {
330                return Err(anyhow!(
331                    "invalid audience grant map: selector {selector:?} for audience \
332                     {audience:?} is not allowed on the mint axis -- API keys never mint"
333                ));
334            }
335            if audience == ALL_AUDIENCES {
336                if !mint.is_empty() {
337                    return Err(anyhow!(
338                        "invalid audience grant map: the '*' audience is allowed on the read axis \
339                         only"
340                    ));
341                }
342                all_audiences_read = read;
343                continue;
344            }
345            entries.insert(audience, GrantEntry { read, mint });
346        }
347        Ok(Self {
348            entries,
349            all_audiences_read,
350        })
351    }
352
353    /// Builds an `AudienceGrants` from `(audience, axis, selector)` triples -- the DB-store
354    /// analogue of [`Self::parse`]. Runs the *same* [`is_valid_grant_audience`]/[`valid_selector`]
355    /// checks `parse` runs, but skips a malformed row (reported in [`Parsed::skipped`]) instead of
356    /// failing the batch: rows only grant, so dropping one is fail-closed for that row and keeps
357    /// every other grant working.
358    pub fn from_rows(rows: impl IntoIterator<Item = (String, GrantAxis, String)>) -> Parsed<Self> {
359        let mut entries: BTreeMap<String, GrantEntry> = BTreeMap::new();
360        let mut all_audiences_read = Vec::new();
361        let mut skipped = Vec::new();
362        for (audience, axis, selector) in rows {
363            let axis_name = match axis {
364                GrantAxis::Read => "read",
365                GrantAxis::Mint => "mint",
366            };
367            let row = format!("audience_grants row ({audience:?}, {axis_name}, {selector})");
368            if !is_valid_grant_audience(&audience) {
369                skipped.push(format!("{row}: invalid audience name"));
370                continue;
371            }
372            if !valid_selector(&selector) {
373                skipped.push(format!("{row}: invalid selector"));
374                continue;
375            }
376            if axis == GrantAxis::Mint && selector.starts_with("key:") {
377                skipped.push(format!(
378                    "{row}: key selectors are not allowed on the mint axis"
379                ));
380                continue;
381            }
382            if audience == ALL_AUDIENCES {
383                match axis {
384                    GrantAxis::Read => all_audiences_read.push(selector),
385                    GrantAxis::Mint => {
386                        skipped.push(format!(
387                            "{row}: the '*' audience is allowed on the read axis only"
388                        ));
389                    }
390                }
391                continue;
392            }
393            let entry = entries.entry(audience).or_default();
394            match axis {
395                GrantAxis::Read => entry.read.push(selector),
396                GrantAxis::Mint => entry.mint.push(selector),
397            }
398        }
399        Parsed {
400            value: Self {
401                entries,
402                all_audiences_read,
403            },
404            skipped,
405        }
406    }
407
408    /// Unions each audience's `read`/`mint` selector lists across `self` and `other`: a selector
409    /// present in either map grants exactly the same access as being present in both. No dedup
410    /// -- `selector_matches` is called with `.any()`, so a selector present in both sources costs
411    /// one redundant comparison, never a wrong answer.
412    ///
413    /// A public utility for combining two `AudienceGrants` maps, exercised by this crate's own
414    /// integration tests (`rust/auth/tests/policy_tests.rs`); `resolve`/`resolve_audience` do
415    /// **not** call it -- they check the static map and the DB store snapshot as two separate
416    /// sources instead, specifically to avoid a per-request deep clone (see the comment in
417    /// [`AudienceReadPolicy::resolve`]).
418    pub fn merge(&self, other: &Self) -> Self {
419        let mut entries = self.entries.clone();
420        for (audience, other_entry) in &other.entries {
421            let entry = entries.entry(audience.clone()).or_default();
422            entry.read.extend(other_entry.read.iter().cloned());
423            entry.mint.extend(other_entry.mint.iter().cloned());
424        }
425        let mut all_audiences_read = self.all_audiences_read.clone();
426        all_audiences_read.extend(other.all_audiences_read.iter().cloned());
427        Self {
428            entries,
429            all_audiences_read,
430        }
431    }
432
433    fn readers(&self) -> impl Iterator<Item = (&String, &[String])> {
434        self.entries.iter().map(|(a, e)| (a, e.read.as_slice()))
435    }
436
437    fn mint_selectors(&self, audience: &str) -> &[String] {
438        self.entries
439            .get(audience)
440            .map(|e| e.mint.as_slice())
441            .unwrap_or(&[])
442    }
443}
444
445/// What a policy resolved a caller may read.
446///
447/// An enum, not a bare string list, so a policy's result can never be confused with any other
448/// string list on a security path.
449#[derive(Debug, Clone, PartialEq, Eq)]
450pub enum ReadableAudiences {
451    /// Exactly these audiences.
452    Listed(Arc<[String]>),
453    /// Every audience, including ones created later (a `*`-audience read grant). Still
454    /// row-filtered downstream: only rows that carry an audience are readable.
455    Every,
456}
457
458/// Resolves the set of audiences an authenticated caller may read.
459///
460/// `resolve` can **never** return "all" -- `ReadScope::All` is deliberately not a policy output.
461/// It is the marker only internal (non-request) callers pass, which is what keeps "who granted
462/// themselves `All`?" a greppable question with a small, auditable answer set. The most
463/// permissive result is [`ReadableAudiences::Every`], which is not `All`: it keeps the row-level
464/// filter and the call-level guard, and only widens the membership test to "carries an audience".
465///
466/// `async` and fallible because grants can be resolved from a store -- nested groups, plus
467/// group→audience grants -- which cannot live behind a sync, infallible signature.
468/// `AudienceReadPolicy` is fallible today whenever a [`DbAudienceGrantsSource`] is attached via
469/// `with_store` -- a cold-start store outage with no prior successful load returns `Err`, which
470/// `caller_context` (`flight_sql_service_impl.rs`) maps to `Status::unavailable`. Without a store
471/// attached it still cannot fail.
472///
473/// **Every caller must deny on `Err`.** An `Err` here means "the policy could not be evaluated" --
474/// never soften it into `ReadableAudiences::Listed(Arc::from([]))` (that would read as a legitimate,
475/// audited fail-closed decision) and never into `ReadScope::All` (a silent fail-open bypass).
476#[async_trait]
477pub trait ReadPolicy: Send + Sync + Debug {
478    /// Resolves `caller`'s readable-audience set, or `Err` if the policy could not be evaluated
479    /// (e.g. a backing store outage once a store-backed policy lands).
480    async fn resolve(&self, caller: &AuthContext) -> Result<ReadableAudiences>;
481}
482
483/// Resolves the audience a newly minted key may be stamped with.
484///
485/// `requested` is the caller-supplied audience (e.g. `"team-alpha"`); `None` means "no audience
486/// requested and none can be defaulted" -- under the opaque-label model there is no "myself"
487/// audience for a caller's identity to default to, so every implementation must return `Err` for
488/// `requested: None`, admin or not. Async and fallible for the same reason as `ReadPolicy` --
489/// wired by `mint_key` (`analytics-web-srv/src/ingestion_keys.rs`), gated by
490/// `MintGate`/`AuthenticatedUser` rather than `AdminUser`.
491#[async_trait]
492pub trait MintPolicy: Send + Sync + Debug {
493    /// Resolves the audience to stamp on a newly minted key, or `Err` if `requested` is outside
494    /// what `caller` may mint (including `requested: None` -- see the trait doc comment).
495    async fn resolve_audience(
496        &self,
497        caller: &AuthContext,
498        requested: Option<&str>,
499    ) -> Result<String>;
500}
501
502/// The shipped `ReadPolicy`: a lookup over an [`AudienceGrants`] map -- and, when a
503/// [`DbAudienceGrantsSource`] is attached via `with_store`, a second lookup over that store's
504/// snapshot -- with no identity derivation anywhere. Resolves the readable set:
505///
506/// ```text
507/// Every                                  if some selector in grants["*"].read matches the caller
508/// else
509/// { a : "*"            ∈ grants[a].read }
510///   ∪ { a : "user:<email>" ∈ grants[a].read }                  if email present
511///   ∪ { a : "group:<g>"    ∈ grants[a].read for some g ∈ caller.memberships }
512///   ∪ { a : "key:<id>"     ∈ grants[a].read }                  if caller is an analytics key
513///   ∪ { a : selector       ∈ store.readers(a) matches caller } if a store is attached
514///   ∪ caller.read_audiences                                    // per-key direct grant
515/// ```
516///
517/// There is **no self-audience rule** -- a caller is granted no audience merely for being named
518/// like one: the charset makes an email unrepresentable as an audience name, and keying on
519/// `subject` instead would let an admin mint themselves read access by naming a key after an
520/// audience.
521///
522/// `read_audiences` is folded in here but deliberately **excluded** from
523/// `AudienceMintPolicy`'s mintable set -- a service-account key's ability to *see* an audience
524/// must not imply it can *stamp new keys* with that audience (mint is integrity, read is
525/// confidentiality).
526#[derive(Debug, Clone, Default)]
527pub struct AudienceReadPolicy {
528    grants: AudienceGrants,
529    /// The DB-backed grant store, when this process has one configured -- checked alongside
530    /// `grants` on every `resolve` call, as a separate source rather than merged into it (see
531    /// `resolve`). `None` for every disabled-auth/test caller that has no DB pool to back one.
532    store: Option<Arc<DbAudienceGrantsSource>>,
533}
534
535impl AudienceReadPolicy {
536    /// Builds a policy with an explicit static grant map.
537    pub fn new(grants: AudienceGrants) -> Self {
538        Self {
539            grants,
540            store: None,
541        }
542    }
543
544    /// Attaches the DB-backed grant store. A builder method, not a constructor argument, so
545    /// `new`/`default` keep working unchanged for every caller with no DB pool to back one
546    /// (disabled-auth, tests).
547    pub fn with_store(mut self, store: Arc<DbAudienceGrantsSource>) -> Self {
548        self.store = Some(store);
549        self
550    }
551}
552
553#[async_trait]
554impl ReadPolicy for AudienceReadPolicy {
555    async fn resolve(&self, caller: &AuthContext) -> Result<ReadableAudiences> {
556        // `Err` only on a cold-start outage (no snapshot has ever loaded successfully) --
557        // propagated as-is, so `resolve` denies exactly as documented on its own trait.
558        let store_grants = match &self.store {
559            Some(store) => Some(store.current().await?),
560            None => None,
561        };
562        // A `*`-audience read grant short-circuits the per-audience loop.
563        if self
564            .grants
565            .all_audiences_read
566            .iter()
567            .any(|s| selector_matches(s, caller))
568            || store_grants.as_ref().is_some_and(|grants| {
569                grants
570                    .all_audiences_read
571                    .iter()
572                    .any(|s| selector_matches(s, caller))
573            })
574        {
575            return Ok(ReadableAudiences::Every);
576        }
577        let mut set = BTreeSet::new();
578        // The static map and the store snapshot are checked as two separate sources -- a
579        // selector present in either grants access -- rather than merged into one map, so
580        // neither side is deep-cloned on every request.
581        for (audience, read) in self.grants.readers() {
582            if read.iter().any(|s| selector_matches(s, caller)) {
583                set.insert(audience.clone());
584            }
585        }
586        if let Some(grants) = &store_grants {
587            for (audience, read) in grants.readers() {
588                if read.iter().any(|s| selector_matches(s, caller)) {
589                    set.insert(audience.clone());
590                }
591            }
592        }
593        for audience in &caller.read_audiences {
594            set.insert(audience.clone());
595        }
596        let audiences: Arc<[String]> = set.into_iter().collect::<Vec<_>>().into();
597        Ok(ReadableAudiences::Listed(audiences))
598    }
599}
600
601/// The shipped `MintPolicy`. Every caller, admin included, may mint only an audience in their
602/// **mint** set -- `grants[a].mint`, never `grants[a].read` (a read grant confers no mint
603/// authority, unchanged from `AudienceReadPolicy`'s split); being able to *read* `public` via its
604/// seeded read grant does not imply being able to *mint into* it -- that requires its own grant
605/// naming `public` in a `"mint"` list (in production, the seeded `('public', 'mint', '*')` row,
606/// schema v9).
607///
608/// A route's authorization is the authority that route's own effect requires: minting yields
609/// write access to an audience, so it requires a grant on that audience -- `is_admin` confers
610/// none. `mint_key` (`analytics-web-srv/src/ingestion_keys.rs`) delegates authorization to this
611/// policy for every caller, with no admin-specific arm of its own accord (its own gate,
612/// `MintGate`, only enforces the self-service knob against non-admins).
613#[derive(Debug, Clone, Default)]
614pub struct AudienceMintPolicy {
615    grants: AudienceGrants,
616    /// The DB-backed grant store. Built for symmetry with [`AudienceReadPolicy::with_store`] and
617    /// unit-tested, but nothing wires it in production yet: no production code constructs a `dyn
618    /// MintPolicy` today -- see [`with_store`](Self::with_store).
619    store: Option<Arc<DbAudienceGrantsSource>>,
620}
621
622impl AudienceMintPolicy {
623    /// Builds a policy with an explicit static grant map.
624    pub fn new(grants: AudienceGrants) -> Self {
625        Self {
626            grants,
627            store: None,
628        }
629    }
630
631    /// Attaches the DB-backed grant store. Built alongside [`AudienceReadPolicy::with_store`] for
632    /// symmetry -- unlike the read side, no production call site attaches a store through this
633    /// method: `mint_key` constructs its `AudienceMintPolicy` via `new`, so mint grants stay
634    /// resolved by a fresh, uncached point query against `audience_grants`, never a
635    /// `DbAudienceGrantsSource` snapshot.
636    pub fn with_store(mut self, store: Arc<DbAudienceGrantsSource>) -> Self {
637        self.store = Some(store);
638        self
639    }
640}
641
642#[async_trait]
643impl MintPolicy for AudienceMintPolicy {
644    async fn resolve_audience(
645        &self,
646        caller: &AuthContext,
647        requested: Option<&str>,
648    ) -> Result<String> {
649        // Holds by construction rather than by which services happen to accept analytics keys.
650        if caller.analytics_key_id.is_some() {
651            return Err(anyhow!("analytics API keys cannot mint"));
652        }
653        let Some(aud) = requested else {
654            return Err(anyhow!("no audience requested and none can be defaulted"));
655        };
656        if !is_valid_audience(aud) {
657            return Err(anyhow!(
658                "malformed audience {aud:?}: must match [A-Za-z0-9_-]{{1,255}}"
659            ));
660        }
661        // The static map and the store snapshot are checked as two separate sources -- a
662        // selector present in either grants access -- rather than merged into one map, so
663        // neither side is deep-cloned on every request.
664        let store_grants = match &self.store {
665            Some(store) => Some(store.current().await?),
666            None => None,
667        };
668        let granted = self
669            .grants
670            .mint_selectors(aud)
671            .iter()
672            .any(|s| selector_matches(s, caller))
673            || store_grants.as_ref().is_some_and(|grants| {
674                grants
675                    .mint_selectors(aud)
676                    .iter()
677                    .any(|s| selector_matches(s, caller))
678            });
679        if granted {
680            Ok(aud.to_string())
681        } else {
682            Err(anyhow!(
683                "audience {aud:?} is not in the caller's mintable set"
684            ))
685        }
686    }
687}