Skip to main content

micromegas_auth/
types.rs

1use crate::groups::ADMINS_GROUP;
2use anyhow::Result;
3use chrono::{DateTime, Utc};
4use std::sync::Arc;
5
6/// A DB-backed auth provider (e.g. `DbApiKeyAuthProvider`) could not reach its
7/// key store — distinguishes a store *outage* from a rejected credential all
8/// the way out to the HTTP/gRPC response.
9///
10/// Wraps the underlying `anyhow::Error` rather than replacing it: callers that
11/// only need to log or propagate the error keep using it as an `anyhow::Error`
12/// (via `?`/`From`), while `MultiAuthProvider`, `auth_middleware`, and the gRPC
13/// `AuthService` downcast (`anyhow::Error::downcast_ref`) to detect this specific
14/// kind and map it to a retryable status (503 / `Status::unavailable`) instead of
15/// the blanket "invalid credential" response every other error gets.
16///
17/// Per `rust/CLAUDE.md`'s anyhow-vs-thiserror rule, the retryable/terminal
18/// distinction *is* modeled as an explicit type rather than an ad-hoc string —
19/// that's the part of the rule this satisfies. What it doesn't satisfy: callers
20/// still reach that type via `downcast_ref` instead of matching on it directly,
21/// because `AuthProvider::validate_request` returns `anyhow::Result` and this
22/// plan chose not to change that trait's public return type. Treat this as a
23/// deliberate, scoped exception rather than a full application of the rule.
24#[derive(thiserror::Error, Debug)]
25#[error("auth provider unavailable: {0}")]
26pub struct ProviderUnavailable(#[source] pub anyhow::Error);
27
28/// Authentication type
29#[derive(Debug, Clone, PartialEq, Eq)]
30pub enum AuthType {
31    /// API key authentication
32    ApiKey,
33    /// OIDC authentication
34    Oidc,
35}
36
37/// Authentication context containing user identity and metadata
38#[derive(Debug, Clone)]
39pub struct AuthContext {
40    /// Unique subject identifier (e.g., user ID, service account ID)
41    pub subject: String,
42    /// Email address (if available)
43    pub email: Option<String>,
44    /// Issuer (for OIDC) or "api_key" for API key auth
45    pub issuer: String,
46    /// Audience that was matched during token validation
47    /// - For OIDC access tokens: API audience (e.g., "<https://api.example.com>")
48    /// - For OIDC ID tokens: client ID
49    /// - For API key auth: None
50    pub audience: Option<String>,
51    /// Token expiration time (if applicable)
52    pub expires_at: Option<DateTime<Utc>>,
53    /// Authentication type
54    pub auth_type: AuthType,
55    /// Whether this authentication allows user delegation (acting on behalf of others)
56    /// - OIDC user tokens: false (user cannot impersonate others)
57    /// - Analytics API keys/service accounts: true (can act on behalf of users)
58    /// - Ingestion API keys: false — a write credential is not a delegating service account, and
59    ///   it can never reach the gRPC path this flag governs anyway (`ingestion_api_keys` never
60    ///   crosses `flight_sql_service_impl.rs`)
61    pub allow_delegation: bool,
62    /// The write audience an ingestion key is immutably bound to. `Some(..)` for every ingestion
63    /// API key (the `ingestion_api_keys.audience` column is `NOT NULL` as of migration v6);
64    /// `None` for every other principal kind. Write-side only; never consulted by `ReadPolicy`.
65    pub bound_audience: Option<String>,
66    /// The set of audiences an analytics service-account key is granted read access to. Empty for
67    /// every principal today — no analytics key provider populates it yet. Read-side only; folded
68    /// into `AudienceReadPolicy::resolve`'s union but never into `AudienceMintPolicy`'s mintable
69    /// set (a read grant confers no mint authority).
70    pub read_audiences: Vec<String>,
71    /// The `analytics_api_keys.key_id` this request authenticated with. `Some` only for an
72    /// analytics API key; `None` for ingestion keys, OIDC, static keys, and the disabled-auth and
73    /// maintenance contexts. `subject` carries the key's name, which is neither unique nor
74    /// stable, so `key:<id>` selectors and the mint guard rest on this instead.
75    pub analytics_key_id: Option<uuid::Uuid>,
76    /// The caller's resolved, transitive local-group membership -- filled by
77    /// [`crate::membership::MembershipProvider`] from a [`crate::groups::GroupGraph`] snapshot,
78    /// **after** the inner provider authenticates the request. Empty until a
79    /// `MembershipProvider` fills it (disabled-auth and maintenance contexts set this to
80    /// `Arc::from([ADMINS_GROUP.to_string()])` directly instead). `AudienceReadPolicy`/
81    /// `AudienceMintPolicy` match each entry against `group:<name>` grant-map *selectors* via
82    /// [`crate::policy::caller_selectors`]/`selector_matches`.
83    pub memberships: Arc<[String]>,
84}
85
86impl AuthContext {
87    /// `true` iff `memberships` contains [`ADMINS_GROUP`] -- a method, not a field, so no
88    /// construction site can set it inconsistently with `memberships`.
89    pub fn is_admin(&self) -> bool {
90        self.memberships.iter().any(|g| g == ADMINS_GROUP)
91    }
92}
93
94/// Trait for extracting authentication-relevant data from requests
95pub trait RequestParts: Send + Sync {
96    /// Extract Authorization header as string
97    fn authorization_header(&self) -> Option<&str>;
98
99    /// Extract Bearer token from Authorization header
100    fn bearer_token(&self) -> Option<&str> {
101        self.authorization_header()
102            .and_then(|h| h.strip_prefix("Bearer "))
103    }
104
105    /// Get custom header value by name
106    fn get_header(&self, name: &str) -> Option<&str>;
107
108    /// Get request method (if applicable)
109    fn method(&self) -> Option<&str>;
110
111    /// Get request URI (if applicable)
112    fn uri(&self) -> Option<&str>;
113
114    /// The resolved client IP, `None` when nothing resolves (see
115    /// [`crate::client_ip::resolve_client_ip`]). This is what
116    /// [`crate::ip_allowlist::IpAllowlist::allows`] checks a restricted key's request against;
117    /// `None` never satisfies a non-empty allowlist.
118    fn client_ip(&self) -> Option<std::net::IpAddr>;
119}
120
121/// HTTP request validation input
122pub struct HttpRequestParts {
123    /// HTTP headers
124    pub headers: http::HeaderMap,
125    /// HTTP method
126    pub method: http::Method,
127    /// Request URI
128    pub uri: http::Uri,
129    /// The resolved client IP, computed once by the caller (see
130    /// [`crate::client_ip::resolve_client_ip`]) before this struct is built.
131    pub client_ip: Option<std::net::IpAddr>,
132}
133
134impl RequestParts for HttpRequestParts {
135    fn authorization_header(&self) -> Option<&str> {
136        self.headers
137            .get(http::header::AUTHORIZATION)
138            .and_then(|h| h.to_str().ok())
139    }
140
141    fn get_header(&self, name: &str) -> Option<&str> {
142        self.headers.get(name).and_then(|h| h.to_str().ok())
143    }
144
145    fn method(&self) -> Option<&str> {
146        Some(self.method.as_str())
147    }
148
149    fn uri(&self) -> Option<&str> {
150        Some(self.uri.path())
151    }
152
153    fn client_ip(&self) -> Option<std::net::IpAddr> {
154        self.client_ip
155    }
156}
157
158/// gRPC request validation input (tonic metadata)
159pub struct GrpcRequestParts {
160    /// gRPC metadata map
161    pub metadata: tonic::metadata::MetadataMap,
162    /// The resolved client IP, computed once by the caller (see
163    /// [`crate::client_ip::resolve_client_ip`]) before this struct is built.
164    pub client_ip: Option<std::net::IpAddr>,
165}
166
167impl RequestParts for GrpcRequestParts {
168    fn authorization_header(&self) -> Option<&str> {
169        self.metadata
170            .get("authorization")
171            .and_then(|h| h.to_str().ok())
172    }
173
174    fn get_header(&self, name: &str) -> Option<&str> {
175        self.metadata.get(name).and_then(|h| h.to_str().ok())
176    }
177
178    fn method(&self) -> Option<&str> {
179        None
180    }
181
182    fn uri(&self) -> Option<&str> {
183        None
184    }
185
186    fn client_ip(&self) -> Option<std::net::IpAddr> {
187        self.client_ip
188    }
189}
190
191/// Trait for authentication providers
192#[async_trait::async_trait]
193pub trait AuthProvider: Send + Sync {
194    /// Short label naming this provider in aggregated rejection reasons.
195    fn name(&self) -> &'static str;
196
197    /// Validate a request and return authentication context
198    async fn validate_request(&self, parts: &dyn RequestParts) -> Result<AuthContext>;
199}