Skip to main content

reddb_server/auth/
store.rs

1//! AuthStore -- manages users, sessions, and API keys in memory.
2//!
3//! Password hashing delegates to the existing Argon2id implementation in
4//! `crate::storage::encryption::argon2id`.  Token generation uses the
5//! OS CSPRNG (`crate::crypto::os_random`) plus SHA-256.
6
7use std::collections::HashMap;
8use std::sync::atomic::{AtomicBool, Ordering};
9use std::sync::{Arc, RwLock};
10
11use crate::crypto::os_random;
12use crate::crypto::sha256::sha256;
13use crate::storage::encryption::argon2id::{derive_key, Argon2Params};
14use crate::storage::engine::pager::Pager;
15
16use super::column_policy_gate::{ColumnAccessRequest, ColumnPolicyGate, ColumnPolicyOutcome};
17use super::policies::{self as iam_policies, EvalContext, Policy, ResourceRef, SimulationOutcome};
18use super::privileges::{
19    check_grant, Action, AuthzContext, AuthzError, Grant, GrantPrincipal, GrantsView,
20    PermissionCache, Resource, UserAttributes,
21};
22use super::vault::{KeyPair, Vault, VaultState};
23use super::{now_ms, ApiKey, AuthConfig, AuthError, Role, Session, User, UserId};
24
25// ---------------------------------------------------------------------------
26// PrincipalRef + SimCtx — IAM policy attachments
27// ---------------------------------------------------------------------------
28
29/// Principal targeted by `attach_policy` / `detach_policy`.
30#[derive(Debug, Clone, PartialEq, Eq, Hash)]
31pub enum PrincipalRef {
32    User(UserId),
33    Group(String),
34}
35
36/// Reserved IAM group that every principal belongs to. Used by the
37/// GRANT-to-PUBLIC compatibility layer.
38pub const PUBLIC_IAM_GROUP: &str = "__public__";
39
40/// Optional context overrides for `simulate` — anything not set falls back
41/// to a default value when the kernel evaluates the request.
42#[derive(Debug, Clone, Default)]
43pub struct SimCtx {
44    pub current_tenant: Option<String>,
45    pub peer_ip: Option<std::net::IpAddr>,
46    pub mfa_present: bool,
47    pub now_ms: Option<u128>,
48}
49
50// ---------------------------------------------------------------------------
51// BootstrapResult
52// ---------------------------------------------------------------------------
53
54/// Result of a successful bootstrap operation.
55///
56/// The `certificate` is the hex-encoded string the admin must save --
57/// it is the ONLY way to unseal the vault after a restart.
58#[derive(Debug)]
59pub struct BootstrapResult {
60    pub user: User,
61    pub api_key: ApiKey,
62    /// Certificate hex string.  `None` when vault is not configured.
63    pub certificate: Option<String>,
64}
65
66// ---------------------------------------------------------------------------
67// AuthStore
68// ---------------------------------------------------------------------------
69
70/// Central in-process authority for auth state.
71///
72/// All mutations are guarded by `RwLock`s so the store is `Send + Sync`.
73pub struct AuthStore {
74    /// `(tenant_id, username) -> User`. Tenant scoping is built into the
75    /// key so `alice@acme` and `alice@globex` are distinct identities.
76    users: RwLock<HashMap<UserId, User>>,
77    sessions: RwLock<HashMap<String, Session>>,
78    /// key-string -> (owner UserId, role)
79    api_key_index: RwLock<HashMap<String, (UserId, Role)>>,
80    /// Once true, bootstrap() is permanently sealed.
81    bootstrapped: AtomicBool,
82    config: AuthConfig,
83    /// Optional encrypted vault for persisting auth state to pager pages.
84    vault: RwLock<Option<Vault>>,
85    /// Reference to the pager for vault page I/O.
86    pager: Option<Arc<Pager>>,
87    /// Certificate-based keypair for token signing and vault seal.
88    /// Populated after bootstrap or after restoring from a sealed vault.
89    keypair: RwLock<Option<KeyPair>>,
90    /// Encrypted key-value store for arbitrary secrets.
91    /// Persisted to vault alongside users/api_keys.
92    vault_kv: RwLock<HashMap<String, String>>,
93    /// Per-user GRANT rows. Persisted via `vault_kv` under the
94    /// `red.acl.grants.<tenant>/<user>` key prefix so existing snapshot
95    /// logic keeps working without modification. See `privileges` module
96    /// for the resolution algorithm.
97    grants: RwLock<HashMap<UserId, Vec<Grant>>>,
98    /// PUBLIC grants — apply to every authenticated principal.
99    public_grants: RwLock<Vec<Grant>>,
100    /// PG-style account attributes (`VALID UNTIL`, `CONNECTION LIMIT`,
101    /// `search_path`). Keyed by `UserId`. Persisted under
102    /// `red.acl.attrs.<tenant>/<user>`.
103    user_attributes: RwLock<HashMap<UserId, UserAttributes>>,
104    /// Live session count per user — used by `CONNECTION LIMIT`
105    /// enforcement on login. Bumped at authenticate, decremented at
106    /// session revoke / expiry.
107    session_count_by_user: RwLock<HashMap<UserId, u32>>,
108    /// Pre-resolved (resource, action) cache built per-user so the
109    /// hot path skips a linear scan of the user's grants on every
110    /// statement. Invalidated on GRANT / REVOKE / ALTER USER.
111    permission_cache: RwLock<HashMap<UserId, PermissionCache>>,
112    /// IAM-style policies, keyed by id. Persisted under
113    /// `red.iam.policies`. The kernel in `super::policies` owns the
114    /// Policy type — this map just deduplicates and shares.
115    policies: RwLock<HashMap<String, Arc<Policy>>>,
116    /// Per-user policy attachments — ordered list of policy ids.
117    /// Persisted under `red.iam.attachments.users`.
118    user_attachments: RwLock<HashMap<UserId, Vec<String>>>,
119    /// Per-group policy attachments. Users join groups through
120    /// `UserAttributes::groups`; effective policies resolve group
121    /// attachments before user-direct attachments.
122    group_attachments: RwLock<HashMap<String, Vec<String>>>,
123    /// Cached effective `Vec<Arc<Policy>>` per user. Invalidated on
124    /// any policy mutation that affects the user's attachments.
125    iam_effective_cache: RwLock<HashMap<UserId, Vec<Arc<Policy>>>>,
126    /// Once any IAM policy is installed, authorization switches to the
127    /// IAM evaluator and stays deny-by-default even if policies are
128    /// later deleted. Persisted under `red.iam.enabled`.
129    iam_authorization_enabled: AtomicBool,
130    /// `(tenant, role) → HashSet<CollectionId>` cache used by the AI
131    /// pipeline (issue #119). Distinct from `permission_cache`, which
132    /// is keyed by `UserId` and answers `(resource, action)` lookups —
133    /// this cache answers the inverse "what collections is this scope
134    /// allowed to read?" query that `AuthorizedSearch` uses to
135    /// pre-filter SEARCH SIMILAR / SEARCH CONTEXT candidates before any
136    /// similarity score is computed. Entries TTL out at 60s and are
137    /// invalidated explicitly on GRANT/REVOKE/CREATE POLICY/DROP
138    /// POLICY/DROP COLLECTION.
139    visible_collections_cache: super::scope_cache::AuthCache,
140}
141
142// Use fast-but-safe Argon2id params for auth hashing (smaller than the
143// default 64 MB so that user-management RPCs respond quickly).
144fn auth_argon2_params() -> Argon2Params {
145    Argon2Params {
146        m_cost: 4 * 1024, // 4 MB
147        t_cost: 3,
148        p: 1,
149        tag_len: 32,
150    }
151}
152
153impl AuthStore {
154    // -----------------------------------------------------------------
155    // Construction
156    // -----------------------------------------------------------------
157
158    pub fn new(config: AuthConfig) -> Self {
159        Self {
160            users: RwLock::new(HashMap::new()),
161            sessions: RwLock::new(HashMap::new()),
162            api_key_index: RwLock::new(HashMap::new()),
163            bootstrapped: AtomicBool::new(false),
164            config,
165            vault: RwLock::new(None),
166            pager: None,
167            keypair: RwLock::new(None),
168            vault_kv: RwLock::new(HashMap::new()),
169            grants: RwLock::new(HashMap::new()),
170            public_grants: RwLock::new(Vec::new()),
171            user_attributes: RwLock::new(HashMap::new()),
172            session_count_by_user: RwLock::new(HashMap::new()),
173            permission_cache: RwLock::new(HashMap::new()),
174            policies: RwLock::new(HashMap::new()),
175            user_attachments: RwLock::new(HashMap::new()),
176            group_attachments: RwLock::new(HashMap::new()),
177            iam_effective_cache: RwLock::new(HashMap::new()),
178            iam_authorization_enabled: AtomicBool::new(false),
179            visible_collections_cache: super::scope_cache::AuthCache::new(
180                super::scope_cache::DEFAULT_TTL,
181            ),
182        }
183    }
184
185    /// Create an `AuthStore` backed by encrypted vault pages inside the
186    /// main `.rdb` database file.
187    ///
188    /// If vault pages already exist, their contents are loaded and
189    /// restored into the in-memory store.  All subsequent mutations are
190    /// automatically persisted to the vault pages via the pager.
191    pub fn with_vault(
192        config: AuthConfig,
193        pager: Arc<Pager>,
194        passphrase: Option<&str>,
195    ) -> Result<Self, AuthError> {
196        let vault = Vault::open(&pager, passphrase)?;
197        let mut store = Self::new(config);
198
199        // Restore persisted state if vault pages exist.
200        if let Some(state) = vault.load(&pager)? {
201            store.restore_from_vault(state);
202        }
203
204        *store.vault.write().unwrap_or_else(|e| e.into_inner()) = Some(vault);
205        store.pager = Some(pager);
206        Ok(store)
207    }
208
209    pub fn config(&self) -> &AuthConfig {
210        &self.config
211    }
212
213    pub fn is_enabled(&self) -> bool {
214        self.config.enabled
215    }
216
217    /// Returns true when no users exist yet and bootstrap hasn't been sealed.
218    pub fn needs_bootstrap(&self) -> bool {
219        !self.bootstrapped.load(Ordering::Acquire)
220            && self.users.read().map(|u| u.is_empty()).unwrap_or(true)
221    }
222
223    /// Internal: read-locked lookup by `UserId`.
224    fn get_user_cloned(&self, id: &UserId) -> Option<User> {
225        self.users.read().ok().and_then(|m| m.get(id).cloned())
226    }
227
228    /// Whether bootstrap has already been performed (sealed).
229    pub fn is_bootstrapped(&self) -> bool {
230        self.bootstrapped.load(Ordering::Acquire)
231    }
232
233    /// Bootstrap the first admin user. One-shot, irreversible.
234    ///
235    /// Uses an atomic compare-exchange to guarantee that even under
236    /// concurrent calls, only the first one succeeds. Once sealed,
237    /// all subsequent calls fail immediately -- there is no undo.
238    ///
239    /// When a vault/pager is configured, a certificate-based keypair is
240    /// generated and the vault is re-encrypted with the certificate-derived
241    /// key.  The certificate hex string is returned in `BootstrapResult`
242    /// so the admin can save it.
243    pub fn bootstrap(&self, username: &str, password: &str) -> Result<BootstrapResult, AuthError> {
244        // Atomic seal: only the first caller wins.
245        if self
246            .bootstrapped
247            .compare_exchange(false, true, Ordering::AcqRel, Ordering::Acquire)
248            .is_err()
249        {
250            return Err(AuthError::Forbidden(
251                "bootstrap already completed — sealed permanently".to_string(),
252            ));
253        }
254
255        // Double-check users are actually empty (belt and suspenders).
256        {
257            let users = self.users.read().map_err(lock_err)?;
258            if !users.is_empty() {
259                return Err(AuthError::Forbidden(
260                    "bootstrap already completed — users exist".to_string(),
261                ));
262            }
263        }
264
265        let user = self.create_user(username, password, Role::Admin)?;
266        let key = self.create_api_key(username, "bootstrap", Role::Admin)?;
267
268        // Generate a certificate-based keypair and re-seal the vault.
269        let certificate = if let Some(ref pager) = self.pager {
270            let kp = KeyPair::generate();
271            let cert_hex = kp.certificate_hex();
272
273            // Re-create the vault using the certificate-derived key.
274            let new_vault = Vault::with_certificate_bytes(pager, &kp.certificate)
275                .map_err(|e| AuthError::Internal(format!("vault re-seal failed: {e}")))?;
276
277            // Store the keypair so token signing works immediately.
278            if let Ok(mut kp_guard) = self.keypair.write() {
279                *kp_guard = Some(kp);
280            }
281
282            // Replace the vault and persist with the master secret included.
283            if let Ok(mut vault_guard) = self.vault.write() {
284                *vault_guard = Some(new_vault);
285            }
286            // Generate the AES-256 secret key for Value::Secret encryption.
287            self.ensure_vault_secret_key();
288            self.persist_to_vault();
289
290            Some(cert_hex)
291        } else {
292            None
293        };
294
295        Ok(BootstrapResult {
296            user,
297            api_key: key,
298            certificate,
299        })
300    }
301
302    /// Auto-bootstrap from environment variables if no users exist.
303    ///
304    /// Checks `REDDB_USERNAME` and `REDDB_PASSWORD`. If both are set and
305    /// the user store is empty, creates the first admin user automatically.
306    /// This mirrors the Docker pattern (`MYSQL_ROOT_PASSWORD`, etc.).
307    ///
308    /// Returns `Some(BootstrapResult)` if bootstrapped, `None` if skipped.
309    pub fn bootstrap_from_env(&self) -> Option<BootstrapResult> {
310        if !self.needs_bootstrap() {
311            return None;
312        }
313
314        let username = std::env::var("REDDB_USERNAME").ok()?;
315        let password = std::env::var("REDDB_PASSWORD").ok()?;
316
317        if username.is_empty() || password.is_empty() {
318            return None;
319        }
320
321        match self.bootstrap(&username, &password) {
322            Ok(result) => {
323                // F-04: `username` is REDDB_USERNAME — operator-supplied
324                // (env), but still routed through the LogField escaper
325                // because env strings cross trust boundaries in some
326                // deployment models (k8s downward API, Vault sidecar,
327                // external secret operator). See ADR 0010.
328                tracing::info!(
329                    username = %reddb_wire::audit_safe_log_field(&username),
330                    "bootstrapped admin user from REDDB_USERNAME/REDDB_PASSWORD"
331                );
332                if let Some(ref cert) = result.certificate {
333                    // Certificate must be readable by the operator — keep it
334                    // in the log stream but print raw to stderr too so it
335                    // survives even if the log file gets rotated.
336                    eprintln!("[reddb] CERTIFICATE: {}", cert);
337                    tracing::warn!(
338                        "vault certificate issued — save it: ONLY way to unseal after restart"
339                    );
340                }
341                Some(result)
342            }
343            Err(e) => {
344                tracing::error!(err = %e, "env bootstrap failed");
345                None
346            }
347        }
348    }
349
350    // -----------------------------------------------------------------
351    // Vault persistence
352    // -----------------------------------------------------------------
353
354    /// Persist the current auth state to the vault pages (if configured).
355    fn persist_to_vault_result(&self) -> Result<(), AuthError> {
356        let vault_guard = self.vault.read().unwrap_or_else(|e| e.into_inner());
357        if let (Some(ref vault), Some(ref pager)) = (&*vault_guard, &self.pager) {
358            let state = self.snapshot();
359            vault.save(pager, &state)?;
360        }
361        Ok(())
362    }
363
364    /// Persist the current auth state to the vault pages (if configured).
365    ///
366    /// Legacy auth mutations still treat in-memory state as authoritative.
367    /// New secret-management paths use the `try_` methods below so callers
368    /// get a hard error if the vault write fails.
369    fn persist_to_vault(&self) {
370        if let Err(e) = self.persist_to_vault_result() {
371            tracing::error!(err = %e, "vault persist failed");
372            // Issue #205 — vault persist is the secret-rotation
373            // serialization point: when this fails, freshly rotated
374            // credentials live only in memory and a process restart
375            // loses them. Operator-grade event so the operator can
376            // intervene before the next restart.
377            crate::telemetry::operator_event::OperatorEvent::SecretRotationFailed {
378                secret_ref: "auth_vault".to_string(),
379                error: e.to_string(),
380            }
381            .emit_global();
382        }
383    }
384
385    /// True when this store has an encrypted vault and pager wired in.
386    pub fn is_vault_backed(&self) -> bool {
387        self.pager.is_some()
388            && self
389                .vault
390                .read()
391                .map(|guard| guard.is_some())
392                .unwrap_or(false)
393    }
394
395    // -----------------------------------------------------------------
396    // Vault KV — encrypted key-value store for arbitrary secrets
397    // -----------------------------------------------------------------
398
399    /// Read a value from the vault KV store. Returns `None` if not set.
400    pub fn vault_kv_get(&self, key: &str) -> Option<String> {
401        self.vault_kv
402            .read()
403            .ok()
404            .and_then(|kv| kv.get(key).cloned())
405    }
406
407    /// Snapshot vault KV values for statement-local secret resolution.
408    pub fn vault_kv_snapshot(&self) -> HashMap<String, String> {
409        self.vault_kv
410            .read()
411            .map(|kv| kv.clone())
412            .unwrap_or_default()
413    }
414
415    /// Export vault KV as an encrypted logical blob for JSONL dump/restore.
416    /// Returns `None` when the vault has no KV entries.
417    pub fn vault_kv_export_encrypted(&self) -> Result<Option<String>, AuthError> {
418        if !self.is_vault_backed() {
419            return Err(AuthError::Forbidden(
420                "vault KV export requires an enabled, unsealed vault".to_string(),
421            ));
422        }
423        let kv = self.vault_kv_snapshot();
424        if kv.is_empty() {
425            return Ok(None);
426        }
427
428        let vault_guard = self.vault.read().map_err(lock_err)?;
429        let vault = vault_guard.as_ref().ok_or_else(|| {
430            AuthError::Forbidden("vault KV export requires an enabled, unsealed vault".to_string())
431        })?;
432        let state = VaultState {
433            users: Vec::new(),
434            api_keys: Vec::new(),
435            bootstrapped: false,
436            master_secret: None,
437            kv,
438        };
439        Ok(Some(vault.seal_logical_export(&state)?))
440    }
441
442    /// Merge imported vault KV entries and fail if the encrypted vault
443    /// write cannot be made durable.
444    pub fn vault_kv_try_import(
445        &self,
446        entries: HashMap<String, String>,
447    ) -> Result<usize, AuthError> {
448        if !self.is_vault_backed() {
449            return Err(AuthError::Forbidden(
450                "vault KV import requires an enabled, unsealed vault".to_string(),
451            ));
452        }
453        if entries.is_empty() {
454            return Ok(0);
455        }
456
457        let mut previous = HashMap::new();
458        {
459            let mut kv = self.vault_kv.write().map_err(lock_err)?;
460            for (key, value) in &entries {
461                previous.insert(key.clone(), kv.insert(key.clone(), value.clone()));
462            }
463        }
464
465        if let Err(err) = self.persist_to_vault_result() {
466            if let Ok(mut kv) = self.vault_kv.write() {
467                for (key, old) in previous {
468                    match old {
469                        Some(value) => {
470                            kv.insert(key, value);
471                        }
472                        None => {
473                            kv.remove(&key);
474                        }
475                    }
476                }
477            }
478            return Err(err);
479        }
480
481        Ok(entries.len())
482    }
483
484    /// Import false placeholders for secrets whose encrypted payload
485    /// could not be decrypted during logical restore.
486    pub fn vault_kv_try_import_placeholders(&self, keys: &[String]) -> Result<usize, AuthError> {
487        let entries = keys
488            .iter()
489            .map(|key| (key.clone(), "false".to_string()))
490            .collect();
491        self.vault_kv_try_import(entries)
492    }
493
494    /// Write a value to the vault KV store, persisting to disk.
495    pub fn vault_kv_set(&self, key: String, value: String) {
496        if let Ok(mut kv) = self.vault_kv.write() {
497            kv.insert(key, value);
498        }
499        self.persist_to_vault();
500    }
501
502    /// Write a value to the vault KV store and fail if the vault write
503    /// cannot be made durable.
504    pub fn vault_kv_try_set(&self, key: String, value: String) -> Result<(), AuthError> {
505        if !self.is_vault_backed() {
506            return Err(AuthError::Forbidden(
507                "SET SECRET requires an enabled, unsealed vault".to_string(),
508            ));
509        }
510
511        let previous = {
512            let mut kv = self.vault_kv.write().map_err(lock_err)?;
513            kv.insert(key.clone(), value)
514        };
515
516        if let Err(err) = self.persist_to_vault_result() {
517            if let Ok(mut kv) = self.vault_kv.write() {
518                match previous {
519                    Some(value) => {
520                        kv.insert(key, value);
521                    }
522                    None => {
523                        kv.remove(&key);
524                    }
525                }
526            }
527            return Err(err);
528        }
529
530        Ok(())
531    }
532
533    /// Delete a value from the vault KV store. Returns true if it existed.
534    pub fn vault_kv_delete(&self, key: &str) -> bool {
535        let existed = self
536            .vault_kv
537            .write()
538            .map(|mut kv| kv.remove(key).is_some())
539            .unwrap_or(false);
540        if existed {
541            self.persist_to_vault();
542        }
543        existed
544    }
545
546    /// Delete a value from the vault KV store and fail if the vault write
547    /// cannot be made durable.
548    pub fn vault_kv_try_delete(&self, key: &str) -> Result<bool, AuthError> {
549        if !self.is_vault_backed() {
550            return Err(AuthError::Forbidden(
551                "DELETE SECRET requires an enabled, unsealed vault".to_string(),
552            ));
553        }
554
555        let removed = {
556            let mut kv = self.vault_kv.write().map_err(lock_err)?;
557            kv.remove(key)
558        };
559
560        if removed.is_none() {
561            return Ok(false);
562        }
563
564        if let Err(err) = self.persist_to_vault_result() {
565            if let Ok(mut kv) = self.vault_kv.write() {
566                if let Some(value) = removed {
567                    kv.insert(key.to_string(), value);
568                }
569            }
570            return Err(err);
571        }
572
573        Ok(true)
574    }
575
576    /// List all keys in the vault KV store.
577    pub fn vault_kv_keys(&self) -> Vec<String> {
578        self.vault_kv
579            .read()
580            .map(|kv| kv.keys().cloned().collect())
581            .unwrap_or_default()
582    }
583
584    /// Convenience: get the 32-byte secret key for Value::Secret encryption.
585    /// Generated on first boot and stored at `red.secret.aes_key`.
586    pub fn vault_secret_key(&self) -> Option<[u8; 32]> {
587        let hex_str = self.vault_kv_get("red.secret.aes_key")?;
588        let bytes = hex::decode(hex_str).ok()?;
589        if bytes.len() == 32 {
590            let mut key = [0u8; 32];
591            key.copy_from_slice(&bytes);
592            Some(key)
593        } else {
594            None
595        }
596    }
597
598    /// Generate and store the AES-256 secret key on first boot if not present.
599    pub fn ensure_vault_secret_key(&self) {
600        if self.vault_kv_get("red.secret.aes_key").is_none() {
601            let key = random_bytes(32);
602            self.vault_kv_set("red.secret.aes_key".to_string(), hex::encode(key));
603        }
604    }
605
606    /// Take a snapshot of the current auth state for vault serialization.
607    fn snapshot(&self) -> VaultState {
608        let users_guard = self.users.read().unwrap_or_else(|e| e.into_inner());
609        let users: Vec<User> = users_guard.values().cloned().collect();
610
611        // Collect (owner UserId, api_key) pairs from all users so a
612        // tenant-scoped owner can be reattached on restore.
613        let mut api_keys = Vec::new();
614        for user in &users {
615            let owner = UserId::from_parts(user.tenant_id.as_deref(), &user.username);
616            for key in &user.api_keys {
617                api_keys.push((owner.clone(), key.clone()));
618            }
619        }
620
621        // Include the master secret if a keypair is loaded.
622        let master_secret = self
623            .keypair
624            .read()
625            .ok()
626            .and_then(|guard| guard.as_ref().map(|kp| kp.master_secret.clone()));
627
628        let kv = self.vault_kv.read().map(|m| m.clone()).unwrap_or_default();
629
630        VaultState {
631            users,
632            api_keys,
633            bootstrapped: self.bootstrapped.load(Ordering::Acquire),
634            master_secret,
635            kv,
636        }
637    }
638
639    /// Restore the in-memory auth state from a vault snapshot.
640    fn restore_from_vault(&mut self, state: VaultState) {
641        // Restore bootstrap seal.
642        if state.bootstrapped {
643            self.bootstrapped.store(true, Ordering::Release);
644        }
645
646        // Restore keypair from master secret (if present).
647        if let Some(secret) = state.master_secret {
648            let kp = KeyPair::from_master_secret(secret);
649            if let Ok(mut guard) = self.keypair.write() {
650                *guard = Some(kp);
651            }
652        }
653
654        // Restore KV store.
655        if let Ok(mut kv) = self.vault_kv.write() {
656            *kv = state.kv;
657        }
658
659        // Restore users.
660        let mut users = self.users.write().unwrap_or_else(|e| e.into_inner());
661        let mut idx = self
662            .api_key_index
663            .write()
664            .unwrap_or_else(|e| e.into_inner());
665
666        for user in state.users {
667            let id = UserId::from_parts(user.tenant_id.as_deref(), &user.username);
668            // Register API keys in the index.
669            for key in &user.api_keys {
670                idx.insert(key.key.clone(), (id.clone(), key.role));
671            }
672            users.insert(id, user);
673        }
674        drop(idx);
675        drop(users);
676
677        self.rehydrate_acl();
678        self.rehydrate_iam();
679    }
680
681    // -----------------------------------------------------------------
682    // User management
683    // -----------------------------------------------------------------
684
685    /// Create a new platform-scoped user (`tenant_id = None`).
686    ///
687    /// For tenant-scoped creation, use [`Self::create_user_in_tenant`].
688    pub fn create_user(
689        &self,
690        username: &str,
691        password: &str,
692        role: Role,
693    ) -> Result<User, AuthError> {
694        self.create_user_in_tenant(None, username, password, role)
695    }
696
697    /// Create a user under the given tenant scope. `tenant_id == None`
698    /// produces a platform-wide user. `(tenant, username)` is the
699    /// uniqueness key — the same `username` may exist independently
700    /// under multiple tenants.
701    pub fn create_user_in_tenant(
702        &self,
703        tenant_id: Option<&str>,
704        username: &str,
705        password: &str,
706        role: Role,
707    ) -> Result<User, AuthError> {
708        self.create_user_in_tenant_with_ownership(tenant_id, username, password, role, false)
709    }
710
711    pub fn create_system_user(
712        &self,
713        username: &str,
714        password: &str,
715        role: Role,
716        tenant_id: Option<&str>,
717    ) -> Result<User, AuthError> {
718        self.create_user_in_tenant_with_ownership(tenant_id, username, password, role, true)
719    }
720
721    fn create_user_in_tenant_with_ownership(
722        &self,
723        tenant_id: Option<&str>,
724        username: &str,
725        password: &str,
726        role: Role,
727        system_owned: bool,
728    ) -> Result<User, AuthError> {
729        let id = UserId::from_parts(tenant_id, username);
730        let mut users = self.users.write().map_err(lock_err)?;
731        if users.contains_key(&id) {
732            return Err(AuthError::UserExists(id.to_string()));
733        }
734
735        let now = now_ms();
736        let user = User {
737            username: username.to_string(),
738            tenant_id: tenant_id.map(|s| s.to_string()),
739            password_hash: hash_password(password),
740            scram_verifier: Some(make_scram_verifier(password)),
741            role,
742            api_keys: Vec::new(),
743            created_at: now,
744            updated_at: now,
745            enabled: true,
746            system_owned,
747        };
748        users.insert(id, user.clone());
749        drop(users); // release lock before vault I/O
750        self.persist_to_vault();
751        Ok(user)
752    }
753
754    /// Look up a user's SCRAM verifier by full `UserId`.
755    ///
756    /// The wire handshake passes the tenant resolved from the session
757    /// (or `None` for the bootstrap admin) so cross-tenant collisions
758    /// never authenticate the wrong identity.
759    pub fn lookup_scram_verifier(&self, id: &UserId) -> Option<crate::auth::scram::ScramVerifier> {
760        let users = self.users.read().ok()?;
761        users.get(id).and_then(|u| u.scram_verifier.clone())
762    }
763
764    /// Backwards-compatible shim for the v2 wire bootstrap path: looks
765    /// up a user by username assuming the platform (`tenant=None`)
766    /// scope. Use this only where the handshake hasn't yet learned the
767    /// caller's tenant.
768    pub fn lookup_scram_verifier_global(
769        &self,
770        username: &str,
771    ) -> Option<crate::auth::scram::ScramVerifier> {
772        self.lookup_scram_verifier(&UserId::platform(username))
773    }
774
775    /// Return all users (password hashes redacted).
776    pub fn list_users(&self) -> Vec<User> {
777        let users = match self.users.read() {
778            Ok(g) => g,
779            Err(_) => return Vec::new(),
780        };
781        users
782            .values()
783            .map(|u| User {
784                password_hash: String::new(), // redacted
785                ..u.clone()
786            })
787            .collect()
788    }
789
790    /// Return users restricted to a tenant scope.
791    ///
792    /// `tenant_filter`:
793    ///   - `None` listing in `Some(None)` — only platform users
794    ///   - `Some(Some("acme"))` — only users in tenant `acme`
795    ///   - `None` argument — all users (admin-only callers)
796    pub fn list_users_scoped(&self, tenant_filter: Option<Option<&str>>) -> Vec<User> {
797        let users = match self.users.read() {
798            Ok(g) => g,
799            Err(_) => return Vec::new(),
800        };
801        users
802            .values()
803            .filter(|u| match tenant_filter {
804                None => true,
805                Some(t) => u.tenant_id.as_deref() == t,
806            })
807            .map(|u| User {
808                password_hash: String::new(), // redacted
809                ..u.clone()
810            })
811            .collect()
812    }
813
814    /// Look up a single user by `(tenant, username)`. Password hash
815    /// is redacted.
816    pub fn get_user(&self, tenant_id: Option<&str>, username: &str) -> Option<User> {
817        let id = UserId::from_parts(tenant_id, username);
818        self.get_user_cloned(&id).map(|u| User {
819            password_hash: String::new(),
820            ..u
821        })
822    }
823
824    /// Delete a platform-scoped user (`tenant_id = None`) and revoke
825    /// all of their API keys + sessions.
826    ///
827    /// For tenant-scoped deletes, use [`Self::delete_user_in_tenant`].
828    pub fn delete_user(&self, username: &str) -> Result<(), AuthError> {
829        self.delete_user_in_tenant(None, username)
830    }
831
832    /// Delete a user identified by `(tenant_id, username)` and revoke
833    /// all of their API keys + sessions.
834    pub fn delete_user_in_tenant(
835        &self,
836        tenant_id: Option<&str>,
837        username: &str,
838    ) -> Result<(), AuthError> {
839        let id = UserId::from_parts(tenant_id, username);
840        let mut users = self.users.write().map_err(lock_err)?;
841        let user = users
842            .get(&id)
843            .ok_or_else(|| AuthError::UserNotFound(id.to_string()))?;
844        reject_system_owned(&id, user)?;
845        let user = users
846            .remove(&id)
847            .ok_or_else(|| AuthError::UserNotFound(id.to_string()))?;
848
849        // Remove API key index entries.
850        if let Ok(mut idx) = self.api_key_index.write() {
851            for api_key in &user.api_keys {
852                idx.remove(&api_key.key);
853            }
854        }
855
856        // Remove sessions belonging to this user (match on tenant+username
857        // so we don't tear down a same-named user in another tenant).
858        if let Ok(mut sessions) = self.sessions.write() {
859            sessions
860                .retain(|_, s| !(s.username == username && s.tenant_id.as_deref() == tenant_id));
861        }
862
863        self.persist_to_vault();
864        Ok(())
865    }
866
867    /// Change password (requires the old password). Defaults to
868    /// platform tenant; use [`Self::change_password_in_tenant`] for
869    /// scoped users.
870    pub fn change_password(
871        &self,
872        username: &str,
873        old_password: &str,
874        new_password: &str,
875    ) -> Result<(), AuthError> {
876        self.change_password_in_tenant(None, username, old_password, new_password)
877    }
878
879    pub fn change_password_in_tenant(
880        &self,
881        tenant_id: Option<&str>,
882        username: &str,
883        old_password: &str,
884        new_password: &str,
885    ) -> Result<(), AuthError> {
886        let id = UserId::from_parts(tenant_id, username);
887        let mut users = self.users.write().map_err(lock_err)?;
888        let user = users
889            .get_mut(&id)
890            .ok_or_else(|| AuthError::UserNotFound(id.to_string()))?;
891        reject_system_owned(&id, user)?;
892
893        if !verify_password(old_password, &user.password_hash) {
894            return Err(AuthError::InvalidCredentials);
895        }
896
897        user.password_hash = hash_password(new_password);
898        user.scram_verifier = Some(make_scram_verifier(new_password));
899        user.updated_at = now_ms();
900        drop(users); // release lock before vault I/O
901        self.persist_to_vault();
902        Ok(())
903    }
904
905    /// Change a user's role (admin-only operation). Defaults to platform
906    /// tenant; use [`Self::change_role_in_tenant`] for scoped users.
907    pub fn change_role(&self, username: &str, new_role: Role) -> Result<(), AuthError> {
908        self.change_role_in_tenant(None, username, new_role)
909    }
910
911    pub fn change_role_in_tenant(
912        &self,
913        tenant_id: Option<&str>,
914        username: &str,
915        new_role: Role,
916    ) -> Result<(), AuthError> {
917        let id = UserId::from_parts(tenant_id, username);
918        let mut users = self.users.write().map_err(lock_err)?;
919        let user = users
920            .get_mut(&id)
921            .ok_or_else(|| AuthError::UserNotFound(id.to_string()))?;
922        reject_system_owned(&id, user)?;
923
924        let prior_role = user.role;
925        user.role = new_role;
926        user.updated_at = now_ms();
927
928        // Issue #205 — promotion to Admin is an operator-grade event:
929        // the new role grants destructive capabilities (DROP, ALTER,
930        // GRANT) that an operator must observe out-of-band even when
931        // the auth path itself is healthy.
932        if new_role == Role::Admin && prior_role != Role::Admin {
933            crate::telemetry::operator_event::OperatorEvent::AdminCapabilityGranted {
934                granted_to: id.to_string(),
935                capability: "Role::Admin".to_string(),
936                granted_by: "auth_store::change_role".to_string(),
937            }
938            .emit_global();
939        }
940
941        // Downgrade any API keys that now exceed the user's role.
942        for key in &mut user.api_keys {
943            if key.role > new_role {
944                key.role = new_role;
945            }
946        }
947
948        // Update the api_key_index as well.
949        if let Ok(mut idx) = self.api_key_index.write() {
950            for key in &user.api_keys {
951                if let Some(entry) = idx.get_mut(&key.key) {
952                    entry.1 = key.role;
953                }
954            }
955        }
956
957        self.persist_to_vault();
958        Ok(())
959    }
960
961    // -----------------------------------------------------------------
962    // Authentication (login)
963    // -----------------------------------------------------------------
964
965    /// Verify credentials for a platform-tenant user (`tenant_id = None`)
966    /// and create a session. For tenant-scoped login use
967    /// [`Self::authenticate_in_tenant`].
968    ///
969    /// When a keypair is available (certificate-based seal), session tokens
970    /// are signed with the master secret so the server can verify they were
971    /// genuinely issued by this vault instance.
972    pub fn authenticate(&self, username: &str, password: &str) -> Result<Session, AuthError> {
973        self.authenticate_in_tenant(None, username, password)
974    }
975
976    /// Verify credentials for `(tenant_id, username, password)` and
977    /// create a session. Tenant-aware: `alice@acme` and `alice@globex`
978    /// authenticate independently.
979    pub fn authenticate_in_tenant(
980        &self,
981        tenant_id: Option<&str>,
982        username: &str,
983        password: &str,
984    ) -> Result<Session, AuthError> {
985        let id = UserId::from_parts(tenant_id, username);
986        let users = self.users.read().map_err(lock_err)?;
987        let user = users.get(&id).ok_or(AuthError::InvalidCredentials)?;
988
989        if !user.enabled {
990            return Err(AuthError::InvalidCredentials);
991        }
992
993        if !verify_password(password, &user.password_hash) {
994            return Err(AuthError::InvalidCredentials);
995        }
996
997        // Generate token: signed if keypair is available, random otherwise.
998        let token = match self.keypair.read().ok().and_then(|g| {
999            g.as_ref().map(|kp| {
1000                let token_id = random_hex(16);
1001                let sig = kp.sign(format!("session:{}", token_id).as_bytes());
1002                // Take first 16 bytes of signature for compact token.
1003                format!("rs_{}{}", token_id, hex::encode(&sig[..16]))
1004            })
1005        }) {
1006            Some(signed_token) => signed_token,
1007            None => generate_session_token(),
1008        };
1009
1010        let now = now_ms();
1011        let session = Session {
1012            token,
1013            username: username.to_string(),
1014            tenant_id: user.tenant_id.clone(),
1015            role: user.role,
1016            created_at: now,
1017            expires_at: now + (self.config.session_ttl_secs as u128 * 1000),
1018        };
1019
1020        drop(users); // release read lock before acquiring write
1021
1022        let mut sessions = self.sessions.write().map_err(lock_err)?;
1023        sessions.insert(session.token.clone(), session.clone());
1024        Ok(session)
1025    }
1026
1027    // -----------------------------------------------------------------
1028    // Token validation
1029    // -----------------------------------------------------------------
1030
1031    /// Validate a token (session or API key).
1032    ///
1033    /// Returns `(username, role)` if valid, `None` otherwise. Tenant
1034    /// scope is dropped here for compatibility with the bulk of the
1035    /// existing caller surface (routing, gRPC control, redwire). Use
1036    /// [`Self::validate_token_full`] when the caller needs the
1037    /// resolved `UserId` (e.g. to pin `CURRENT_TENANT()`).
1038    pub fn validate_token(&self, token: &str) -> Option<(String, Role)> {
1039        self.validate_token_full(token)
1040            .map(|(id, role)| (id.username, role))
1041    }
1042
1043    /// Tenant-aware token validation. Returns the resolved `UserId`
1044    /// (which carries the tenant) and the granted `Role`.
1045    pub fn validate_token_full(&self, token: &str) -> Option<(UserId, Role)> {
1046        // Try session tokens first.
1047        if token.starts_with("rs_") {
1048            if let Ok(sessions) = self.sessions.read() {
1049                if let Some(session) = sessions.get(token) {
1050                    let now = now_ms();
1051                    if now < session.expires_at {
1052                        return Some((
1053                            UserId::from_parts(session.tenant_id.as_deref(), &session.username),
1054                            session.role,
1055                        ));
1056                    }
1057                }
1058            }
1059            return None;
1060        }
1061
1062        // Try API keys.
1063        if token.starts_with("rk_") {
1064            if let Ok(idx) = self.api_key_index.read() {
1065                return idx.get(token).cloned();
1066            }
1067            return None;
1068        }
1069
1070        None
1071    }
1072
1073    // -----------------------------------------------------------------
1074    // API Key management
1075    // -----------------------------------------------------------------
1076
1077    /// Create a persistent API key for a platform-tenant user.
1078    ///
1079    /// For tenant-scoped users use [`Self::create_api_key_in_tenant`].
1080    pub fn create_api_key(
1081        &self,
1082        username: &str,
1083        name: &str,
1084        role: Role,
1085    ) -> Result<ApiKey, AuthError> {
1086        self.create_api_key_in_tenant(None, username, name, role)
1087    }
1088
1089    pub fn create_api_key_in_tenant(
1090        &self,
1091        tenant_id: Option<&str>,
1092        username: &str,
1093        name: &str,
1094        role: Role,
1095    ) -> Result<ApiKey, AuthError> {
1096        let id = UserId::from_parts(tenant_id, username);
1097        let mut users = self.users.write().map_err(lock_err)?;
1098        let user = users
1099            .get_mut(&id)
1100            .ok_or_else(|| AuthError::UserNotFound(id.to_string()))?;
1101
1102        // The key's role cannot exceed the user's role.
1103        if role > user.role {
1104            return Err(AuthError::RoleExceeded {
1105                requested: role,
1106                ceiling: user.role,
1107            });
1108        }
1109
1110        let api_key = ApiKey {
1111            key: generate_api_key(),
1112            name: name.to_string(),
1113            role,
1114            created_at: now_ms(),
1115        };
1116
1117        user.api_keys.push(api_key.clone());
1118        user.updated_at = now_ms();
1119
1120        // Update the index.
1121        if let Ok(mut idx) = self.api_key_index.write() {
1122            idx.insert(api_key.key.clone(), (id.clone(), api_key.role));
1123        }
1124
1125        drop(users); // release lock before vault I/O
1126        self.persist_to_vault();
1127        Ok(api_key)
1128    }
1129
1130    /// Revoke (delete) an API key.
1131    pub fn revoke_api_key(&self, key: &str) -> Result<(), AuthError> {
1132        let mut users = self.users.write().map_err(lock_err)?;
1133
1134        // Find which user owns this key (look up by the api_key_index
1135        // first; fall back to a scan for legacy state restored before
1136        // the index was reseeded).
1137        let owner_id: UserId = {
1138            if let Ok(idx) = self.api_key_index.read() {
1139                if let Some((id, _)) = idx.get(key) {
1140                    id.clone()
1141                } else {
1142                    return Err(AuthError::KeyNotFound(key.to_string()));
1143                }
1144            } else {
1145                let owner = users
1146                    .iter()
1147                    .find(|(_, u)| u.api_keys.iter().any(|k| k.key == key));
1148                match owner {
1149                    Some((id, _)) => id.clone(),
1150                    None => return Err(AuthError::KeyNotFound(key.to_string())),
1151                }
1152            }
1153        };
1154
1155        let user = users
1156            .get_mut(&owner_id)
1157            .ok_or_else(|| AuthError::KeyNotFound(key.to_string()))?;
1158        user.api_keys.retain(|k| k.key != key);
1159        user.updated_at = now_ms();
1160
1161        // Remove from index.
1162        if let Ok(mut idx) = self.api_key_index.write() {
1163            idx.remove(key);
1164        }
1165
1166        self.persist_to_vault();
1167        Ok(())
1168    }
1169
1170    // -----------------------------------------------------------------
1171    // Session management
1172    // -----------------------------------------------------------------
1173
1174    /// Revoke a session token.
1175    pub fn revoke_session(&self, token: &str) {
1176        if let Ok(mut sessions) = self.sessions.write() {
1177            sessions.remove(token);
1178        }
1179    }
1180
1181    /// Purge expired sessions (housekeeping).
1182    pub fn purge_expired_sessions(&self) -> usize {
1183        let now = now_ms();
1184        if let Ok(mut sessions) = self.sessions.write() {
1185            let before = sessions.len();
1186            sessions.retain(|_, s| s.expires_at > now);
1187            return before - sessions.len();
1188        }
1189        0
1190    }
1191
1192    // -----------------------------------------------------------------
1193    // Granular RBAC — GRANT / REVOKE
1194    //
1195    // The privilege engine lives in `super::privileges`. These helpers
1196    // are the AuthStore facade: they keep an in-memory map of grants per
1197    // user (plus a `public_grants` list), persist additions/removals to
1198    // the existing `vault_kv` store, and rebuild the per-user
1199    // `PermissionCache` so the hot path stays O(1).
1200    //
1201    // Persistence design: rather than extend the snapshot/restore
1202    // pipeline (Agent #2's territory) we serialise grants and account
1203    // attributes to the vault KV store. That gives us atomic write +
1204    // encrypted-at-rest semantics for free without touching the
1205    // existing USER/KEY/KV serializer paths. On restart `rehydrate_acl`
1206    // reads these KV entries back into the in-memory maps.
1207    // -----------------------------------------------------------------
1208
1209    /// Persist a grant. Returns `Forbidden` when the granting user is
1210    /// not Admin or attempts a cross-tenant grant.
1211    pub fn grant(
1212        &self,
1213        granter: &UserId,
1214        granter_role: Role,
1215        principal: GrantPrincipal,
1216        resource: Resource,
1217        actions: Vec<Action>,
1218        with_grant_option: bool,
1219        tenant: Option<String>,
1220    ) -> Result<(), AuthError> {
1221        if granter_role != Role::Admin {
1222            return Err(AuthError::Forbidden(format!(
1223                "GRANT requires Admin role; granter `{}` has `{:?}`",
1224                granter, granter_role
1225            )));
1226        }
1227
1228        // Cross-tenant guard: a tenant-scoped admin cannot mint grants
1229        // outside their tenant. Platform admin (tenant=None) may grant
1230        // anywhere.
1231        if granter.tenant.is_some() && granter.tenant != tenant {
1232            return Err(AuthError::Forbidden(format!(
1233                "cross-tenant GRANT denied: granter tenant `{:?}` != grant tenant `{:?}`",
1234                granter.tenant, tenant
1235            )));
1236        }
1237
1238        let mut actions_set = std::collections::BTreeSet::new();
1239        for a in actions {
1240            actions_set.insert(a);
1241        }
1242        let g = Grant {
1243            principal: principal.clone(),
1244            resource,
1245            actions: actions_set,
1246            with_grant_option,
1247            granted_by: granter.to_string(),
1248            granted_at: now_ms(),
1249            tenant,
1250            columns: None,
1251        };
1252
1253        match &principal {
1254            GrantPrincipal::User(uid) => {
1255                self.grants
1256                    .write()
1257                    .unwrap_or_else(|e| e.into_inner())
1258                    .entry(uid.clone())
1259                    .or_default()
1260                    .push(g.clone());
1261                self.invalidate_permission_cache(Some(uid));
1262            }
1263            GrantPrincipal::Public => {
1264                self.public_grants
1265                    .write()
1266                    .unwrap_or_else(|e| e.into_inner())
1267                    .push(g.clone());
1268                self.invalidate_permission_cache(None);
1269            }
1270            GrantPrincipal::Group(_) => {
1271                return Err(AuthError::Forbidden(
1272                    "GROUP principals are not yet supported; use a USER or PUBLIC".to_string(),
1273                ));
1274            }
1275        }
1276
1277        // Issue #119: a fresh grant changes the visible-collections set
1278        // for `(tenant, role)` callers under the same tenant. Drop those
1279        // cache entries so the next AI command sees the new SELECT
1280        // privilege immediately.
1281        self.invalidate_visible_collections_for_tenant(g.tenant.as_deref());
1282
1283        self.persist_acl_to_kv();
1284        Ok(())
1285    }
1286
1287    /// Drop matching grants from a principal. Returns the number of
1288    /// grants removed.
1289    pub fn revoke(
1290        &self,
1291        granter_role: Role,
1292        principal: &GrantPrincipal,
1293        resource: &Resource,
1294        actions: &[Action],
1295    ) -> Result<usize, AuthError> {
1296        if granter_role != Role::Admin {
1297            return Err(AuthError::Forbidden(format!(
1298                "REVOKE requires Admin role; granter has `{:?}`",
1299                granter_role
1300            )));
1301        }
1302
1303        let removed = match principal {
1304            GrantPrincipal::User(uid) => {
1305                let mut g = self.grants.write().unwrap_or_else(|e| e.into_inner());
1306                let before = g.get(uid).map(|v| v.len()).unwrap_or(0);
1307                if let Some(list) = g.get_mut(uid) {
1308                    list.retain(|gr| {
1309                        !(gr.resource == *resource
1310                            && (actions.iter().any(|a| gr.actions.contains(a))
1311                                || (gr.actions.contains(&Action::All) && !actions.is_empty())))
1312                    });
1313                }
1314                let after = g.get(uid).map(|v| v.len()).unwrap_or(0);
1315                drop(g);
1316                self.invalidate_permission_cache(Some(uid));
1317                before - after
1318            }
1319            GrantPrincipal::Public => {
1320                let mut p = self
1321                    .public_grants
1322                    .write()
1323                    .unwrap_or_else(|e| e.into_inner());
1324                let before = p.len();
1325                p.retain(|gr| {
1326                    !(gr.resource == *resource
1327                        && (actions.iter().any(|a| gr.actions.contains(a))
1328                            || (gr.actions.contains(&Action::All) && !actions.is_empty())))
1329                });
1330                let after = p.len();
1331                drop(p);
1332                self.invalidate_permission_cache(None);
1333                before - after
1334            }
1335            GrantPrincipal::Group(_) => 0,
1336        };
1337
1338        if removed > 0 {
1339            // Issue #119: REVOKE may shrink the visible-collections set
1340            // for any `(tenant, role)` slot. We don't know the exact
1341            // tenant when the principal is `Public`, so a `Public`
1342            // revoke clears the whole cache; user revokes scope to the
1343            // user's tenant.
1344            match principal {
1345                GrantPrincipal::User(uid) => {
1346                    self.invalidate_visible_collections_for_tenant(uid.tenant.as_deref());
1347                }
1348                GrantPrincipal::Public | GrantPrincipal::Group(_) => {
1349                    self.invalidate_visible_collections_cache();
1350                }
1351            }
1352            self.persist_acl_to_kv();
1353        }
1354        Ok(removed)
1355    }
1356
1357    /// Compute the set of collection ids a given `(tenant, role)`
1358    /// scope can read, consulting the explicit grant table. The result
1359    /// is cached for `super::scope_cache::DEFAULT_TTL` (60s) and
1360    /// invalidated on every GRANT/REVOKE/policy/collection mutation
1361    /// that could change the answer.
1362    ///
1363    /// `all_collections` is the full list of collection ids known to
1364    /// the storage layer. The runtime hands it in so this module stays
1365    /// decoupled from the storage crate. Each collection passes through
1366    /// `check_grant(SELECT)` under a synthetic `(principal, role,
1367    /// tenant)` view. The cache key includes principal because direct
1368    /// grants can differ between users that share the same tenant and
1369    /// role.
1370    pub fn visible_collections_for_scope(
1371        &self,
1372        tenant: Option<&str>,
1373        role: Role,
1374        principal: &str,
1375        all_collections: &[String],
1376    ) -> std::collections::HashSet<String> {
1377        let key = super::scope_cache::ScopeKey::new(tenant, principal, role);
1378        if let Some(hit) = self.visible_collections_cache.get(&key) {
1379            return hit;
1380        }
1381        // Slow path: walk every collection through `check_grant`. We
1382        // build the AuthzContext once, then reuse it per resource.
1383        let ctx = AuthzContext {
1384            principal,
1385            effective_role: role,
1386            tenant,
1387        };
1388        let mut visible = std::collections::HashSet::new();
1389        for collection in all_collections {
1390            let resource = Resource::table_from_name(collection);
1391            if self.check_grant(&ctx, Action::Select, &resource).is_ok() {
1392                visible.insert(collection.clone());
1393            }
1394        }
1395        self.visible_collections_cache.insert(key, visible.clone());
1396        visible
1397    }
1398
1399    /// Stats probe required by issue #119 — exposes hit/miss counts and
1400    /// invalidations for the visible-collections cache so metrics
1401    /// pipelines can compute a hit rate.
1402    pub fn auth_cache_stats(&self) -> super::scope_cache::AuthCacheStats {
1403        self.visible_collections_cache.stats()
1404    }
1405
1406    /// Drop every cached `(tenant, role)` entry. Called from CREATE
1407    /// POLICY / DROP POLICY / DROP COLLECTION paths where the affected
1408    /// tenant set is unknown.
1409    pub fn invalidate_visible_collections_cache(&self) {
1410        self.visible_collections_cache.invalidate_all();
1411    }
1412
1413    /// Drop cached entries for one tenant. Called from GRANT / REVOKE
1414    /// where the principal's tenant is known.
1415    pub fn invalidate_visible_collections_for_tenant(&self, tenant: Option<&str>) {
1416        self.visible_collections_cache.invalidate_tenant(tenant);
1417    }
1418
1419    /// Snapshot of every grant the principal effectively has, including
1420    /// `Public` grants. Audit / introspection helper.
1421    pub fn effective_grants(&self, uid: &UserId) -> Vec<Grant> {
1422        let mut out = Vec::new();
1423        if let Ok(g) = self.grants.read() {
1424            if let Some(list) = g.get(uid) {
1425                out.extend(list.iter().cloned());
1426            }
1427        }
1428        if let Ok(p) = self.public_grants.read() {
1429            out.extend(p.iter().cloned());
1430        }
1431        out
1432    }
1433
1434    /// Run a privilege check using the in-memory grant tables. Returns
1435    /// `Ok(())` on allow, `Err(AuthzError)` on deny.
1436    pub fn check_grant(
1437        &self,
1438        ctx: &AuthzContext<'_>,
1439        action: Action,
1440        resource: &Resource,
1441    ) -> Result<(), AuthzError> {
1442        if ctx.effective_role == Role::Admin {
1443            return Ok(());
1444        }
1445
1446        let uid = UserId::from_parts(ctx.tenant, ctx.principal);
1447
1448        // Fast path: per-user pre-resolved cache.
1449        if let Ok(cache) = self.permission_cache.read() {
1450            if let Some(pc) = cache.get(&uid) {
1451                if pc.allows(resource, action) {
1452                    return Ok(());
1453                }
1454            }
1455        }
1456
1457        // Slow path: linear scan + rebuild cache as a side-effect.
1458        let user_grants = self
1459            .grants
1460            .read()
1461            .ok()
1462            .and_then(|g| g.get(&uid).cloned())
1463            .unwrap_or_default();
1464        let any_user_grants = self
1465            .grants
1466            .read()
1467            .ok()
1468            .map(|g| g.values().any(|list| !list.is_empty()))
1469            .unwrap_or(false);
1470        let public_grants = self
1471            .public_grants
1472            .read()
1473            .ok()
1474            .map(|p| p.clone())
1475            .unwrap_or_default();
1476        if user_grants.is_empty() && public_grants.is_empty() && any_user_grants {
1477            return Err(AuthzError::PermissionDenied {
1478                action,
1479                resource: resource.clone(),
1480                principal: ctx.principal.to_string(),
1481            });
1482        }
1483        let view = GrantsView {
1484            user_grants: &user_grants,
1485            public_grants: &public_grants,
1486        };
1487        let result = check_grant(ctx, action, resource, &view);
1488
1489        if result.is_ok() {
1490            let pc = PermissionCache::build(&user_grants, &public_grants);
1491            if let Ok(mut cache) = self.permission_cache.write() {
1492                cache.insert(uid, pc);
1493            }
1494        }
1495        result
1496    }
1497
1498    // -----------------------------------------------------------------
1499    // ALTER USER attributes (VALID UNTIL, CONNECTION LIMIT, etc.)
1500    // -----------------------------------------------------------------
1501
1502    /// Replace the attribute record for `uid`.
1503    pub fn set_user_attributes(
1504        &self,
1505        uid: &UserId,
1506        attrs: UserAttributes,
1507    ) -> Result<(), AuthError> {
1508        let users = self.users.read().map_err(lock_err)?;
1509        if !users.contains_key(uid) {
1510            return Err(AuthError::UserNotFound(uid.to_string()));
1511        }
1512        drop(users);
1513
1514        self.user_attributes
1515            .write()
1516            .unwrap_or_else(|e| e.into_inner())
1517            .insert(uid.clone(), attrs);
1518        self.invalidate_iam_cache(Some(uid));
1519        self.persist_acl_to_kv();
1520        Ok(())
1521    }
1522
1523    /// Read the attributes for `uid`. Returns `Default::default()` for
1524    /// users that have never been altered.
1525    pub fn user_attributes(&self, uid: &UserId) -> UserAttributes {
1526        self.user_attributes
1527            .read()
1528            .ok()
1529            .and_then(|m| m.get(uid).cloned())
1530            .unwrap_or_default()
1531    }
1532
1533    pub fn add_user_to_group(&self, uid: &UserId, group: &str) -> Result<(), AuthError> {
1534        if group.trim().is_empty() {
1535            return Err(AuthError::Forbidden("group name cannot be empty".into()));
1536        }
1537        let mut attrs = self.user_attributes(uid);
1538        if !attrs.groups.iter().any(|g| g == group) {
1539            attrs.groups.push(group.to_string());
1540            attrs.groups.sort();
1541        }
1542        self.set_user_attributes(uid, attrs)
1543    }
1544
1545    pub fn remove_user_from_group(&self, uid: &UserId, group: &str) -> Result<(), AuthError> {
1546        let mut attrs = self.user_attributes(uid);
1547        attrs.groups.retain(|g| g != group);
1548        self.set_user_attributes(uid, attrs)
1549    }
1550
1551    /// Toggle `User.enabled` without rotating credentials.
1552    pub fn set_user_enabled(&self, uid: &UserId, enabled: bool) -> Result<(), AuthError> {
1553        let mut users = self.users.write().map_err(lock_err)?;
1554        let user = users
1555            .get_mut(uid)
1556            .ok_or_else(|| AuthError::UserNotFound(uid.to_string()))?;
1557        reject_system_owned(uid, user)?;
1558        user.enabled = enabled;
1559        user.updated_at = now_ms();
1560        drop(users);
1561        self.persist_to_vault();
1562        Ok(())
1563    }
1564
1565    // -----------------------------------------------------------------
1566    // Login-side enforcement (HTTP path)
1567    // -----------------------------------------------------------------
1568
1569    /// Authenticate with VALID UNTIL / CONNECTION LIMIT enforcement.
1570    /// Wraps `authenticate_in_tenant` and additionally:
1571    ///   * rejects logins after `valid_until`,
1572    ///   * rejects logins when the live session count would exceed the
1573    ///     `connection_limit` attribute.
1574    pub fn authenticate_with_attrs(
1575        &self,
1576        tenant_id: Option<&str>,
1577        username: &str,
1578        password: &str,
1579    ) -> Result<Session, AuthError> {
1580        let uid = UserId::from_parts(tenant_id, username);
1581        let attrs = self.user_attributes(&uid);
1582
1583        if let Some(deadline) = attrs.valid_until {
1584            if now_ms() >= deadline {
1585                return Err(AuthError::Forbidden(format!(
1586                    "account `{}` expired (VALID UNTIL exceeded)",
1587                    uid
1588                )));
1589            }
1590        }
1591
1592        if let Some(limit) = attrs.connection_limit {
1593            let current = self
1594                .session_count_by_user
1595                .read()
1596                .ok()
1597                .and_then(|m| m.get(&uid).copied())
1598                .unwrap_or(0);
1599            if current >= limit {
1600                return Err(AuthError::Forbidden(format!(
1601                    "account `{}` exceeded CONNECTION LIMIT ({})",
1602                    uid, limit
1603                )));
1604            }
1605        }
1606
1607        let session = self.authenticate_in_tenant(tenant_id, username, password)?;
1608
1609        if let Ok(mut counts) = self.session_count_by_user.write() {
1610            *counts.entry(uid).or_insert(0) += 1;
1611        }
1612        Ok(session)
1613    }
1614
1615    /// Decrement the live-session count for `uid`. Call from session
1616    /// revoke / expiry paths so CONNECTION LIMIT stays accurate.
1617    pub fn decrement_session_count(&self, uid: &UserId) {
1618        if let Ok(mut counts) = self.session_count_by_user.write() {
1619            if let Some(c) = counts.get_mut(uid) {
1620                *c = c.saturating_sub(1);
1621            }
1622        }
1623    }
1624
1625    // -----------------------------------------------------------------
1626    // ACL persistence — vault_kv backed
1627    // -----------------------------------------------------------------
1628
1629    /// Re-read the ACL state from `vault_kv`. Call after vault load /
1630    /// restore so the in-memory maps reflect the persisted data.
1631    pub fn rehydrate_acl(&self) {
1632        let kv_snapshot: Vec<(String, String)> = self
1633            .vault_kv
1634            .read()
1635            .map(|kv| {
1636                kv.iter()
1637                    .filter(|(k, _)| {
1638                        k.starts_with("red.acl.grants.")
1639                            || k.starts_with("red.acl.attrs.")
1640                            || k == &"red.acl.public_grants"
1641                    })
1642                    .map(|(k, v)| (k.clone(), v.clone()))
1643                    .collect()
1644            })
1645            .unwrap_or_default();
1646
1647        for (k, v) in kv_snapshot {
1648            if k == "red.acl.public_grants" {
1649                if let Some(parsed) = decode_grants_blob(&v) {
1650                    *self
1651                        .public_grants
1652                        .write()
1653                        .unwrap_or_else(|e| e.into_inner()) = parsed;
1654                }
1655            } else if let Some(suffix) = k.strip_prefix("red.acl.grants.") {
1656                if let Some(uid) = decode_uid(suffix) {
1657                    if let Some(mut parsed) = decode_grants_blob(&v) {
1658                        // Restore the principal field — the on-disk
1659                        // line stores only resource+action shape.
1660                        for g in parsed.iter_mut() {
1661                            g.principal = GrantPrincipal::User(uid.clone());
1662                        }
1663                        self.grants
1664                            .write()
1665                            .unwrap_or_else(|e| e.into_inner())
1666                            .insert(uid, parsed);
1667                    }
1668                }
1669            } else if let Some(suffix) = k.strip_prefix("red.acl.attrs.") {
1670                if let Some(uid) = decode_uid(suffix) {
1671                    if let Some(parsed) = decode_attrs_blob(&v) {
1672                        self.user_attributes
1673                            .write()
1674                            .unwrap_or_else(|e| e.into_inner())
1675                            .insert(uid, parsed);
1676                    }
1677                }
1678            }
1679        }
1680
1681        self.permission_cache
1682            .write()
1683            .unwrap_or_else(|e| e.into_inner())
1684            .clear();
1685    }
1686
1687    /// Snapshot every ACL change back into the vault KV store.
1688    fn persist_acl_to_kv(&self) {
1689        let public = self
1690            .public_grants
1691            .read()
1692            .ok()
1693            .map(|p| encode_grants_blob(&p))
1694            .unwrap_or_default();
1695        self.vault_kv_set("red.acl.public_grants".to_string(), public);
1696
1697        let snapshot: Vec<(UserId, Vec<Grant>)> = self
1698            .grants
1699            .read()
1700            .ok()
1701            .map(|g| g.iter().map(|(k, v)| (k.clone(), v.clone())).collect())
1702            .unwrap_or_default();
1703        for (uid, list) in snapshot {
1704            let key = format!("red.acl.grants.{}", encode_uid(&uid));
1705            let val = encode_grants_blob(&list);
1706            self.vault_kv_set(key, val);
1707        }
1708
1709        let attrs_snapshot: Vec<(UserId, UserAttributes)> = self
1710            .user_attributes
1711            .read()
1712            .ok()
1713            .map(|m| m.iter().map(|(k, v)| (k.clone(), v.clone())).collect())
1714            .unwrap_or_default();
1715        for (uid, attrs) in attrs_snapshot {
1716            let key = format!("red.acl.attrs.{}", encode_uid(&uid));
1717            let val = encode_attrs_blob(&attrs);
1718            self.vault_kv_set(key, val);
1719        }
1720    }
1721
1722    fn invalidate_permission_cache(&self, uid: Option<&UserId>) {
1723        if let Ok(mut cache) = self.permission_cache.write() {
1724            match uid {
1725                Some(u) => {
1726                    cache.remove(u);
1727                }
1728                None => cache.clear(),
1729            }
1730        }
1731    }
1732
1733    // -----------------------------------------------------------------
1734    // IAM policies — put / delete / attach / detach / simulate
1735    //
1736    // The kernel in `super::policies` owns the Policy type and the
1737    // evaluator. AuthStore handles persistence + per-user cache + the
1738    // GRANT translation layer (synthetic `_grant_*` policies).
1739    // -----------------------------------------------------------------
1740
1741    /// Insert or replace a policy by id. Rejects synthetic ids
1742    /// (`_grant_*` / `_default_*`) so callers can't hand-write them
1743    /// from the public API. Use `put_policy_internal` for synthetic
1744    /// inserts.
1745    pub fn put_policy(&self, p: Policy) -> Result<(), AuthError> {
1746        if p.id.starts_with("_grant_") || p.id.starts_with("_default_") {
1747            return Err(AuthError::Forbidden(format!(
1748                "policy id `{}` is reserved",
1749                p.id
1750            )));
1751        }
1752        self.put_policy_internal(p)
1753    }
1754
1755    /// Internal put bypassing the synthetic-namespace guard. Used by
1756    /// the GRANT translation layer; exposed publicly so integration
1757    /// tests can register synthetic `_grant_*` policies without going
1758    /// through the SQL frontend.
1759    pub fn put_policy_internal(&self, p: Policy) -> Result<(), AuthError> {
1760        p.validate()
1761            .map_err(|e| AuthError::Forbidden(format!("invalid policy `{}`: {e}", p.id)))?;
1762        let id = p.id.clone();
1763        self.policies
1764            .write()
1765            .unwrap_or_else(|e| e.into_inner())
1766            .insert(id, Arc::new(p));
1767        self.iam_authorization_enabled
1768            .store(true, Ordering::Release);
1769        self.iam_effective_cache
1770            .write()
1771            .unwrap_or_else(|e| e.into_inner())
1772            .clear();
1773        // Issue #119: a policy mutation can change the visible-
1774        // collections answer for any (tenant, role); we don't know
1775        // which up-front, so blow the whole cache.
1776        self.invalidate_visible_collections_cache();
1777        self.persist_iam_to_kv();
1778        Ok(())
1779    }
1780
1781    /// Whether the IAM evaluator should be authoritative for runtime
1782    /// authorization. This flips on the first policy write and remains
1783    /// on after deletes so dropping all policies leaves the instance in
1784    /// default-deny rather than silently returning to role fallback.
1785    pub fn iam_authorization_enabled(&self) -> bool {
1786        self.iam_authorization_enabled.load(Ordering::Acquire)
1787    }
1788
1789    /// Remove a policy and any attachments referencing it.
1790    pub fn delete_policy(&self, id: &str) -> Result<(), AuthError> {
1791        let removed = self
1792            .policies
1793            .write()
1794            .unwrap_or_else(|e| e.into_inner())
1795            .remove(id)
1796            .is_some();
1797        if !removed {
1798            return Err(AuthError::Forbidden(format!("policy `{id}` not found")));
1799        }
1800        // Detach from every user / group.
1801        if let Ok(mut ua) = self.user_attachments.write() {
1802            for ids in ua.values_mut() {
1803                ids.retain(|p| p != id);
1804            }
1805            ua.retain(|_, v| !v.is_empty());
1806        }
1807        if let Ok(mut ga) = self.group_attachments.write() {
1808            for ids in ga.values_mut() {
1809                ids.retain(|p| p != id);
1810            }
1811            ga.retain(|_, v| !v.is_empty());
1812        }
1813        self.iam_effective_cache
1814            .write()
1815            .unwrap_or_else(|e| e.into_inner())
1816            .clear();
1817        // Issue #119: dropping a policy can shrink any caller's visible
1818        // set; clear the (tenant, role) cache so AI commands re-resolve.
1819        self.invalidate_visible_collections_cache();
1820        self.persist_iam_to_kv();
1821        Ok(())
1822    }
1823
1824    /// List all policies (id-sorted for deterministic output).
1825    pub fn list_policies(&self) -> Vec<Arc<Policy>> {
1826        let map = match self.policies.read() {
1827            Ok(g) => g,
1828            Err(_) => return Vec::new(),
1829        };
1830        let mut out: Vec<Arc<Policy>> = map.values().cloned().collect();
1831        out.sort_by(|a, b| a.id.cmp(&b.id));
1832        out
1833    }
1834
1835    /// Fetch a single policy by id.
1836    pub fn get_policy(&self, id: &str) -> Option<Arc<Policy>> {
1837        self.policies.read().ok().and_then(|m| m.get(id).cloned())
1838    }
1839
1840    /// List policies directly attached to a group.
1841    pub fn group_policies(&self, group: &str) -> Vec<Arc<Policy>> {
1842        let policies = self.policies.read();
1843        let attachments = self.group_attachments.read();
1844        let mut out = Vec::new();
1845        if let (Ok(p_map), Ok(ga_map)) = (policies, attachments) {
1846            if let Some(ids) = ga_map.get(group) {
1847                for id in ids {
1848                    if let Some(p) = p_map.get(id) {
1849                        out.push(p.clone());
1850                    }
1851                }
1852            }
1853        }
1854        out.sort_by(|a, b| a.id.cmp(&b.id));
1855        out
1856    }
1857
1858    /// Delete synthetic policies produced by SQL GRANT translation.
1859    /// REVOKE uses this to keep the IAM lane and the legacy grant table
1860    /// in lock-step.
1861    pub fn delete_synthetic_grant_policies(
1862        &self,
1863        principal: &GrantPrincipal,
1864        resource: &Resource,
1865        actions: &[Action],
1866    ) -> usize {
1867        let attached = match principal {
1868            GrantPrincipal::User(uid) => self
1869                .user_attachments
1870                .read()
1871                .ok()
1872                .and_then(|m| m.get(uid).cloned())
1873                .unwrap_or_default(),
1874            GrantPrincipal::Group(group) => self
1875                .group_attachments
1876                .read()
1877                .ok()
1878                .and_then(|m| m.get(group).cloned())
1879                .unwrap_or_default(),
1880            GrantPrincipal::Public => self
1881                .group_attachments
1882                .read()
1883                .ok()
1884                .and_then(|m| m.get(PUBLIC_IAM_GROUP).cloned())
1885                .unwrap_or_default(),
1886        };
1887        if attached.is_empty() {
1888            return 0;
1889        }
1890
1891        let mut delete_ids = Vec::new();
1892        if let Ok(policies) = self.policies.read() {
1893            for id in attached {
1894                let Some(policy) = policies.get(&id) else {
1895                    continue;
1896                };
1897                if !policy.id.starts_with("_grant_") {
1898                    continue;
1899                }
1900                if synthetic_grant_matches(policy, resource, actions) {
1901                    delete_ids.push(policy.id.clone());
1902                }
1903            }
1904        }
1905
1906        let mut deleted = 0usize;
1907        for id in delete_ids {
1908            if self.delete_policy(&id).is_ok() {
1909                deleted += 1;
1910            }
1911        }
1912        deleted
1913    }
1914
1915    /// Attach a policy to a user or group. Returns an error if the
1916    /// policy id doesn't exist.
1917    pub fn attach_policy(&self, principal: PrincipalRef, policy_id: &str) -> Result<(), AuthError> {
1918        if !self
1919            .policies
1920            .read()
1921            .map(|m| m.contains_key(policy_id))
1922            .unwrap_or(false)
1923        {
1924            return Err(AuthError::Forbidden(format!(
1925                "policy `{policy_id}` not found"
1926            )));
1927        }
1928        match &principal {
1929            PrincipalRef::User(uid) => {
1930                let mut ua = self
1931                    .user_attachments
1932                    .write()
1933                    .unwrap_or_else(|e| e.into_inner());
1934                let list = ua.entry(uid.clone()).or_default();
1935                if !list.iter().any(|p| p == policy_id) {
1936                    list.push(policy_id.to_string());
1937                }
1938                drop(ua);
1939                self.invalidate_iam_cache(Some(uid));
1940            }
1941            PrincipalRef::Group(g) => {
1942                let mut ga = self
1943                    .group_attachments
1944                    .write()
1945                    .unwrap_or_else(|e| e.into_inner());
1946                let list = ga.entry(g.clone()).or_default();
1947                if !list.iter().any(|p| p == policy_id) {
1948                    list.push(policy_id.to_string());
1949                }
1950                drop(ga);
1951                self.invalidate_iam_cache(None);
1952            }
1953        }
1954        self.persist_iam_to_kv();
1955        Ok(())
1956    }
1957
1958    /// Remove a policy attachment from a user or group.
1959    pub fn detach_policy(&self, principal: PrincipalRef, policy_id: &str) -> Result<(), AuthError> {
1960        match &principal {
1961            PrincipalRef::User(uid) => {
1962                if let Ok(mut ua) = self.user_attachments.write() {
1963                    if let Some(list) = ua.get_mut(uid) {
1964                        list.retain(|p| p != policy_id);
1965                        if list.is_empty() {
1966                            ua.remove(uid);
1967                        }
1968                    }
1969                }
1970                self.invalidate_iam_cache(Some(uid));
1971            }
1972            PrincipalRef::Group(g) => {
1973                if let Ok(mut ga) = self.group_attachments.write() {
1974                    if let Some(list) = ga.get_mut(g) {
1975                        list.retain(|p| p != policy_id);
1976                        if list.is_empty() {
1977                            ga.remove(g);
1978                        }
1979                    }
1980                }
1981                self.invalidate_iam_cache(None);
1982            }
1983        }
1984        self.persist_iam_to_kv();
1985        Ok(())
1986    }
1987
1988    /// Resolve the ordered list of effective policies for a user:
1989    /// group attachments first (least specific), then user
1990    /// attachments (most specific). Cached per user.
1991    pub fn effective_policies(&self, user: &UserId) -> Vec<Arc<Policy>> {
1992        if let Ok(cache) = self.iam_effective_cache.read() {
1993            if let Some(hit) = cache.get(user) {
1994                return hit.clone();
1995            }
1996        }
1997        let policies = self.policies.read();
1998        let user_attachments = self.user_attachments.read();
1999        let group_attachments = self.group_attachments.read();
2000        let mut groups = self
2001            .user_attributes
2002            .read()
2003            .ok()
2004            .and_then(|m| m.get(user).map(|attrs| attrs.groups.clone()))
2005            .unwrap_or_default();
2006        groups.insert(0, PUBLIC_IAM_GROUP.to_string());
2007        let mut out: Vec<Arc<Policy>> = Vec::new();
2008        if let (Ok(p_map), Ok(ua_map), Ok(ga_map)) = (policies, user_attachments, group_attachments)
2009        {
2010            for group in groups {
2011                if let Some(ids) = ga_map.get(&group) {
2012                    for id in ids {
2013                        if let Some(p) = p_map.get(id) {
2014                            out.push(p.clone());
2015                        }
2016                    }
2017                }
2018            }
2019            if let Some(ids) = ua_map.get(user) {
2020                for id in ids {
2021                    if let Some(p) = p_map.get(id) {
2022                        out.push(p.clone());
2023                    }
2024                }
2025            }
2026        }
2027        if let Ok(mut cache) = self.iam_effective_cache.write() {
2028            cache.insert(user.clone(), out.clone());
2029        }
2030        out
2031    }
2032
2033    /// Run the policy simulator for a principal. Synthesises an
2034    /// `EvalContext` from the user record + caller-supplied extras.
2035    pub fn simulate(
2036        &self,
2037        principal: &UserId,
2038        action: &str,
2039        resource: &ResourceRef,
2040        ctx_extras: SimCtx,
2041    ) -> SimulationOutcome {
2042        let user_role = self
2043            .users
2044            .read()
2045            .ok()
2046            .and_then(|u| u.get(principal).map(|u| u.role));
2047        let principal_is_admin_role = user_role == Some(Role::Admin);
2048        let now = ctx_extras.now_ms.unwrap_or_else(now_ms);
2049        let ctx = EvalContext {
2050            principal_tenant: principal.tenant.clone(),
2051            current_tenant: ctx_extras.current_tenant,
2052            peer_ip: ctx_extras.peer_ip,
2053            mfa_present: ctx_extras.mfa_present,
2054            now_ms: now,
2055            principal_is_admin_role,
2056        };
2057        let pols = self.effective_policies(principal);
2058        let refs: Vec<&Policy> = pols.iter().map(|p| p.as_ref()).collect();
2059        iam_policies::simulate(&refs, action, resource, &ctx)
2060    }
2061
2062    /// Production hot-path policy evaluation. Returns `true` on Allow
2063    /// / AdminBypass, `false` on Deny / DefaultDeny.
2064    pub fn check_policy_authz(
2065        &self,
2066        principal: &UserId,
2067        action: &str,
2068        resource: &ResourceRef,
2069        ctx: &EvalContext,
2070    ) -> bool {
2071        let pols = self.effective_policies(principal);
2072        let refs: Vec<&Policy> = pols.iter().map(|p| p.as_ref()).collect();
2073        let decision = iam_policies::evaluate(&refs, action, resource, ctx);
2074        matches!(
2075            decision,
2076            iam_policies::Decision::Allow { .. } | iam_policies::Decision::AdminBypass
2077        )
2078    }
2079
2080    /// Evaluate a resolved table projection through the column policy
2081    /// gate. Query paths should pass already-resolved column names; this
2082    /// helper intentionally does not parse SQL projection syntax.
2083    pub fn check_column_projection_authz(
2084        &self,
2085        principal: &UserId,
2086        request: &ColumnAccessRequest,
2087        ctx: &EvalContext,
2088    ) -> ColumnPolicyOutcome {
2089        let pols = self.effective_policies(principal);
2090        let refs: Vec<&Policy> = pols.iter().map(|p| p.as_ref()).collect();
2091        ColumnPolicyGate::new(&refs).evaluate(request, ctx)
2092    }
2093
2094    fn invalidate_iam_cache(&self, uid: Option<&UserId>) {
2095        if let Ok(mut cache) = self.iam_effective_cache.write() {
2096            match uid {
2097                Some(u) => {
2098                    cache.remove(u);
2099                }
2100                None => cache.clear(),
2101            }
2102        }
2103    }
2104
2105    /// Drop every effective-policy cache entry. Called from execution
2106    /// paths that mutate policies/attachments without knowing which
2107    /// users will be affected.
2108    pub fn invalidate_all_iam_cache(&self) {
2109        self.invalidate_iam_cache(None);
2110    }
2111
2112    // -----------------------------------------------------------------
2113    // IAM persistence — vault_kv backed under `red.iam.*` keys
2114    // -----------------------------------------------------------------
2115
2116    /// Reload IAM state (policies + attachments) from the vault KV.
2117    /// Replaces the legacy `rehydrate_acl` reader — pre-1.0 we drop
2118    /// the old `red.acl.*` blob format entirely.
2119    pub fn rehydrate_iam(&self) {
2120        let mut enabled = self
2121            .vault_kv_get("red.iam.enabled")
2122            .map(|v| v == "true")
2123            .unwrap_or(false);
2124        // Policies — single JSON object keyed by id.
2125        if let Some(blob) = self.vault_kv_get("red.iam.policies") {
2126            if let Ok(val) = crate::serde_json::from_str::<crate::serde_json::Value>(&blob) {
2127                if let Some(obj) = val.as_object() {
2128                    let mut map = HashMap::new();
2129                    for (id, body) in obj.iter() {
2130                        let s = body.to_string_compact();
2131                        if let Ok(p) = Policy::from_json_str(&s) {
2132                            map.insert(id.clone(), Arc::new(p));
2133                        }
2134                    }
2135                    if !map.is_empty() {
2136                        enabled = true;
2137                    }
2138                    *self.policies.write().unwrap_or_else(|e| e.into_inner()) = map;
2139                }
2140            }
2141        }
2142        // User attachments.
2143        if let Some(blob) = self.vault_kv_get("red.iam.attachments.users") {
2144            if let Ok(val) = crate::serde_json::from_str::<crate::serde_json::Value>(&blob) {
2145                if let Some(obj) = val.as_object() {
2146                    let mut map: HashMap<UserId, Vec<String>> = HashMap::new();
2147                    for (encoded_uid, ids_v) in obj.iter() {
2148                        let Some(uid) = decode_uid(encoded_uid) else {
2149                            continue;
2150                        };
2151                        if let Some(arr) = ids_v.as_array() {
2152                            let ids: Vec<String> = arr
2153                                .iter()
2154                                .filter_map(|v| v.as_str().map(|s| s.to_string()))
2155                                .collect();
2156                            map.insert(uid, ids);
2157                        }
2158                    }
2159                    *self
2160                        .user_attachments
2161                        .write()
2162                        .unwrap_or_else(|e| e.into_inner()) = map;
2163                }
2164            }
2165        }
2166        // Group attachments.
2167        if let Some(blob) = self.vault_kv_get("red.iam.attachments.groups") {
2168            if let Ok(val) = crate::serde_json::from_str::<crate::serde_json::Value>(&blob) {
2169                if let Some(obj) = val.as_object() {
2170                    let mut map: HashMap<String, Vec<String>> = HashMap::new();
2171                    for (g, ids_v) in obj.iter() {
2172                        if let Some(arr) = ids_v.as_array() {
2173                            let ids: Vec<String> = arr
2174                                .iter()
2175                                .filter_map(|v| v.as_str().map(|s| s.to_string()))
2176                                .collect();
2177                            map.insert(g.clone(), ids);
2178                        }
2179                    }
2180                    *self
2181                        .group_attachments
2182                        .write()
2183                        .unwrap_or_else(|e| e.into_inner()) = map;
2184                }
2185            }
2186        }
2187        self.iam_authorization_enabled
2188            .store(enabled, Ordering::Release);
2189        self.invalidate_iam_cache(None);
2190    }
2191
2192    /// Snapshot policies + attachments into the vault KV. Called
2193    /// after every mutation.
2194    fn persist_iam_to_kv(&self) {
2195        let enabled = if self.iam_authorization_enabled() {
2196            "true"
2197        } else {
2198            "false"
2199        };
2200        self.vault_kv_set("red.iam.enabled".to_string(), enabled.to_string());
2201
2202        // Policies: `{ "<id>": <policy_json>, ... }`
2203        let policies_obj = {
2204            let map = self.policies.read().unwrap_or_else(|e| e.into_inner());
2205            let mut obj = crate::serde_json::Map::new();
2206            for (id, p) in map.iter() {
2207                let s = p.to_json_string();
2208                if let Ok(v) = crate::serde_json::from_str::<crate::serde_json::Value>(&s) {
2209                    obj.insert(id.clone(), v);
2210                }
2211            }
2212            crate::serde_json::Value::Object(obj).to_string_compact()
2213        };
2214        self.vault_kv_set("red.iam.policies".to_string(), policies_obj);
2215
2216        // User attachments: `{ "<encoded_uid>": [ "<policy_id>", ... ], ... }`
2217        let users_obj = {
2218            let map = self
2219                .user_attachments
2220                .read()
2221                .unwrap_or_else(|e| e.into_inner());
2222            let mut obj = crate::serde_json::Map::new();
2223            for (uid, ids) in map.iter() {
2224                let arr = crate::serde_json::Value::Array(
2225                    ids.iter()
2226                        .map(|s| crate::serde_json::Value::String(s.clone()))
2227                        .collect(),
2228                );
2229                obj.insert(encode_uid(uid), arr);
2230            }
2231            crate::serde_json::Value::Object(obj).to_string_compact()
2232        };
2233        self.vault_kv_set("red.iam.attachments.users".to_string(), users_obj);
2234
2235        // Group attachments.
2236        let groups_obj = {
2237            let map = self
2238                .group_attachments
2239                .read()
2240                .unwrap_or_else(|e| e.into_inner());
2241            let mut obj = crate::serde_json::Map::new();
2242            for (g, ids) in map.iter() {
2243                let arr = crate::serde_json::Value::Array(
2244                    ids.iter()
2245                        .map(|s| crate::serde_json::Value::String(s.clone()))
2246                        .collect(),
2247                );
2248                obj.insert(g.clone(), arr);
2249            }
2250            crate::serde_json::Value::Object(obj).to_string_compact()
2251        };
2252        self.vault_kv_set("red.iam.attachments.groups".to_string(), groups_obj);
2253    }
2254}
2255
2256fn synthetic_grant_matches(policy: &Policy, resource: &Resource, actions: &[Action]) -> bool {
2257    policy.statements.iter().any(|st| {
2258        st.effect == crate::auth::policies::Effect::Allow
2259            && st.condition.is_none()
2260            && grant_actions_overlap(&st.actions, actions)
2261            && grant_resource_matches(&st.resources, resource)
2262    })
2263}
2264
2265fn grant_actions_overlap(
2266    patterns: &[crate::auth::policies::ActionPattern],
2267    actions: &[Action],
2268) -> bool {
2269    if actions.contains(&Action::All) {
2270        return true;
2271    }
2272    patterns.iter().any(|pat| match pat {
2273        crate::auth::policies::ActionPattern::Wildcard => true,
2274        crate::auth::policies::ActionPattern::Exact(s) => {
2275            actions.iter().any(|a| s.eq_ignore_ascii_case(a.as_str()))
2276        }
2277        crate::auth::policies::ActionPattern::Prefix(_) => false,
2278    })
2279}
2280
2281fn grant_resource_matches(
2282    patterns: &[crate::auth::policies::ResourcePattern],
2283    resource: &Resource,
2284) -> bool {
2285    let expected = grant_resource_pattern(resource);
2286    patterns.iter().any(|pat| pat == &expected)
2287}
2288
2289fn grant_resource_pattern(resource: &Resource) -> crate::auth::policies::ResourcePattern {
2290    use crate::auth::policies::ResourcePattern;
2291
2292    match resource {
2293        Resource::Database => ResourcePattern::Glob("table:*".to_string()),
2294        Resource::Schema(s) => ResourcePattern::Glob(format!("table:{s}.*")),
2295        Resource::Table { schema, table } => ResourcePattern::Exact {
2296            kind: "table".to_string(),
2297            name: match schema {
2298                Some(s) => format!("{s}.{table}"),
2299                None => table.clone(),
2300            },
2301        },
2302        Resource::Function { schema, name } => ResourcePattern::Exact {
2303            kind: "function".to_string(),
2304            name: match schema {
2305                Some(s) => format!("{s}.{name}"),
2306                None => name.clone(),
2307            },
2308        },
2309    }
2310}
2311
2312// ===========================================================================
2313// ACL serialization helpers — line-oriented, human-readable so an
2314// operator inspecting the vault dump can spot misconfigurations.
2315//
2316// Format (one record per line):
2317//   GRANT|<resource>|<actions_csv>|<with_grant_option>|<tenant_or_*>|<granted_by>|<granted_at>
2318//   ATTR|<valid_until>|<connection_limit>|<search_path>
2319//
2320// Resources are encoded as:
2321//   db                          → Database
2322//   schema:<name>               → Schema(name)
2323//   table:<schema_or_*>:<name>  → Table { schema, table }
2324//   func:<schema_or_*>:<name>   → Function { schema, name }
2325// ===========================================================================
2326
2327fn encode_uid(uid: &UserId) -> String {
2328    match &uid.tenant {
2329        Some(t) => format!("{}/{}", t, uid.username),
2330        None => format!("*/{}", uid.username),
2331    }
2332}
2333
2334fn decode_uid(s: &str) -> Option<UserId> {
2335    let (tenant, username) = s.split_once('/')?;
2336    Some(if tenant == "*" {
2337        UserId::platform(username)
2338    } else {
2339        UserId::scoped(tenant, username)
2340    })
2341}
2342
2343fn encode_resource(r: &Resource) -> String {
2344    match r {
2345        Resource::Database => "db".into(),
2346        Resource::Schema(s) => format!("schema:{}", s),
2347        Resource::Table { schema, table } => {
2348            format!("table:{}:{}", schema.as_deref().unwrap_or("*"), table)
2349        }
2350        Resource::Function { schema, name } => {
2351            format!("func:{}:{}", schema.as_deref().unwrap_or("*"), name)
2352        }
2353    }
2354}
2355
2356fn decode_resource(s: &str) -> Option<Resource> {
2357    if s == "db" {
2358        return Some(Resource::Database);
2359    }
2360    if let Some(rest) = s.strip_prefix("schema:") {
2361        return Some(Resource::Schema(rest.to_string()));
2362    }
2363    if let Some(rest) = s.strip_prefix("table:") {
2364        let (schema, table) = rest.split_once(':')?;
2365        return Some(Resource::Table {
2366            schema: if schema == "*" {
2367                None
2368            } else {
2369                Some(schema.to_string())
2370            },
2371            table: table.to_string(),
2372        });
2373    }
2374    if let Some(rest) = s.strip_prefix("func:") {
2375        let (schema, name) = rest.split_once(':')?;
2376        return Some(Resource::Function {
2377            schema: if schema == "*" {
2378                None
2379            } else {
2380                Some(schema.to_string())
2381            },
2382            name: name.to_string(),
2383        });
2384    }
2385    None
2386}
2387
2388fn encode_grants_blob(grants: &[Grant]) -> String {
2389    let mut out = String::new();
2390    for g in grants {
2391        let actions: Vec<&str> = g.actions.iter().map(|a| a.as_str()).collect();
2392        out.push_str(&format!(
2393            "GRANT|{}|{}|{}|{}|{}|{}\n",
2394            encode_resource(&g.resource),
2395            actions.join(","),
2396            g.with_grant_option,
2397            g.tenant.as_deref().unwrap_or("*"),
2398            g.granted_by,
2399            g.granted_at,
2400        ));
2401    }
2402    out
2403}
2404
2405fn decode_grants_blob(s: &str) -> Option<Vec<Grant>> {
2406    let mut out = Vec::new();
2407    for line in s.lines() {
2408        if line.is_empty() {
2409            continue;
2410        }
2411        let parts: Vec<&str> = line.split('|').collect();
2412        if parts.len() != 7 || parts[0] != "GRANT" {
2413            return None;
2414        }
2415        let resource = decode_resource(parts[1])?;
2416        let mut actions = std::collections::BTreeSet::new();
2417        for token in parts[2].split(',') {
2418            if let Some(a) = Action::from_keyword(token) {
2419                actions.insert(a);
2420            }
2421        }
2422        let with_grant_option = parts[3] == "true";
2423        let tenant = if parts[4] == "*" {
2424            None
2425        } else {
2426            Some(parts[4].to_string())
2427        };
2428        let granted_by = parts[5].to_string();
2429        let granted_at: u128 = parts[6].parse().unwrap_or(0);
2430        out.push(Grant {
2431            // Principal field is reconstructed by the loader from the
2432            // storage-key prefix; default to `Public` here.
2433            principal: GrantPrincipal::Public,
2434            resource,
2435            actions,
2436            with_grant_option,
2437            granted_by,
2438            granted_at,
2439            tenant,
2440            columns: None,
2441        });
2442    }
2443    Some(out)
2444}
2445
2446fn encode_attrs_blob(a: &UserAttributes) -> String {
2447    let valid = a
2448        .valid_until
2449        .map(|t| t.to_string())
2450        .unwrap_or_else(|| "*".into());
2451    let limit = a
2452        .connection_limit
2453        .map(|l| l.to_string())
2454        .unwrap_or_else(|| "*".into());
2455    let path = a.search_path.clone().unwrap_or_else(|| "*".into());
2456    let groups = if a.groups.is_empty() {
2457        "*".to_string()
2458    } else {
2459        a.groups.join(",")
2460    };
2461    format!("ATTR|{}|{}|{}|{}\n", valid, limit, path, groups)
2462}
2463
2464fn decode_attrs_blob(s: &str) -> Option<UserAttributes> {
2465    let line = s.lines().next()?;
2466    let parts: Vec<&str> = line.split('|').collect();
2467    if !(parts.len() == 4 || parts.len() == 5) || parts[0] != "ATTR" {
2468        return None;
2469    }
2470    let groups = if parts.get(4).copied().unwrap_or("*") == "*" {
2471        Vec::new()
2472    } else {
2473        parts[4]
2474            .split(',')
2475            .filter(|g| !g.is_empty())
2476            .map(|g| g.to_string())
2477            .collect()
2478    };
2479    Some(UserAttributes {
2480        valid_until: if parts[1] == "*" {
2481            None
2482        } else {
2483            parts[1].parse().ok()
2484        },
2485        connection_limit: if parts[2] == "*" {
2486            None
2487        } else {
2488            parts[2].parse().ok()
2489        },
2490        search_path: if parts[3] == "*" {
2491            None
2492        } else {
2493            Some(parts[3].to_string())
2494        },
2495        groups,
2496    })
2497}
2498
2499// ===========================================================================
2500// Password hashing
2501// ===========================================================================
2502
2503/// Derive a SCRAM-SHA-256 verifier for a fresh user / password
2504/// rotation. Salt is 16 random bytes; iter is the engine default
2505/// (`scram::DEFAULT_ITER`). Stored alongside the Argon2 password
2506/// hash so HTTP login + v2 SCRAM can both authenticate the same
2507/// user.
2508fn make_scram_verifier(password: &str) -> crate::auth::scram::ScramVerifier {
2509    let salt = random_bytes(16);
2510    crate::auth::scram::ScramVerifier::from_password(
2511        password,
2512        salt,
2513        crate::auth::scram::DEFAULT_ITER,
2514    )
2515}
2516
2517/// Hash a password using Argon2id.
2518///
2519/// Format: `argon2id$<salt_hex>$<hash_hex>`
2520pub(crate) fn hash_password(password: &str) -> String {
2521    let salt = random_bytes(16);
2522    let params = auth_argon2_params();
2523    let hash = derive_key(password.as_bytes(), &salt, &params);
2524    format!("argon2id${}${}", hex::encode(&salt), hex::encode(&hash))
2525}
2526
2527/// Verify a password against a stored `argon2id$<salt>$<hash>` string.
2528pub(crate) fn verify_password(password: &str, stored_hash: &str) -> bool {
2529    let parts: Vec<&str> = stored_hash.splitn(3, '$').collect();
2530    if parts.len() != 3 || parts[0] != "argon2id" {
2531        return false;
2532    }
2533
2534    let salt = match hex::decode(parts[1]) {
2535        Ok(s) => s,
2536        Err(_) => return false,
2537    };
2538
2539    let expected_hash = match hex::decode(parts[2]) {
2540        Ok(h) => h,
2541        Err(_) => return false,
2542    };
2543
2544    let params = auth_argon2_params();
2545    let computed = derive_key(password.as_bytes(), &salt, &params);
2546    constant_time_eq(&computed, &expected_hash)
2547}
2548
2549/// Constant-time byte comparison to avoid timing side-channels.
2550fn constant_time_eq(a: &[u8], b: &[u8]) -> bool {
2551    if a.len() != b.len() {
2552        return false;
2553    }
2554    let mut diff: u8 = 0;
2555    for (x, y) in a.iter().zip(b.iter()) {
2556        diff |= x ^ y;
2557    }
2558    diff == 0
2559}
2560
2561// ===========================================================================
2562// Token generation
2563// ===========================================================================
2564
2565fn generate_session_token() -> String {
2566    format!("rs_{}", hex::encode(random_bytes(32)))
2567}
2568
2569fn generate_api_key() -> String {
2570    format!("rk_{}", hex::encode(random_bytes(32)))
2571}
2572
2573/// Generate `n` random bytes and return as a hex string.
2574fn random_hex(n: usize) -> String {
2575    hex::encode(random_bytes(n))
2576}
2577
2578/// Generate `n` cryptographically random bytes using the OS CSPRNG,
2579/// then mix with SHA-256 for domain separation.
2580pub(crate) fn random_bytes(n: usize) -> Vec<u8> {
2581    let mut buf = vec![0u8; n.max(32)];
2582    if os_random::fill_bytes(&mut buf).is_err() {
2583        // Fallback: use system time and pointers as entropy (best-effort).
2584        let seed = now_ms().to_le_bytes();
2585        for (i, byte) in buf.iter_mut().enumerate() {
2586            *byte = seed[i % seed.len()] ^ (i as u8);
2587        }
2588    }
2589    // SHA-256 mix to ensure uniform distribution.
2590    let digest = sha256(&buf);
2591    if n <= 32 {
2592        digest[..n].to_vec()
2593    } else {
2594        // Chain SHA-256 for longer outputs (unusual but supported).
2595        let mut out = Vec::with_capacity(n);
2596        let mut prev = digest;
2597        while out.len() < n {
2598            out.extend_from_slice(&prev[..std::cmp::min(32, n - out.len())]);
2599            prev = sha256(&prev);
2600        }
2601        out
2602    }
2603}
2604
2605// ===========================================================================
2606// Helpers
2607// ===========================================================================
2608
2609fn lock_err<T>(_: T) -> AuthError {
2610    AuthError::Internal("lock poisoned".to_string())
2611}
2612
2613fn reject_system_owned(uid: &UserId, user: &User) -> Result<(), AuthError> {
2614    if user.system_owned {
2615        return Err(AuthError::SystemUserImmutable {
2616            username: uid.to_string(),
2617        });
2618    }
2619    Ok(())
2620}
2621
2622// ===========================================================================
2623// Tests
2624// ===========================================================================
2625
2626#[cfg(test)]
2627mod tests {
2628    use super::*;
2629
2630    fn test_config() -> AuthConfig {
2631        AuthConfig {
2632            enabled: true,
2633            session_ttl_secs: 60,
2634            require_auth: true,
2635            auto_encrypt_storage: false,
2636            vault_enabled: false,
2637            cert: Default::default(),
2638            oauth: Default::default(),
2639        }
2640    }
2641
2642    #[test]
2643    fn test_create_and_list_users() {
2644        let store = AuthStore::new(test_config());
2645        store.create_user("alice", "pass1", Role::Admin).unwrap();
2646        store.create_user("bob", "pass2", Role::Read).unwrap();
2647
2648        let users = store.list_users();
2649        assert_eq!(users.len(), 2);
2650        // Password hashes should be redacted.
2651        for u in &users {
2652            assert!(u.password_hash.is_empty());
2653        }
2654    }
2655
2656    #[test]
2657    fn test_create_duplicate_user() {
2658        let store = AuthStore::new(test_config());
2659        store.create_user("alice", "pass", Role::Admin).unwrap();
2660        let err = store.create_user("alice", "pass2", Role::Read).unwrap_err();
2661        assert!(matches!(err, AuthError::UserExists(_)));
2662    }
2663
2664    #[test]
2665    fn test_authenticate_and_validate() {
2666        let store = AuthStore::new(test_config());
2667        store.create_user("alice", "secret", Role::Write).unwrap();
2668
2669        let session = store.authenticate("alice", "secret").unwrap();
2670        assert!(session.token.starts_with("rs_"));
2671
2672        let (username, role) = store.validate_token(&session.token).unwrap();
2673        assert_eq!(username, "alice");
2674        assert_eq!(role, Role::Write);
2675    }
2676
2677    #[test]
2678    fn test_authenticate_wrong_password() {
2679        let store = AuthStore::new(test_config());
2680        store.create_user("alice", "secret", Role::Read).unwrap();
2681
2682        let err = store.authenticate("alice", "wrong").unwrap_err();
2683        assert!(matches!(err, AuthError::InvalidCredentials));
2684    }
2685
2686    #[test]
2687    fn test_api_key_lifecycle() {
2688        let store = AuthStore::new(test_config());
2689        store.create_user("alice", "pass", Role::Admin).unwrap();
2690
2691        let key = store
2692            .create_api_key("alice", "ci-token", Role::Write)
2693            .unwrap();
2694        assert!(key.key.starts_with("rk_"));
2695
2696        let (username, role) = store.validate_token(&key.key).unwrap();
2697        assert_eq!(username, "alice");
2698        assert_eq!(role, Role::Write);
2699
2700        store.revoke_api_key(&key.key).unwrap();
2701        assert!(store.validate_token(&key.key).is_none());
2702    }
2703
2704    #[test]
2705    fn test_api_key_role_exceeded() {
2706        let store = AuthStore::new(test_config());
2707        store.create_user("bob", "pass", Role::Read).unwrap();
2708
2709        let err = store
2710            .create_api_key("bob", "escalate", Role::Admin)
2711            .unwrap_err();
2712        assert!(matches!(err, AuthError::RoleExceeded { .. }));
2713    }
2714
2715    #[test]
2716    fn test_change_password() {
2717        let store = AuthStore::new(test_config());
2718        store.create_user("alice", "old", Role::Write).unwrap();
2719
2720        store.change_password("alice", "old", "new").unwrap();
2721
2722        // Old password should fail.
2723        assert!(store.authenticate("alice", "old").is_err());
2724        // New password should succeed.
2725        assert!(store.authenticate("alice", "new").is_ok());
2726    }
2727
2728    #[test]
2729    fn test_change_role() {
2730        let store = AuthStore::new(test_config());
2731        store.create_user("alice", "pass", Role::Admin).unwrap();
2732        store.create_api_key("alice", "key1", Role::Admin).unwrap();
2733
2734        store.change_role("alice", Role::Read).unwrap();
2735
2736        // User's role should be Read now.
2737        let users = store.list_users();
2738        let alice = users.iter().find(|u| u.username == "alice").unwrap();
2739        assert_eq!(alice.role, Role::Read);
2740
2741        // API keys should have been downgraded.
2742        assert_eq!(alice.api_keys[0].role, Role::Read);
2743    }
2744
2745    #[test]
2746    fn test_system_owned_user_blocks_destructive_mutations() {
2747        let store = AuthStore::new(test_config());
2748        store
2749            .create_system_user("system", "pass", Role::Admin, None)
2750            .unwrap();
2751
2752        let uid = UserId::platform("system");
2753        let err = store.delete_user("system").unwrap_err();
2754        assert!(matches!(err, AuthError::SystemUserImmutable { .. }));
2755
2756        let err = store.change_password("system", "pass", "new").unwrap_err();
2757        assert!(matches!(err, AuthError::SystemUserImmutable { .. }));
2758
2759        let err = store.change_role("system", Role::Read).unwrap_err();
2760        assert!(matches!(err, AuthError::SystemUserImmutable { .. }));
2761
2762        let err = store.set_user_enabled(&uid, false).unwrap_err();
2763        assert!(matches!(err, AuthError::SystemUserImmutable { .. }));
2764
2765        let key = store
2766            .create_api_key("system", "rotation", Role::Admin)
2767            .unwrap();
2768        assert!(store.validate_token(&key.key).is_some());
2769        store.revoke_api_key(&key.key).unwrap();
2770        assert!(store.validate_token(&key.key).is_none());
2771    }
2772
2773    #[test]
2774    fn test_regular_user_mutations_still_work() {
2775        let store = AuthStore::new(test_config());
2776        store.create_user("alice", "old", Role::Admin).unwrap();
2777
2778        let uid = UserId::platform("alice");
2779        store.set_user_enabled(&uid, false).unwrap();
2780        assert!(matches!(
2781            store.authenticate("alice", "old"),
2782            Err(AuthError::InvalidCredentials)
2783        ));
2784
2785        store.set_user_enabled(&uid, true).unwrap();
2786        store.change_password("alice", "old", "new").unwrap();
2787        store.change_role("alice", Role::Read).unwrap();
2788        store.delete_user("alice").unwrap();
2789        assert!(matches!(
2790            store.authenticate("alice", "new"),
2791            Err(AuthError::InvalidCredentials)
2792        ));
2793    }
2794
2795    #[test]
2796    fn test_delete_user() {
2797        let store = AuthStore::new(test_config());
2798        store.create_user("alice", "pass", Role::Admin).unwrap();
2799        let key = store.create_api_key("alice", "key1", Role::Read).unwrap();
2800        let session = store.authenticate("alice", "pass").unwrap();
2801
2802        store.delete_user("alice").unwrap();
2803
2804        assert!(store.validate_token(&key.key).is_none());
2805        assert!(store.validate_token(&session.token).is_none());
2806        assert!(store.list_users().is_empty());
2807    }
2808
2809    #[test]
2810    fn test_revoke_session() {
2811        let store = AuthStore::new(test_config());
2812        store.create_user("alice", "pass", Role::Read).unwrap();
2813        let session = store.authenticate("alice", "pass").unwrap();
2814
2815        store.revoke_session(&session.token);
2816        assert!(store.validate_token(&session.token).is_none());
2817    }
2818
2819    #[test]
2820    fn test_password_hash_format() {
2821        let hash = hash_password("test");
2822        assert!(hash.starts_with("argon2id$"));
2823        let parts: Vec<&str> = hash.splitn(3, '$').collect();
2824        assert_eq!(parts.len(), 3);
2825        // Salt is 16 bytes = 32 hex chars.
2826        assert_eq!(parts[1].len(), 32);
2827        // Hash is 32 bytes = 64 hex chars.
2828        assert_eq!(parts[2].len(), 64);
2829    }
2830
2831    #[test]
2832    fn test_constant_time_eq() {
2833        assert!(constant_time_eq(b"hello", b"hello"));
2834        assert!(!constant_time_eq(b"hello", b"world"));
2835        assert!(!constant_time_eq(b"short", b"longer"));
2836    }
2837
2838    #[test]
2839    fn test_bootstrap_seals_permanently() {
2840        let store = AuthStore::new(test_config());
2841
2842        assert!(store.needs_bootstrap());
2843        assert!(!store.is_bootstrapped());
2844
2845        // First bootstrap succeeds
2846        let result = store.bootstrap("admin", "secret");
2847        assert!(result.is_ok());
2848        let br = result.unwrap();
2849        assert_eq!(br.user.username, "admin");
2850        assert_eq!(br.user.role, Role::Admin);
2851        assert!(br.api_key.key.starts_with("rk_"));
2852        // No vault configured, so no certificate.
2853        assert!(br.certificate.is_none());
2854
2855        // Sealed now
2856        assert!(!store.needs_bootstrap());
2857        assert!(store.is_bootstrapped());
2858
2859        // Second bootstrap fails -- sealed permanently
2860        let result = store.bootstrap("admin2", "secret2");
2861        assert!(result.is_err());
2862        let err = result.unwrap_err();
2863        assert!(err.to_string().contains("sealed permanently"));
2864
2865        // Only 1 user exists (the first one)
2866        assert_eq!(store.list_users().len(), 1);
2867        assert_eq!(store.list_users()[0].username, "admin");
2868    }
2869
2870    #[test]
2871    fn test_bootstrap_after_manual_user_creation() {
2872        let store = AuthStore::new(test_config());
2873
2874        // Create a user manually first
2875        store.create_user("existing", "pass", Role::Read).unwrap();
2876
2877        // Bootstrap sees the seal hasn't been set but users exist
2878        // The atomic seal fires first, then the users check catches it
2879        assert!(!store.needs_bootstrap()); // users exist → false
2880    }
2881
2882    // ---------------------------------------------------------------
2883    // Tenant scoping
2884    // ---------------------------------------------------------------
2885
2886    #[test]
2887    fn test_same_username_two_tenants_distinct() {
2888        let store = AuthStore::new(test_config());
2889        store
2890            .create_user_in_tenant(Some("acme"), "alice", "pw-acme", Role::Write)
2891            .unwrap();
2892        store
2893            .create_user_in_tenant(Some("globex"), "alice", "pw-globex", Role::Read)
2894            .unwrap();
2895
2896        // Two distinct users.
2897        let users = store.list_users();
2898        assert_eq!(users.len(), 2);
2899
2900        // Each verifies its own password under its own tenant.
2901        assert!(store
2902            .authenticate_in_tenant(Some("acme"), "alice", "pw-acme")
2903            .is_ok());
2904        assert!(store
2905            .authenticate_in_tenant(Some("globex"), "alice", "pw-globex")
2906            .is_ok());
2907
2908        // Cross-tenant credentials are rejected.
2909        assert!(store
2910            .authenticate_in_tenant(Some("acme"), "alice", "pw-globex")
2911            .is_err());
2912        assert!(store
2913            .authenticate_in_tenant(Some("globex"), "alice", "pw-acme")
2914            .is_err());
2915    }
2916
2917    #[test]
2918    fn test_session_carries_tenant() {
2919        let store = AuthStore::new(test_config());
2920        store
2921            .create_user_in_tenant(Some("acme"), "alice", "pw", Role::Admin)
2922            .unwrap();
2923        let session = store
2924            .authenticate_in_tenant(Some("acme"), "alice", "pw")
2925            .unwrap();
2926        assert_eq!(session.tenant_id.as_deref(), Some("acme"));
2927
2928        let (id, role) = store.validate_token_full(&session.token).unwrap();
2929        assert_eq!(id.tenant.as_deref(), Some("acme"));
2930        assert_eq!(id.username, "alice");
2931        assert_eq!(role, Role::Admin);
2932    }
2933
2934    #[test]
2935    fn test_platform_user_has_no_tenant() {
2936        let store = AuthStore::new(test_config());
2937        store.create_user("admin", "pw", Role::Admin).unwrap();
2938        let session = store.authenticate("admin", "pw").unwrap();
2939        assert!(session.tenant_id.is_none());
2940
2941        let (id, _) = store.validate_token_full(&session.token).unwrap();
2942        assert!(id.tenant.is_none());
2943    }
2944
2945    #[test]
2946    fn test_lookup_scram_verifier_global_resolves_platform() {
2947        let store = AuthStore::new(test_config());
2948        store.create_user("admin", "pw", Role::Admin).unwrap();
2949        store
2950            .create_user_in_tenant(Some("acme"), "admin", "pw", Role::Admin)
2951            .unwrap();
2952
2953        // The global helper picks the platform-tenant user only.
2954        let v = store.lookup_scram_verifier_global("admin");
2955        assert!(v.is_some());
2956
2957        // The tenant-scoped user has its own verifier.
2958        let v_acme = store.lookup_scram_verifier(&UserId::scoped("acme", "admin"));
2959        assert!(v_acme.is_some());
2960
2961        // The two verifiers carry independent salts.
2962        assert_ne!(v.unwrap().salt, v_acme.unwrap().salt);
2963    }
2964
2965    #[test]
2966    fn test_delete_in_tenant_does_not_touch_other_tenant() {
2967        let store = AuthStore::new(test_config());
2968        store
2969            .create_user_in_tenant(Some("acme"), "alice", "pw", Role::Admin)
2970            .unwrap();
2971        store
2972            .create_user_in_tenant(Some("globex"), "alice", "pw", Role::Admin)
2973            .unwrap();
2974
2975        store.delete_user_in_tenant(Some("acme"), "alice").unwrap();
2976
2977        // Globex still alive.
2978        assert!(store
2979            .authenticate_in_tenant(Some("globex"), "alice", "pw")
2980            .is_ok());
2981        // Acme gone.
2982        assert!(store
2983            .authenticate_in_tenant(Some("acme"), "alice", "pw")
2984            .is_err());
2985    }
2986
2987    #[test]
2988    fn test_user_id_display() {
2989        assert_eq!(UserId::platform("admin").to_string(), "admin");
2990        assert_eq!(UserId::scoped("acme", "alice").to_string(), "acme/alice");
2991    }
2992}