micromegas_analytics/lakehouse/read_scope.rs
1//! The analytics-side half of the authorization seam.
2//!
3//! `ReadScope` is the query planner's authorization input -- what a `ReadPolicy`
4//! (`micromegas-auth`) resolves down to. `micromegas-analytics` does not depend on
5//! `micromegas-auth`: that edge would pull in the whole OIDC/JWT dependency tree behind one enum,
6//! so `ReadScope` carries resolved audiences only (or the "every audience" marker) -- no group vocabulary, no policy trait, nothing
7//! that requires a store. The `rust/public` bridge is the only place a `ReadableAudiences` (from
8//! `micromegas-auth`) becomes a `ReadScope`.
9//!
10//! Enforcement has two layers. [`crate::lakehouse::ownership_rewrite::OwnershipRewrite`] (the row-level filter) reads
11//! `ReadScope` out of [`crate::lakehouse::read_scope::CallerContext`] inside `query.rs::make_session_context` and injects an
12//! audience predicate into every `MaterializedView`-backed scan. The call-level guard is the UDTF/UDF guards
13//! ([`crate::lakehouse::audience_guard::AudienceGuard`]) for the span/metadata functions the row-level filter structurally
14//! cannot reach, plus `CallerContext.is_admin`'s mutating-function registration
15//! gate. `view_instance(...)` is also guarded by the call-level guard, closing a cost/availability residual for
16//! the six view sets carrying a physical `audience` column, where the row-level filter already filters
17//! `view_instance` scans row-by-row, same as the named-table form; for the other five view sets,
18//! reachable only through a guarded `view_instance(...)`, the call-level guard is the sole enforcement
19//! -- the row-level filter injects no predicate there at all.
20
21use std::sync::Arc;
22
23/// The authorization scope a query planner may read under: unrestricted (`All`, internal only),
24/// a listed set of audiences, or every audience (`EveryAudience`).
25///
26/// `All` is deliberately not something a `ReadPolicy` can produce (see
27/// `micromegas_auth::policy::ReadPolicy`'s doc comment) -- it is the marker internal
28/// (non-request) callers pass, via [`CallerContext::internal`] / [`CallerContext::maintenance`].
29#[derive(Debug, Clone, PartialEq, Eq)]
30pub enum ReadScope {
31 /// No audience restriction. Only ever constructed by an internal/maintenance caller, or by
32 /// the `rust/public` resolver when no `AuthContext` extension is present at all (no auth
33 /// provider configured, e.g. `--disable-auth`) -- never as the output of resolving a
34 /// `ReadPolicy` against a real caller.
35 All,
36 /// Restricted to the given set of audiences -- opaque labels (e.g. `"public"`,
37 /// `"team-alpha"`), as resolved by a `ReadPolicy`.
38 Audiences(Arc<[String]>),
39 /// Any row carrying an audience. A request scope like `Audiences`, never `All`: the same
40 /// row-level filter and call-level guard apply, and only the membership test changes from
41 /// "audience in list" to "has an audience". Covers audiences created after the grant.
42 EveryAudience,
43}
44
45/// Bundles the orthogonal authorization inputs `make_session_context` and friends need --
46/// audience scope (`read_scope`) and the `is_admin` mutating-function-registration capability --
47/// into one struct instead of adjacent, transposable positional parameters.
48///
49/// Required (not `Option`/defaulted) at every call site by design: a defaulting parameter would
50/// let a future call site inherit `ReadScope::All` by omission, which is exactly the failure this
51/// seam exists to prevent. Every call site must state its scope explicitly, via one of the three
52/// constructors below or a resolved value from a `ReadPolicy`.
53#[derive(Debug, Clone)]
54pub struct CallerContext {
55 /// The audience scope to plan queries under. Consumed by
56 /// [`super::ownership_rewrite::OwnershipRewrite`] inside `query.rs::make_session_context`.
57 pub read_scope: ReadScope,
58 /// Whether the caller may use the five mutating lakehouse UDTFs/UDFs.
59 pub is_admin: bool,
60 /// Per-service data-isolation deployment config (the `public_view_sets` setting, env
61 /// fallback `MICROMEGAS_PUBLIC_VIEW_SETS`) -- resolved per request by the service and bundled
62 /// here rather than as a new `make_session_context` parameter: it rides along with
63 /// `read_scope` at every real call site anyway.
64 pub isolation_config: Arc<IsolationConfig>,
65 /// The caller's identity, as recorded in `deny_queries`'s `created_by` column. `None` on
66 /// internal/maintenance paths -- such a caller cannot call `deny_queries`, which requires
67 /// `Some`. One string, not a struct: `created_by` is the only consumer, so a richer identity
68 /// type would be written at every construction site and read nowhere.
69 pub identity: Option<String>,
70 /// The grant selectors this caller matches -- `"*"`, `"user:<email>"` when an email is present,
71 /// `"key:<id>"` for an analytics API key, and one `"group:<g>"` per claimed group -- precomputed by `rust/public` from the
72 /// `AuthContext` (`micromegas_auth::policy::caller_selectors`), so `micromegas-analytics` never
73 /// needs the auth crate. Empty for internal and maintenance callers and for a request with no
74 /// `AuthContext` at all (`--disable-auth`). Consumed by `list_audience_grants()`
75 /// (`list_audience_grants_table_function.rs`); admins do not need it -- they see every row.
76 pub grant_selectors: Arc<[String]>,
77}
78
79impl CallerContext {
80 /// For background/materialization callers that are not serving a user request at all
81 /// (`is_admin: false`, `ReadScope::All`). Distinct from [`Self::maintenance`] only in
82 /// `is_admin` -- use this for internal call sites that must not register the mutating
83 /// UDTFs/UDFs.
84 pub fn internal() -> Self {
85 Self {
86 read_scope: ReadScope::All,
87 is_admin: false,
88 isolation_config: Arc::new(IsolationConfig::default()),
89 identity: None,
90 grant_selectors: Arc::from([]),
91 }
92 }
93
94 /// For background/materialization callers performing maintenance work (`is_admin: true`,
95 /// `ReadScope::All`) -- never a user session.
96 pub fn maintenance() -> Self {
97 Self {
98 read_scope: ReadScope::All,
99 is_admin: true,
100 isolation_config: Arc::new(IsolationConfig::default()),
101 identity: None,
102 grant_selectors: Arc::from([]),
103 }
104 }
105}
106
107/// Deployment config for the data-isolation seam: [`super::ownership_rewrite::OwnershipRewrite`]
108/// (the row-level filter). Resolved once at server startup from environment variables -- see
109/// [`IsolationConfig::from_env`].
110///
111/// `#[derive(Default)]`: `public_view_sets` is the only field, and its empty-by-default matches
112/// [`Self::from_env`]'s own default.
113#[derive(Debug, Clone, Default)]
114pub struct IsolationConfig {
115 /// View-set names `OwnershipRewrite` skips entirely -- no predicate injected at all,
116 /// regardless of scope. Off (empty) by default, fail-closed for this
117 /// operator-responsibility allowlist. Built from the `public_view_sets` setting, or parsed from the `MICROMEGAS_PUBLIC_VIEW_SETS` env fallback.
118 pub public_view_sets: Vec<String>,
119}
120
121/// Comma-separated list parser for `MICROMEGAS_PUBLIC_VIEW_SETS`.
122///
123/// Deliberately a comma-separated list (rejecting `[`, `]`, `"`) rather than the
124/// `MICROMEGAS_API_KEYS` JSON-array shape -- duplicated here rather than depending on
125/// `micromegas-auth` for it, since `micromegas-analytics` does not depend on that crate (the same
126/// crate-boundary reasoning `read_scope.rs`'s own module doc comment gives for keeping
127/// `ReadScope` here).
128fn parse_comma_separated_list(var: &str) -> anyhow::Result<Vec<String>> {
129 let raw = match std::env::var(var) {
130 Ok(raw) => raw,
131 Err(_) => return Ok(vec![]),
132 };
133 if raw.trim().is_empty() {
134 return Ok(vec![]);
135 }
136 let mut values = Vec::new();
137 for entry in raw.split(',') {
138 let trimmed = entry.trim();
139 if trimmed.is_empty() {
140 anyhow::bail!("{var}: empty entry (entry {entry:?} in {raw:?})");
141 }
142 if trimmed.contains(['[', ']', '"']) {
143 anyhow::bail!(
144 "{var}: entry {trimmed:?} contains '[', ']', or '\"' -- this variable is \
145 comma-separated, not a JSON array like MICROMEGAS_API_KEYS"
146 );
147 }
148 values.push(trimmed.to_string());
149 }
150 Ok(values)
151}
152
153impl IsolationConfig {
154 /// Resolves the surviving knob from the environment. `MICROMEGAS_PUBLIC_VIEW_SETS` unset ⇒
155 /// no public view sets; a malformed entry is `Err`, not silently ignored -- a startup `?`
156 /// turns a typo into a fail-fast instead of a silently-inert knob.
157 pub fn from_env() -> anyhow::Result<Self> {
158 Ok(Self {
159 public_view_sets: parse_comma_separated_list("MICROMEGAS_PUBLIC_VIEW_SETS")?,
160 })
161 }
162}